0% found this document useful (0 votes)
6 views

Java Programming - Delegate Pack

The document provides an overview of Java programming, including its history, applications, and fundamental concepts such as data types, operators, and object-oriented programming principles. It outlines the course syllabus for a Java programming course, detailing various modules covering topics from Java fundamentals to advanced features like Swing and JavaFX. Additionally, it explains key concepts like bytecode, variables, and the importance of data types in Java.

Uploaded by

ruchi solani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Java Programming - Delegate Pack

The document provides an overview of Java programming, including its history, applications, and fundamental concepts such as data types, operators, and object-oriented programming principles. It outlines the course syllabus for a Java programming course, detailing various modules covering topics from Java fundamentals to advanced features like Swing and JavaFX. Additionally, it explains key concepts like bytecode, variables, and the importance of data types in Java.

Uploaded by

ruchi solani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 426

theknowledgeacademy

Java Programming
theknowledgeacademy

About Us

The world's largest provider of classroom and online


training courses
 World Class Training Solutions
 Subject Matter Experts
 Highest Quality Training Material
 Accelerated Learning Techniques
 Project, Programme, and Change Management, ITIL®
Consultancy
 Bespoke Tailor Made Training Solutions
 PRINCE2®, MSP®, ITIL®, Soft Skills, and More
theknowledgeacademy Course Syllabus
Module 1: Java Fundamentals 5

Module 2: Data Types and Operators 25

Module 3: Program Control Statements 58

Module 4: Classes, Objects, Methods 86

Module 5: More Data Types and Operators 109

Module 6: Closer look at Methods and Classes 131

Module 7: Inheritance 156

Module 8: : Packages and Interfaces 188


theknowledgeacademy Course Syllabus
Module 9: Exception Handling 215

Module 10: Using I/O 243

Module 11: Multithreaded Programming 281

Module 12: Enumerations, Autoboxing, 312


Static Import, Annotations

Module 13: Generics 342

Module 14: Swing 366

Module 15: JavaFX 397


Module 1: Java Fundamentals

theknowledgeacademy
5
What is Java?
• Java is a computer programming language that has essentially become the language of
the internet

• Java includes tools and platforms that aid in the development of programs

• Java relates to the C, C++ and C# frameworks, but is slightly easier to use

Types of Java Applications

01 02 03 04
Standalone Web
Applications Enterprise Applications Applications Mobile Applications

theknowledgeacademy
6
What is Java?
1. Standalone Applications: It uses Graphical User Interface(GUI) components like AWT,
Swing, and JavaFX. These components include buttons, list, menu, scroll panel, etc. It is
also called desktop alienations

2. Enterprise Applications: An application that is distributed in nature is called an


enterprise application

3. Web Applications: An application that runs on the server is called a web application.
For creating web applications, technologies like JSP, Servlet, Spring, and Hibernate are
used

4. Mobile Applications: Java ME (Micro Edition) is a cross-platform to create mobile


applications which run across smartphones. Java is a platform for App Development in
Android

theknowledgeacademy
7
How it all began
• The first Java program Java 1.0 was released in 1995 by Sun Microsystems, Inc

• Development was started by James Gosling, Patrick Naughton, Chris Warth, Ed Frank,
and Mike Sheridan at Sun Microsystems in 1991

• Firstly, it was called Oak. It was initially designed as a platform-independent language,


to be used in consumer electronic devices

theknowledgeacademy
8
Change of Direction

So they switched
The Web
In the early 90s In 1993 Java’s direction and
demanded
we saw the design team began to create
portable
introduction of realised that this Java for the
programmes due
the World Wide was a high, in- Internet rather
to its diverse
Web demand issue than the
universe
electronic good

theknowledgeacademy
9
Java and the Internet
Java’s contribution to the Internet was profound:

• Ultimately it transformed the Web into a highly interactive environment

• It offered a solution of portability and security, allowing use of the same code on any
computer. It simplified web programming

• It set a new standard in computer language design, and has been at the head of
development ever since

theknowledgeacademy
10
Java and Program Solutions for the Internet
Security

• Security problems needed to be addressed to prevent virus programs from searching


the contents of a users computer

• To address this Java found a way to confine the applet to the Java execution
environment, not allowing it to access other parts of the computer, thus preventing
malicious attacks

• This was a revolution in internet security

theknowledgeacademy
11
Java and the Internet

Bytecode essentially allowed


Java introduced a major
Java to run on any computer,
solution to portability in the
where the same code could be
Internet sphere: Bytecode
accessed by multiple operating
systems

theknowledgeacademy
12
What is Bytecode?
• Bytecode is a sequence of instructions designed to be implemented by the Java Virtual
Machine

• It is not executable code

• It is designed to be run by the Java run-time system (Java Virtual Machine)

• Translating a Java Program into bytecode makes it easier to run a program in a diverse
range of environments

• Bytecodes enable programs running through the JVM to be executed much quicker

• HotSpot Technology: Provides a just-in-time compiler for bytecode. A JIT compiler


compiles code as it is needed during execution

theknowledgeacademy
13
Object-Oriented Programming
• Structured Programming made it easier to write moderately complex programs by using
subroutines, local variables, and rich control constructs

• It did however have limits with large projects. OOP was created to be able to handle
them

• Taking the best elements of Structured Programming and reorganising them to make
data the priority

theknowledgeacademy
14
Object-Oriented Programming
Principles of OOP

1 2 3 4

Encapsulation Polymorphism Inheritance Abstraction

theknowledgeacademy
15
Object-Oriented Programming
1. Encapsulation: It is a mechanism that binds code and data together, creating an object,
becoming a self-contained single object, enabling restrictions of access to that object

2. Polymorphism: It is a quality that allows one interface to access a general class of


actions and multiple methods, reducing complexity

3. Inheritance: It is a process in which one object can acquire the properties of another
object, meaning better data analysis, reduces time, and ensures more accurate coding

4. Abstraction: It is an extension of encapsulation. It provides important information to


the outside world while hiding the internal details of implementation

theknowledgeacademy
16
Basic Program
• Entering the Program: Name of source file is Sample.file. The name you give your
source file is vital. It contains class definitions. It makes maintaining programs easier

• Compiling the Program: Use javac to compile. This creates a file that contains the
bytecode of the program

• Running the Program: Check your program runs ok, are there any syntax errors? Always
double check an error message to evaluate the problem

theknowledgeacademy
17
Basic Program
• Example:

theknowledgeacademy
18
Variables
• Programs function by manipulating data placed in memory

• The data is given a name and a value, known as a Variable

• It is a named memory location that can be changed during programming

• The type of values that a variable holds needs to be specified

• We use int. to establish this. All variables must also be declared before they are used

theknowledgeacademy
19
Variables
Example: Create a variable called name of type String and assign it the value ”ABC”

theknowledgeacademy
20
Code Block
• A grouping of two or more statements, enclosed by a matched pair of curly braces { }

• The curly braces mark the beginning and the end of a piece of code

• A block of code becomes a logical unit

• It can be used any place that a single statement can

• E.g. Can be a target for if and for statements

• Code blocks simplify coding so it is effective for increasing the speed and efficiency of a
program

theknowledgeacademy
21
Semicolon and Braces
• Semicolons are used as separators and predominantly to end a statement ;

• A block of code cannot be terminated in this way because it is made up of a group of


statements

• So instead a closing brace is introduced )

• This is also used as a separator the same way as the semicolon

• Indentations became accepted, recommended indentation style for readable programs

theknowledgeacademy
22
Keywords & Identifiers

Abstract Continue For New Throws


Abstract Default Goto Package Transient
Assert Do If Private Try
Boolean Double Implements Protected Void
Break Else Import Public Volatile
Byte Enum Instanceof Return While
Case Extends Int Synchronized
Catch Final Interface Void
Char Finally Long This
Class Float Native Throw

theknowledgeacademy
23
Exercise

What is Java?
Which is the latest Java version?
What is Bytecode?
What is Code Block?

theknowledgeacademy
24
Module 2: Data Types and Operators

theknowledgeacademy
25
Data Types and Operators
• Data types and operators are at the
foundation of any programming language

• They define the limits of a language and


the kind of tasks it can be applied to

• Java is suitable for any type of


programming because it supports a large
collection of data types and operators

theknowledgeacademy
26
Data Types
• A data type represents data’s type which
you can process by using a computer
program. It can be alphanumeric, decimal,
numeric, etc.

• A classification of the type of data that a


variable or object can have and what
operations can be performed

• There is no concept of a type-less variable,


expression or value

theknowledgeacademy
27
Java’s Primitive Types
• There are 8 primitive types of data that are at the core of Java. All of Java’s other data
types are constructed from these:

Type Meaning
boolean Represents true/false values
byte 8-bit integer
char Character
double Double-precision floating point
float Single-precision floating point
int Integer
long Long integer
short Short integer

theknowledgeacademy
28
Integers
• Java defines four integer types that are signed positive and negative values:

Type Width in Bits Range

byte 8 -128 to 127

short 16 -32,768 to 32,767

int 32 -2,147,486,648 to 2,147,483,647

long 64 -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807

theknowledgeacademy
29
Integers
• int is the most commonly used integer type. Variables of int are often employed to:

o Control loops

o Index arrays

o Perform general-purpose integer math

theknowledgeacademy
30
Integers

long is used when you


have a range that is
greater than int

byte type is the Variables of short


smallest integer type are used
type. Variables of when the larger
which are valuable
when working with
int range are not
raw binary data needed

theknowledgeacademy
31
Floating-Point Types
• Java has two kinds of floating-point types:

o Float: represent single-precision numbers

o Double: represent double-precision numbers

• These types can represent numbers that have fractional components, which integers
cannot

• Type float is 32 bits wide whereas type double is 64 bits wide

theknowledgeacademy
32
Floating-Point Types

All of the math functions


in Java’s class library use
double values, so double
type is most commonly
used
On the next slide sqrt( )
is used to compute the
length of the
hypotenuse, given the
lengths of the two
opposing sides

theknowledgeacademy
33
Floating-Point Types
• Use the Pythagorean theorem to find the length of the hypotenuse given the lengths of
the two opposing sides

theknowledgeacademy
34
Characters
Java uses Unicode rather than characters being 8-bit
quantities like they are in many other computer languages

char is an unsigned 16-bit type with a range of 0 to 65,536 in


Java

Unicode defines a character set that can represent all of the


characters found in all human languages

theknowledgeacademy
35
Characters
• As char is an unsigned 16-bit type, it is possible to perform various arithmetic
manipulations on a char variable

• To assign a value to a character variable just enclose the character in single quotes:

Char ch;

ch = ‘Y’ ;

• The letter Y is now assigned to the variable ch

theknowledgeacademy
36
Boolean Type
• The Boolean type only has two values:

1. True 2. False

• The words true and false are reserved for Java to define the values

• The value of a Boolean variable is sufficient, by itself, to control the if statement

• The outcome of a relational operator, such as < is a Boolean value

theknowledgeacademy
37
Exercise

In this project, you will create a program that computes how far away,
in feet, a listener is from an avalanche. Sound travels approximately
1,100 feet per second through air. Thus, knowing the interval between
the time you see the snow advancing and the time the sound reaches
you enables you to compute the distance to the avalanche. For this
project, assume that the time interval is 9.6 seconds

Instructions on the next slide

theknowledgeacademy
38
Instructions
Create a new file called Sound.java

To compute the distance you will need to use floating-point values

To compute the distance, you will multiply 9.6 by 1,100. This value
will then be assigned to a variable

Display the result

theknowledgeacademy
39
Instructions
/*
Try This 2-1
Compute the distance to an avalanche
whose sound takes 9.6 seconds
to reach you
*/
Class Sound {
public static void main (String args[]) {
double dist;

dist = 9.6 * 1100;

System.out.println (“The avalanche is “ +


dist +
“ feet away.”) ;

}
}

The avalanche is 10,560.0 feet away

theknowledgeacademy
40
Literals
• Literals are fixed values that are represented in their human-readable form (also
commonly known as constants)

• Java literals can be any of the primitive data types

• Depending on the type, each literal is presented in a different way

theknowledgeacademy
41
Literals
Can be assigned to variables By default, integer literals
of type char, byte or short are of type int
as long as the value can be Integer
represented by the target Specified as numbers without
type fractional components e.g. 1 or
-63 If you want to specify a
long literal, append an l or
L e.g. 9L

If you want to specify a


float literal, append an f or
F e.g. 16.82F
Literals

Floating-Point Character
Require the use of the decimal
point followed by the number’s Enclosed in single quotes e.g.
fractional component ‘a’ or ‘%’

By default, floating-point literals are of


type double
theknowledgeacademy
42
Variables
• Variable: A named memory location that can be assigned a value

• To declare a variable, use this form of statement:

type var-name

data type variable name

• In order to compile any statement that uses a variable, all variables must be declared
prior to their use

theknowledgeacademy
43
Initialising Variables
Before using a variable, in general, it must have a value which can be given by:

• Having an assignment statement:

int a = 456

o The assignment statement puts the value 456 into the variable

Giving it an initial value:

o Put equals sign and assigned value after variable’s type and name. Value must be
compatible with type

int a = 6

theknowledgeacademy
44
Variables - Blocks and Scopes

Variables are allowed to be declared


within any block. A scope is defined by
a block. Each time a new block is
started, a new scope is also created

The lifetime and visibility to other parts


of your program of objects is
determined by a scope

theknowledgeacademy
45
Variables

Variables declared inside a scope,


in general, are not visible. Whenever a new block of
Meaning it is not accessible to code is created and new-
code defined outside of that nested scope is also
sacope protecting that variable
from unauthorised moderation created
and/or access

theknowledgeacademy
46
Variables - Nested scope

However, it is not
the same the other
way around.
Outer scope
Objects will not be
encloses the inner
visible outside the
scope
inner scope if they
have been declared
inside it

Code within the inner scope


will have access to objects
declared in the outer scope

theknowledgeacademy
47
Operator
Arithmeti
c

Four
A symbol that tells the compiler to general
perform a specific mathematical or logical
Logical classes of Bitwise
operator
manipulation in Java

Relational

theknowledgeacademy
48
Arithmetic Operators
• These arithmetic operators have been defined by Java and can be applied to any built-
in numeric data type and objects of type char:

Operator Meaning
+ Addition (also unary plus)
- Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement

theknowledgeacademy
49
Relational Operators
• The relationship that values can have with one another are referred to as relational
operators:

Operator Meaning

== Equal to

!= Not equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

theknowledgeacademy
50
Logical Operators
• The way in which true and false values can be connected together are referred to as
logical operators. Both relational and logical operators produce boolean value
outcomes:

Operator Meaning
& AND
| OR
^ XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! NOT

theknowledgeacademy
51
Short-Circuit Logical Operators
• To produce more efficient code, Java supplies short-circuit versions of AND OR logical
operators

o AND operation: If the first operand is false, the outcome is always false regardless

o OR operation: If the first operand is true, the outcome is always true regardless

• If the second operand is not unnecessarily evaluated more efficient code is produced
and time is saved

theknowledgeacademy
52
Assignment Operator
• The single equal sign, =, is the assignment operator

• You can create a chain of assignments:

a = b = c = 100; // set a, b and c to 100

• This is a simple way to set a common value to a group of variables

theknowledgeacademy
53
Type Conversion

Automatic type
conversion will A widening It is common in
take place if: conversion takes programming to
• The two types are place when these assign one type of
compatible (e.g. two conditions variable to
both are numeric) are met another
• The destination
type is larger than
the source type

theknowledgeacademy
54
Casting Incompatible Types
• As they only apply to widening conversions,
automatic type conversions cannot fulfil all
programming needs

• Cast, an instruction to the compiler to convert


one type into another

• Information might be lost if a cast involves a


narrowing conversion (e.g. when a floating-
point value is cast to an integer type the
fractional component will be lost)

theknowledgeacademy
55
Exercise

Find the value of the variable result after executing


the following sentences:

int a;
int b;
int
result;

theknowledgeacademy
56
Exercise
a) a = 4;
b = 12;
result = a + b / 3;

b) a = 3;
b = 11;
result = (b % a) + 1;

c) a = 2;
b = a + 1;
a = b + 2;
result = a + b + a;
result = -result

theknowledgeacademy
57
Module 3: Program Control Statements

theknowledgeacademy
58
Program Control Statements
Program control statements are split into three
categories:

1. Selection statements:
o These include the if and the switch

2. Iteration statements:
o These include the for, while and do-while
loops

3. Jump statements:
o These include break, continue and return

theknowledgeacademy
59
The if Statement

An if statement checks to see if a statement is true or false.


Therefore a boolean result must be produced by the
conditional expression controlling if

If proved true, either a function is performed or


information is displayed

The complete form of the if statement is:

if (condition) statement; else statement

theknowledgeacademy
60
The if Statement
Example: Here we are going to test a user’s age:

theknowledgeacademy
61
Nested if Statements
• Nested if is a decision making statement in Java that flows according to particular
condition

• The branching of these conditions is a result of the state change of the program. That
is, an if-else condition will have another if-else inside it

theknowledgeacademy
62
if-else-if Ladder
True False
condition 1
True False
Statement 1
condition 2

Statement 2 True False


condition 3
True False
Statement 3 condition n

Statement n
Default statement

Statement x

Next statement

theknowledgeacademy
63
The Switch Statement
• A switch statement allows the value of an expression or variable to change the control
flow of the program's execution via a multiway branch

• A switch works with the byte, short, char and int primitive data types and an
enumeration

• Modern versions of Java (from JDK7) can use String to control a switch

theknowledgeacademy
64
if-else-if Ladder
Example

theknowledgeacademy
65
if-else-if Ladder
Example

theknowledgeacademy
66
Exercise

Write a program that prints PASS if the int


variable mark is greater than or equal to
50; or prints FAIL otherwise

theknowledgeacademy
67
The for Loop
• Used for repeating a single statement

• The general form of the for loop is:

for (initialisation; condition; iteration);{statement}

increment
start value end value
number

• As long as the condition tests true the for loop will continue to execute

theknowledgeacademy
68
The for Loop
Example

theknowledgeacademy
69
The for Loop
• The conditional expression is always tested at the top of the loop

• If the condition is false to begin with, the code inside the loop may not be executed at
all:

for (count = 10; count < 5; count++)

• Because the control variable is greater than 5 at the beginning, this loop will never
execute

theknowledgeacademy
70
Variations on the for Loop
Multiple loop
control
variables

Declaring
loop control
Missing
variables
Allowing a wide pieces
inside the for
loop range of variations
makes for one of the
most versatile
statements in the
Java language:

Loops with
Infinite loop
no body

theknowledgeacademy
71
Multiple Loop Control Variables
• Multiple loop control variables can simplify certain algorithms and are often convenient

• Any number of initialisation and iteration statements is possible; however, any more
than two or three would make the loop difficult to manage

for (a = 0, b = 20; a < b; a++, b--)

theknowledgeacademy
72
Missing Pieces and The Infinite Loop
• It is possible, in Java, for any or all of the initialisation, condition, or iteration pieces to
be missing

• An infinite loop can be created by leaving the conditional expression empty

• Most ‘infinite loops’ are just loops with special termination requirements

theknowledgeacademy
73
Loops With No Body
• The body associated with a for loop can be empty in Java

• All of the desired functionality is defined within the for statement. The statement is
closed using a semi-colon

int total = 0

for (i = 1; i <= 10; sum += i++) ;

theknowledgeacademy
74
Declaring Loop Control Variables Inside the
for Loop

When this is executed


The variable can be
you must remember The variable will cease
declared inside the
that the scope of that to exist outside of the
initialisation portion of
variable ends when the for loop
the for loop
for statement does

theknowledgeacademy
75
The while Loop
• The general form of the while loop is:

while (condition) {
statement;
}

• The while loop continually executes a single statement or block of statements while a
particular expression is true

• Program control passes when the condition becomes false

theknowledgeacademy
76
The while Loop
• Just like the for loop, the while loop checks the conditional expression at the top of the
loop

• The loop code may not execute at all

• The need to perform a separate test before the loop is eliminated

theknowledgeacademy
77
The do-while Loop
• The general form of the do-while loop is:

do {
statements;
} while (condition);

• The do-while loop checks its condition at the bottom of the loop, unlike the for and the
while

• A do-while loop will always execute at least once

theknowledgeacademy
78
The do-while Loop
Example

theknowledgeacademy
79
Java’s Loops

As all of Java’s
while loop:
loops are so
when the loop
flexible it can be
will repeat an
difficult to know
unknown
which one to
number of times
select:

do-while loop:
for loop: when
when you need
performing a
a loop to
known number
perform at least
of iterations
one iteration

theknowledgeacademy
80
The break Statement
Example:

theknowledgeacademy
81
The break Statement
• The break statement has two forms:

1. Unlabelled – used to jump out of a single loop as seen in the previous example

2. Labelled – used to jump out of nested or multiple loops

o A labelled break loop can be used as a form of goto statement

theknowledgeacademy
82
The break Statement
Example:

theknowledgeacademy
83
The continue Statement
Example:

theknowledgeacademy
84
Exercise

Write a for loop that attempts to display


the numbers from 1 to 10, but terminates
when the control variable reaches the value
6

theknowledgeacademy
85
Module 4: Classes, Objects, Methods

theknowledgeacademy
86
What is a Class?
• Class is at the heart of Java

• Defined data and code that acts upon that data makes up a class

• All Java programming activity operates within a class

• It is the building blocks of a larger application

• A blueprint that defines the form of an object

• Objects are instances of class

• When an object of that class has been created, you will then see a physical
representation of it

theknowledgeacademy
87
General Class Form
• Once you define a class, you declare it by stating the instance variables

• Most classes will contain methods as well as instance variables

• Created using the keyword class

• A class should describe only one logical unit to avoid becoming unrelated and
destructured

• General form does not specify main() method

theknowledgeacademy
88
General Class Form
Syntax:
Class classname {
//declare variables
example1;
example2;
//…
type example;

//declare methods
type methodname1(parameters) {
//body of method
}
type methodname1(parameters) {
//body of method
}
//…
type methodN(parameters){
//body of method
}

theknowledgeacademy
89
Defining a Class
• A class definition creates a new data type

• A class declaration is only a type description

• To create an object you will need a follow on statement

• Each time you create an instance of a class, you create an object

• The object contains its own copy of each instance variable defined by the class

• The dot operator links the name of an object to a member

theknowledgeacademy
90
Defining a Class
(Continued)

Syntax:

public class Puppy {


public Puppy() {
}

theknowledgeacademy
91
How Objects are Created
• You create an object from a class

• You need to declare an object of type

• This creates a physical copy of the object and assigns a reference

• New operator dynamically allocates memory for an object

• The reference is stored as a variable

• All class objects must be dynamically allocated

• By assigning a reference to the object, you link it with the object

theknowledgeacademy
92
How Objects are Created
(Continued)

Example:

theknowledgeacademy
93
Reference Variables
• Reference: leads you to something

• Variable: memory containing data value

• Object reference variables: assigning value of reference to another reference variable

• Changes the object that the reference variable refers to

• It provides the direction to the memory location of where the object is

theknowledgeacademy
94
Methods
• Methods are subroutines that alter the data defined by the class and provide access

• Programs will interact with a class via its methods

• A method performs an operation

• A method has a name (this can be what you like but don’t use Java’s keywords)

• The name will be written like: elephant( )

• Name of the method is specified by name

theknowledgeacademy
95
Methods
• Syntax:

public static int methodName(int a, int b) {


// body
}

• Example:

theknowledgeacademy
96
Returning from a Method
• There are following two ways of returning a method:

1. Return statement, to either void methods or returning a value

2. Range() method, using closing curly braces

Example of Return statement method

theknowledgeacademy
97
Returning from a Method
Example of Range() method

theknowledgeacademy
98
Returning from a Method
Void Method

• Immediate termination of method

• Program controls return to caller

• Skips remaining code

• Can have multiple return statements

• Do not have too many exit points

theknowledgeacademy
99
Returning from a Method
• Example:

theknowledgeacademy
100
Constructor
• It prepares an object when it is created, setting values for variables

• A class constructor saves you from having to create everything manually and risk errors

• A class constructor uses the same as the class

• When you device your own constructor these are skipped

• Java automatically uses default constructors to initialise member variables to their


default values

theknowledgeacademy
101
Constructor
Example:

theknowledgeacademy
102
New Operator
• The new operator creates a new object of any class type

• Used by default constructor if no constructor is defined already

• Returns a reference to new object

• Dynamically allocates memory for object at run time

Syntax:

Class-var = new classname();

theknowledgeacademy
103
New Operator
Example:

theknowledgeacademy
104
Garbage Collection
• If new fails due to insufficient free memory, you need to be able to recover free memory
from unused objects for reallocation

• To do this Java uses a system called garbage collection

• The garbage collection automatically reclaims objects

• If there are no references to an object, it presumes it is no longer required so the


memory can be used

• It releases this memory for reallocation

theknowledgeacademy
105
Finalize
• Finalize method is used to terminate an object cleanly

• Called before the garbage collection occurs

• You manually call the finalize method, it is not an automatic feature

• To add to a class you need to define the method, so that it is used when an object is
about to recycle

• Useful for specifying actions before an object is destroyed

Syntax:
Protected void finalize()
{
//finalization code
}
theknowledgeacademy
106
The this Keyword
• An implicit argument that is a reference to the invoking object is known as this

• It distinguishes between an attribute and a local variable/parameter when they have


the same name in a program

• Solves ambiguity. This must be the first statement in body of constructor

theknowledgeacademy
107
The this Keyword
Example:

theknowledgeacademy
108
Module 5: More Data Types and
Operators

theknowledgeacademy
109
Arrays
• Data can be easily manipulated and sorted as a result of the way it is organised by an
array

• Arrays implemented as objects, an attribute that is not shared in programming


languages

• Stores a fixed-size collection of variables of the same type

Syntax:

dataType[] arr;

theknowledgeacademy
110
Arrays
Example:

theknowledgeacademy
111
One-Dimensional Arrays
• One-dimensional arrays use this general form:

Special operator that allocates memory

type array-name[]=new type[size];

base type number of elements in the array

• Base type, or element type, determines the type of data the array will hold

theknowledgeacademy
112
One-Dimensional Arrays
(Continued)

• All array indexes start at zero. Index, the position of an element within an array

• By using an index, individual elements within an array can be accessed through


specifying its position within square brackets

• Syntax: There are the following three methods to declare one-dimensional array

method_1 - data_type[] array_name;


method_2 - data_type []array_name;
method_3 - data_type array_name[];

theknowledgeacademy
113
One-Dimensional Arrays
Example:

theknowledgeacademy
114
Two-Dimensional Arrays
• The two-dimensional array is the simplest form of the multidimensional array

• It is, in essence, a list of one-dimensional arrays

• Data is stored in rows and columns, and we can access the record using both the row
index and column index

Syntax:

Data_Type[][] Array_Name;

theknowledgeacademy
115
Two-Dimensional Arrays
Example:

theknowledgeacademy
116
Irregular Array
• Irregular arrays are similar to n-dimensional (n>1) arrays, which are displayed as arrays
of one-dimensional arrays with various numbers of elements

• The number of elements in at least one dimension is not known. This number may vary
within this dimension

• Irregular array declaration:

int[][] B = new int[3][]; // irregular array, the total number of elements is unknown

theknowledgeacademy
117
Multidimensional Array
• Arrays with more than two dimensions are allowed in Java

• To initialise a multidimensional array each dimension’s initialiser needs to be enclosed


within its own set of curly braces

• Each inner block designates a row

• The first value will be stored in the first position of the subarray, within in each row, the
second value in the second position

Syntax:

type name [ ] [ ]…[ ] = new type [size1][size2]…[sizeN];

theknowledgeacademy
118
Multidimensional Array
Example:

theknowledgeacademy
119
Length Member
• Each array has a length instance variable associated with it because they are
implemented as objects

• The number of elements an array can hold is found in its length instance variable

• All arrays have this variable and it will always hold the size of the array

Example:

theknowledgeacademy
120
The for-each Style for Loop
• A for-each loop cycles through a collection of objects, such as an array, in strictly
sequential fashion, from start to finish

• The for-each style loop came into existence with the release of JDK5

• It is also referred to as the enhanced for loop

• It automatically cycles through the entire array eliminating the need for a loop counter,
specific start and end points and manually indexing the array

theknowledgeacademy
121
The for-each Style for Loop
(Continued)

• It is possible to terminate the for-each style for loop by using a break statement even
though it iterates until all elements in an array have been examined:

for (int x : nums) {


System.out.println (Value is: “ + x);
sum += x;
if (x == 5) break;
}

• This loop sums only the first five elements of nums

theknowledgeacademy
122
The for-each Style for Loop
Example:

theknowledgeacademy
123
Strings
• String is one of the most important data types in Java

• Unlike other programming languages, strings in Java are objects

• There are two ways to construct strings:

1. String Literal 2. Using new Keyboard

theknowledgeacademy
124
Strings
1. Using Literal: It should be enclosed in double quotes. The compiler make a String
object with its value whenever it encounters a string literal in your code

theknowledgeacademy
125
Strings
2. Using new keyword: The compiler would now create two different objects in memory
that have the same text

theknowledgeacademy
126
Operations on String
• Strings can be operated on by several methods:
Boolean equals (str) Returns true if the invoking string contains the same character
sequence as str
int length ( ) Obtains the length of a string
char charAt (index) Obtains the character at the index specified by index

int compareTo (str) Returns less than zero if the invoking string is less than str,
greater than zero if the invoking string is greater than str, and
zero if the strings are equal

int indexOf (str) Searches the invoking string for the substring specified by str.
Returns the index of the first match or -1 on failure

int lastIndexOf (str) Searches the invoking string for the substring specified by str.
Returns the index of the last match or -1 on failure

theknowledgeacademy
127
Bitwise Operators
• The bitwise operators can be used on values of type long, int, short, char, or byte

• In order to test, set, or shift the individual bits that make up a value, a bitwise operator
is used
Operator Result
& Bitwise AND (turn bits off)
| Bitwise OR (turn bits on)
^ Bitwise exclusive OR (turn a bit on if the bits being
compared are different)

>> Shift right (Brings a 1 on the left if value is negative.


Brings a 0 on the left if the value is positive
>>> Unsigned shift right (Always brings a 0 on the left)

theknowledgeacademy
128
Bitwise Operators
Example:

theknowledgeacademy
129
The ? Operator
• The ? operator is a ternary operator (it requires three operands) and is often used to
replace if-else statements

• If boolean expression specified before ? is true, then expression after ? gets executed
and if boolean expression specified before ? is false, then expression after : gets
executed

Example:

theknowledgeacademy
130
Module 6: Closer look at Methods and
Classes

theknowledgeacademy
131
Controlling Access
• A class provides the possibility to control access to members

• If no access modifier is put in place then a default access setting will be activated

• When declaring a member variable you can disallow/allow classes or objects to it

• Access modifiers, public, private, protected

• You can control member access by using access modifiers

theknowledgeacademy
132
Access Modifiers
• There are the following three access modifiers are present in java:

Private

2
1 3
Public
Protected

theknowledgeacademy
133
Access Modifiers
(Continued)

1. Public: Open access. Any other code in the program can access member. Useful for
when you want the variable to be shared to all of your applications

2. Private: Specified access. Only other members in that class can access it. Other
classes/methods in your application will be blocked from it

3. Protected: Class access. Own class has access, but also other subclasses can too by use
of inheritance

theknowledgeacademy
134
Pass Objects to Methods
• Everything in Java is passed by value

• It is common to pass objects to methods

• But Objects are not directly passed to the methods, they are passed by reference

• It is possible to access instance variables of the object passed inside the called method

theknowledgeacademy
135
Passing an Argument
• Passing non-object arguments is different to passing an object

• They can be passed to a subroutine by using the call-by-value method or call-by


reference

• Call-by-value: Copies value of an argument into formal parameter of subroutine. No


effect on argument in the call

• Call-by-reference: Reference to an argument is passed to parameter. Used to access


actual argument specified in the call

theknowledgeacademy
136
Passing an Argument
Example:

theknowledgeacademy
137
Passing an Argument
• Passing an object to a method uses call-by-reference

• Implicitly passed

• Creating a variable of a class type = creating a reference to an object

• Reference is passed to a method not the object

• Parameter receiving it will refer to same object that the argument refers to

• Changes to object inside a method will affect the object used as an argument in this way

theknowledgeacademy
138
Returning Objects
• Any types of data such as class types can be returned through a method. It is used to
report errors

Example:

theknowledgeacademy
139
Method Overloading
• It is a feature that allows two or more methods within the same class to share the same
name

• It is also known as Static Polymorphism

• In this parameter declarations must be different

• It implements polymorphism

• The methods here are overloaded

theknowledgeacademy
140
Method Overloading
Example:

theknowledgeacademy
141
Automatic Conversions
• Java includes certain automatic conversions

• These also apply to parameters of overloaded methods

• Automatic conversions are employed if no exact parameter or argument match is found

Example:

theknowledgeacademy
142
Overloading Constructors
• Constructors can also be overloaded just as methods can

• This gives you the ability to construct objects in various ways

• The proper constructor is called based upon the parameters specified

• The way that objects are constructed in your class is made flexible by overloading a
class’ constructor

• A common reason for constructors to be overloaded is to allow one object to initialise


another

theknowledgeacademy
143
Overloading Constructors
Example:

theknowledgeacademy
144
Recursion
• It is the technique of creating a function call itself

• It gives a way to break down complex problems into simpler problems that are easy to
solve

• Example: Adding the numbers using recursion:

theknowledgeacademy
145
Understanding Static
Static

• It is a way to associate with a class, but being independent from any object of that class

• The member here can be used on its own, with no specific instance

• Methods and variables can both be static

• The keyword static is used to declare a member, which can be accessed without
reference to, or before, any objects in that class are created

• Outside of a class only the dot operator after the name of your class needs to be used to
use a static member

theknowledgeacademy
146
Understanding Static
Static Block

• Static block, used for static initialisation of a class

• Sometimes before a class is ready to create an object/s, that class will need to be
prepared

• When the class is first loaded this will be the first thing executed, before constructors or
any other purposes of that class can be used

• It is useful for initialising specific static variables before static methods are used

• Code inside static block only executed once

theknowledgeacademy
147
Understanding Static
Example:

theknowledgeacademy
148
The Quicksort
• One of the most popular and best general-purpose sorting algorithms

• Uses partitions to sort the array into two sections

• Elements are divided into two sides, those that are greater than or equal to partition
value and those that are less

• This reoccurs through each section until array is sorted

• Quicksort can then be called by using just the array’s name

theknowledgeacademy
149
The Quicksort
Example:

theknowledgeacademy
150
Nested and Inner Classes
• Nested class, class declared within another class

• Inner class, non-static type of nested class

• Nested class does not exist independently of enclosing class

• There is Possibility of declaring nested class local to a block

• Inner class can access all variables and methods of outer class

• This can directly refer to them similar to outer class, non-static members

• It is useful in providing set of services solely used by enclosing class

theknowledgeacademy
151
Nested and Inner Classes
Syntax:
class OuterClass
{
...
class NestedClass
{
...
}
}
Example:

theknowledgeacademy
152
Varargs
• On occasion you will need to create a method which takes on variable numbers of
arguments

• This will need to be based on its precise usage

• JDK 5 introduced the varargs (variable-length-arguments) feature to solve this problem

• variable-arity method or varargs method. A method that takes variable number of


arguments

• Parameter list is not fixed, but variable in length

• Variable-Length Argument is specified by three periods (…)

theknowledgeacademy
153
Varargs
Overloading

• It is possible to overload a method that takes a variable-length argument

• Types of program varargs parameter may differ and cause it to be treated as an array of
the specific type

• You can also add one or more normal parameters

Ambiguity

• Unexpected errors may result when overloading a method with variable-length


argument

theknowledgeacademy
154
Varargs
(Continued)

• Could create ambiguous call to overloaded varargs method

• Ambiguity errors may expose a conceptual flaw in your code

Example:

theknowledgeacademy
155
Module 7: Inheritance

theknowledgeacademy
156
Foundation Principles
• There are three principles of object-oriented programming:

Inheritance Encapsulation Polymorphism


• Refers to superclasses and • Limits the access that other • An object can take on many
subclasses pieces of code have to a forms while a program is
particular object running
• It allows the creation of
hierarchical classifications • Makes the fields in a class • Subclasses can define their
private own unique behaviour and
share functionality
similarities of parent class

theknowledgeacademy
157
Foundation Principles
• Different kinds of objects have certain
commonalities with each other

• Creating a subclass is simple using the


extends keyword:

o Subclass name

o Superclass name

theknowledgeacademy
158
Foundation Principles
(Continued)

For any subclass that


is created, it can only
have one superclass

Each subclass can


A subclass can
precisely tailor its
become a
own classification
superclass of
once it has a
another subclass,
superclass that
creating a
defines common
hierarchy of
attributes to a set
inheritance
of objects

theknowledgeacademy
159
Foundation Principles
(Continued)

A subclass cannot access


Inheriting a class doesn’t those members of the
overrule any private access superclass that have been
restrictions placed within declared private, even
the superclass though it includes all of the
members of its superclass

theknowledgeacademy
160
Constructors
• It is possible for both subclasses and
superclasses to have their own constructors, in a
hierarchy

• The constructor for the superclass constructs the


superclass portion of the object

• The constructor for the subclass constructs the


subclass part

theknowledgeacademy
161
Using super to Call Superclass Constructors
• super( ) must be the first statement in the subclass constructor, otherwise you will get a
compiler error message

• When a subclass calls super( ), it is calling the constructor of its immediate superclass

• super (parameter list) calls the superclass constructor with a matching parameter list

theknowledgeacademy
162
Using super to Call Superclass Constructors
Example

theknowledgeacademy
163
Using super to Call Superclass Constructors
• Using super in this way is most useful where member names of a subclass hide
members by the same name in the superclass

• It follows this general form:

super.member

either a method or an instance variable

theknowledgeacademy
164
Using super to Call Superclass Constructors
(Continued)

theknowledgeacademy
165
Multilevel Hierarchy
• A is the superclass of B

• B is the subclass of A, but the superclass of C


A
• C is the subclass of B

• As such, class C inherits class B and class B


B
inherits class A
C
• Therefore, class C is implicitly inheriting the
properties and method of class A and class B

theknowledgeacademy
166
Multilevel Hierarchy
Example

theknowledgeacademy
167
Multilevel Hierarchy
(Continued)

theknowledgeacademy
168
Superclass References and Subclass Objects
• Normally, a reference variable for one class type cannot refer to an object of another
class type

• However, a superclass reference can refer to a subclass object, which is an important


exception:

o The members that can be accessed is determined by the type of the reference
variable and not the type of object

o When a reference to a subclass object is assigned to a superclass reference variable,


there is only access to those parts of the object defined by the superclass

theknowledgeacademy
169
Method Overriding
• Method overriding only occurs when the signatures of the subclass and superclass
methods are identical

• The access level cannot be restrictive of the overridden method’s access level

o If the superclass method is declared public, the overriding method in the subclass
cannot be private or protected, it has to be the same

• When this occurs, the method in the subclass overrides the method in the superclass,
hiding the version of the method defined by the superclass

theknowledgeacademy
170
Method Overriding
Example

theknowledgeacademy
171
super Keyword in Overriding

By using super, you can access the superclass


version of an overridden method

All instance variables are therefore


allowed to be displayed

theknowledgeacademy
172
super Keyword in Overriding
Example

theknowledgeacademy
173
Dynamic Method Dispatch
• Dynamic Method Dispatch is the mechanism by which a call to an overridden method is
resolved at run time, rather than compile time

• It is related to the earlier principle:

o A superclass reference can store the reference of subclass objects

• Java determines which method (when an overridden method is called through a


superclass reference) to execute based upon the type of the object being referred to at
the time the call occurs

theknowledgeacademy
174
Dynamic Method Dispatch
Example

theknowledgeacademy
175
Dynamic Method Dispatch
(Continued)
class DynDispDemo {
public static void main (String args []) {
Dyna superOb = new Dyna();
Mite1 subOb1 = new Mite1();
Mite2 subOb2 = new Mite2();

Dyna dynaRef;

dynaRef = superOb;
dynaRef.who();
In each case, the version of
dynaRef = subOb1; who( ) to call is determined
dynaRef.who(); at run time by the type of
object being referred to
dynaRef = subOb2;
dynaRef.who();
}
}

theknowledgeacademy
176
Dynamic Method Dispatch
(Continued)
The output of the program is:
who() in Dyna
who() in Mite1
who() in Mite2

• Subclasses Mite1 and Mite2 are created with a superclass called Dyna

• Objects of type Dyna, Mite1 and Mite2 are declared inside the main( ) method

• A reference of type Dyna is created (dynaRef)

• Each type of object to dynaRef is assigned a reference by the program and that
reference is used to call who( )
theknowledgeacademy
177
Dynamic Method Dispatch
(Continued)

• The type of object being referred to at the time of the call determines the version of
who( ) that is executed, not the class type of dynaRef

theknowledgeacademy
178
Abstract Classes
• Abstract classes cannot be instantiated, meaning you cannot create new instances of an
abstract class

• Their purpose is to act as a base for subclasses

• To declare an abstract class just add abstract to the beginning of the class declaration:

abstract class MyAbstractClass {

theknowledgeacademy
179
Abstract Methods
• An abstract method has no implementation

• To declare an abstract method, just add abstract in front of the method declaration:

abstract class MyAbstractClass {


abstract void abstractMethod();

• The whole class must be declared abstract if it has an abstract method

• However, not all methods in an abstract class have to be abstract methods

theknowledgeacademy
180
Abstract Methods
(Continued)

Any non-abstract If the subclass and


Subclasses of an methods of the superclass are
abstract class must superclass are abstract classes, the
override all abstract inherited as they are subclass is not forced
methods of its and, if needed, they to implement all
abstract superclass can also be abstract methods of
overridden its superclass

theknowledgeacademy
181
Using final

By using final you can prevent


a class from being inherited or
a method from being
overridden

To prevent a method from


being overridden, final must
be specified as a modifier at
the start of its declaration

Models declared as final


cannot be overridden

theknowledgeacademy
182
Using final

To prevent a class
from being It is illegal to
inherited, final declare a class
must precede its as both abstract
declaration and final

All of a class’
methods are
implicitly declared
as final when a class
is declared as final

theknowledgeacademy
183
Using final
• When a class variable’s name is preceded
with final its value cannot be changed once it
is initialised and throughout the lifetime of
the program

• final variables are often treated as constants

• You will receive a compile-time error if you


try to change the value of a final variable

theknowledgeacademy
184
The Object Class
• The Object class is an implicit superclass of all other classes

• A reference variable of type Object can refer to an object of any other class

• A variable of type Object can also refer to any array

• The following methods are defined by Object, therefore they are available in every
object:
Method Purpose
Object clone ( ) Creates a new object that is the same as
the object being cloned
boolean equals (Object object) Determines whether one object is equal
to another
void finalise ( ) Called before an unused object is
recycled

theknowledgeacademy
185
The Object Class
(Continued)
Method Purpose
Class <?> getClass ( ) Obtains the class of an object at run
time
int hashCode ( ) Returns the hash code associated
with the invoking object
void notify ( ) Resumes execution of a thread
waiting on the invoking object
void notifyAll ( ) Resumes execution of all threads
waiting on the invoking object
String toString ( ) Returns a string that describes the
object
void wait ( ) Waits on another thread of
void wait (long milliseconds) execution
void wait (long milliseconds, int
nanoseconds)

theknowledgeacademy
186
The Object Class
• getClass ( ), notify ( ), notifyAll ( ) and wait ( ) are declared as final

• equals ( ) compares two objects

• true is returned if the objects are equivalent

• false otherwise

• toString ( ) returns a string that contains a description of the object on which it is called.
It is also automatically called when an object is output using println ( )

theknowledgeacademy
187
Module 8: Packages and Interfaces

theknowledgeacademy
188
Packages
Package, a group of related
classes that help organise code All classes belong to a package
and delivers encapsulation

A package provides a
Packages give you greater mechanism where connected
control pieces of a program can be
organised together

Helps with controlling the Java Provides a way to partition


access system namespace

It becomes harder to find


Package names are case
unique names for every class
sensitive
when you have a large program

theknowledgeacademy
189
Packages - the Facts
• More than one file can include the same package statement

• The statement specifies to which package the classes defined in a file belong

• This avoids name collisions with classes in other packages that have the same name

• Possible to define specific access rights to code inside a package, but only with code
within the same package

• Allowing you to create self-contained groups of related classes and keep their operation
private

theknowledgeacademy
190
Package Statement
• Java automatically provides a default package if no package statement is specified, but
these are not sufficient for anything but small, sample programs

• For most applications you will need to define one or more packages for your code

• Package defines a namespace

• The package command must be included on top of a Java source file

General form of a package statement: Multileveled package statement:

package mypack; Package alpha.beta.gamma;

• Names of the classes in the file will become part of that packages namespace

theknowledgeacademy
191
Finding Packages
• Java makes use of the file system to manage packages

• Each package is stored in its own directory

• Care must be taken to match names precisely between the package and the directory

• You need to create directories that support the hierarchy you create

• Java needs to be able to find these directories to find your packages and this can be
done by

DEFAULT or CLASSPATH

theknowledgeacademy
192
CLASSPATH
• CLASSPATH:

o environmental variable

• A locator device

• Specifies directory path/s

• Specifies path to your classes

Step 1: Create package directory below a current development directory

Step 2: Put .class files into relevant directories

theknowledgeacademy
193
CLASSPATH
Step 3: Execute programs from a development directory

Step 4: Keep .java and .class files associated with a package in that package’s directory

theknowledgeacademy
194
//Example of a package.
Example
Package bookpack; File is part of bookpack package
Class Book {
private String title;
So Book is part of bookpack
private String author;
private int pubDate; BookDemo is also part of bookpack
Book(String t, String a, int Class BookDemo {
d) { public static void main(String args[]) }
title = t; Book books[] = new Book[5];
author = a;
books[0] = new Book(“A Game of Thrones”,
pubDate = d; “Martin”, 1996);
} books[1] = new Book(“A Clash of Kings”,
“Martin”, 1999);
void show() { books[2] = new Book(“A Storm of Swords”,
System.out.printIn(title); “Martin”, 2000);
System.out.printIn(author);
for(int i=0; I < books.length; i++)
System.out.printIn(pubDate); books[i].show();
System.out.printIn(); }
} }
}
theknowledgeacademy
Continued… 195
CLASSPATH
(Continued)

theknowledgeacademy
196
Packages and Member Access

Package access
level is what you
Packages are also get when you do
involved in the not clearly define
access control a member’s
mechanism access to one of
the other levels

Package level
allows classes in
Assumes classes
the same
in same package
package as your
are trusted
class to access
members

theknowledgeacademy
197
Protected Members
• A field or method accessible to any type in the same package, and to subclasses in any
package

• Protected modifier creates a member that is accessible within its package and to
subclasses in others

• It is available for all subclasses to use but is still protected from arbitrary access by code
outside its package

• If a class has a protected variable or method that is static, the rules are different

theknowledgeacademy
198
Importing Packages
• Usual way, qualifying the name of a class with the name of its package

• Shortcut way, the import statement

• Brings one or more members of a package into view

• Gives you the ability to use those members directly, without explicit package
qualification

General forms of import statement: Importing entire package content:

import box.classname; import mypack.*;

Here box. is name of package. Classname is name of Using an asterisk for the class name enables you to import
class being imported entire contents

theknowledgeacademy
199
Interfaces

Interfaces, defines a set


Able to specify what a One class can
of methods, which will Specifies one or more
class will do (but not implement multiple
then be implemented methods with no body
how) interfaces
by a class

Class must have Each class can


implementations determine details of its Polymorphism, one Default implementation
(bodies) for the own implementation, interface, multiple available but not
methods described by whilst supporting same methods recommended
the interface set of methods

theknowledgeacademy
200
Implementing Interfaces
• Implementing an interface, use implements keyword

• Place implements clause in class definition

• Create methods required by interface

• Implementing more than one interface can be done with separating commas or extends
clause

• Must implement method as public:


General forms of implement in a class:

class classname extends superclass implements interface {


//class-body
}

theknowledgeacademy
201
Implementing Interfaces
Example

theknowledgeacademy
202
Using Interface References

Interface reference It is possible to create


variable has an interface reference
knowledge of only the variable to use as
methods declared by reference type for the
its interface object of an
declaration implanting class

When a method is
called through the It can link to any
interface reference, object that
execution of the implements its
method implemented interface
by the object is
delivered

theknowledgeacademy
203
Variables in Interfaces
• Variables declared in an interface = public, static, final

• Often large programs hold numerous separate source files and so interface variables
help to make constants available to each file

theknowledgeacademy
204
Extending Interfaces
• When adding more methods to the interface you want to avoid breaking the code

• You can do this by creating another interface extending onto the previous ones

• Inherits other interface with keyword, extends

• Must provide implementations for all methods required by interface inheritance chain

• All classes that implement an interface must ensure methods are implemented
correctly, this includes any inherited from other interfaces

theknowledgeacademy
205
Default Interface Methods
• Another way of extending, extension method

• Traditional form of the interface was abstract, contained no body

• JDK8 introduced new default method to define a default implementation for interface
method

• Able for an interface method to provide a body

• Provides means to expand an interface without breaking existing code

• Supplies implementation to be used if no other is provided, preventing code break

theknowledgeacademy
206
Default Interface Models
• Useful for specifying methods in an interface,
that can be optional depending on how that
interface is being used

• Interface still cannot have instance variables

• Must still be implemented by a class

• Default methods give you added flexibility

theknowledgeacademy
207
Default Method Fundamentals
• Interface methods are defined similar to how methods are defined by a class

• Difference, declaration is preceded by default keyword

Public interface MyIF {


// A “normal” interface method declaration.
// Does NOT define a default implementation. Declares 2
int getUserID(); methods
// Default method. Provides
// default implementation. Preceded by
default int getAdminID() { default
return 1;
}
modifier
}

• This example defines no implementation. Because it includes default implementation, it


is not necessary for an implementing class to override it

theknowledgeacademy
208
Default Method Fundamentals
Example

// Example of default • Here n refers to the number


// method called getNextArray().
public interface Series { of elements to retrieve in a
int getNext(); // return next number in series Series interface
• getNext() can be used inside
// Return an array that contains next n elements
// in the series beyond the current element. getNextArray() to obtain
default int[] getNextArray(int n) { next n in series
int[] vals = new int[n]; • no class needed to override
for(int i=0; i < n; i++) vals[i] = getNext(); it
return vals;
}
void reset(); //restart
void setStart(int x); // set starting value
}

theknowledgeacademy
209
Default Method Fundamentals
(Continued)

• By providing a default for this new method, it can be added to Series without breaking
existing code

• Allows you to evolve interfaces over time without break. Provides optional functionality

theknowledgeacademy
210
Multiple Inheritance

Default methods can


Java does not support Interface cannot maintain
however offer a certain
multiple inheritance state information like a
version of multiple
classes class
inheritance

Behaviour can be
inherited from multiple
Problems occur in this
default methods in an
situation with name
interface, when class
conflicts
implements more than
one

theknowledgeacademy
211
Multiple Inheritance
• Class implementation will always take priority over an interface default implementation

• When one interface inherits another, with both defining common default, inheriting
interface’s version wins over

• Possible to refer explicitly to default implementation by using super

General form: Example:

InterfaceName.super.methodName() Alpha.super.reset();

theknowledgeacademy
212
Multiple Inheritance
Example

// method called getNextArray().


public interface Series { • Here n refers to the number of
int getNext(); // return next number in series elements to retrieve in a Series
interface
// Return an array that contains next n elements • getNext() can be used inside
// in the series beyond the current element. getNextArray() to obtain next n
default int[] getNextArray(int n) { in series
int[] vals = new int[n]; • no class needed to override it

for(int i=0; i < n; i++) vals[i] = getNext();


return vals;
}
void reset(); //restart
void setStart(int x); // set starting value
}

theknowledgeacademy
213
Exercise

What are packages stored in?


What is a namespace?
Explain protected access
What is an interface?
Can interfaces be extended?

theknowledgeacademy
214
Module 9: Exception Handling

theknowledgeacademy
215
Exception Handling

Program processing Java is able to handle


gets terminated when run-time errors in a
Exception, an error an exception occurs structured and
that occurs at run time and you will receive a controlled manner
system generated error using its exception
message handling subsystem

theknowledgeacademy
216
The Exception Hierarchy
Throwable

Error Exception

Unchecked errors RuntimeException

Unchecked Checked
exceptions exceptions

theknowledgeacademy
217
The Exception Hierarchy

Errors are types of


All exceptions are
exceptions that are
represented by Exception and
beyond your
classes. The class Error are direct
control. They occur
Throwable derives subclasses of
in the Java virtual
all exception Throwable
machine itself and
classes
not your program

theknowledgeacademy
218
The Exception Hierarchy
Your program should
handle errors that
result from program
activity

They are subclasses of


Exception

RuntimeException is a
subclass of Exception
that is used to present
various common types
of run-time errors

theknowledgeacademy
219
Exception Handling Fundamentals
• There are five keywords that manage Java’s exception handling:

o Try: program statements that you want to monitor for exceptions are contained
within a try block

o Catch: handles an expression that is thrown from the try block in some rational
manner

o Throw: used to manually throw an exception

o Throws: specifies an exception that is thrown out of a method

o Finally: any code that must be executed upon exiting from a try block is put in a
finally block

theknowledgeacademy
220
Using try and catch
• It is impossible to have a catch without a try, these keywords work together

• The try/catch block has this general form:

try {
//statements that may cause an exception
}
catch (ExcepType1 exOb) {
// handler for ExcepType1
}

• There can be more than one catch statement associated with a try, but it must catch a
different type of exception

theknowledgeacademy
221
Using try and catch
(Continued)

All catch statements When an exception is


are bypassed if no thrown from try, it is
exception is thrown caught by its
leaving the try block corresponding catch
to end normally statement

If the exception
matches the The catch statement
exception type that is executed is
specified by the catch determined by the
statement then that type of exception
statement is executed
(all others are
bypassed)

theknowledgeacademy
222
Using try and catch
(Continued)

Example

theknowledgeacademy
223
Exercise

What is wrong with this fragment?

//…
vals [9] = 5;
catch (ArrayIndexOutOfBoundsException exc)
{
// handle error
}

theknowledgeacademy
224
Handle Errors Gracefully
• Exception handling allows your
program to respond to an error and
then continue running

• Once handled, an exception is removed


from the system

• Therefore, your program is able to


handle repeated errors

theknowledgeacademy
225
Catching Subclass Exceptions

A catch clause for a superclass matches any of its subclasses

To catch all possible exceptions of Throwable, catch Throwable because it is the


superclass of all exceptions

Put the subclass first in the catch sequence if you want to catch exceptions of
both superclass and subclass types

If not, the superclass catch will catch all derived classes

theknowledgeacademy
226
Nested try Blocks
• A try block can be nested within another try block

• An exception generated in the inner try block that is not caught by a catch associated
with that try is spread to the outer try block

• Nested try blocks are often used to handle different categories of errors in different
ways:

o An outer try block might be used to catch the most severe errors while inner try
blocks handle less serious ones

theknowledgeacademy
227
Using the throw Statement
• By using the throw statement it is possible to manually throw an exception

• The throw statement uses this general form:

throw exceptOb

must be an object of an exception class derived from Throwable

theknowledgeacademy
228
Using the throw Statement
Example

theknowledgeacademy
229
Rethrowing an Exception

An exception can be
rethrown after it has been
caught by one catch so that
When an exception is rethrown
it can be caught by an
the same catch statement will
outer catch
not catch it again, it will spread
to the next catch statement

theknowledgeacademy
230
Throwable
• All exceptions support the methods defined by Throwable. Below are several of the
commonly used methods:
Method Description
Throwable fillInStackTrace( ) Returns a Throwable object that contains a completed
stack track. This object can be rethrown

String getLocalisedMessage( ) Returns a localised description of the exception

String getMessage( ) Returns a description of the exception


void printStackTrace( ) Displays the stack trace
void printStackTrace(PrintStream stream) Sends the stack trace to the specified stream
void printStackTrace(PrintWriter stream) Sends the stack trace to the specified stream
String toString( ) Returns a String object containing a complete
description of the exception. This method is called by
println( ) when outputting a Throwable object

theknowledgeacademy
231
Using finally
• The finally block is placed after a try block and the catch blocks that follow it

• The code inside the finally block will always be executed, even if an exception is thrown
from within the try and catch block

• finally can be used:

o Where exception doesn’t occur

o Where exception occurs and isn’t handled

o Where exception occurs and is handled

theknowledgeacademy
232
Using finally
Example

theknowledgeacademy
233
Using throws
• Exceptions that are not subclasses of Error or RuntimeException need specification in a
throws list to avoid causing a compile-time error

• A throws clause must be included when defining a method to declare those exceptions
that might be thrown but don’t get caught in the method

• A throws clause has this general form:

Type method_name(parameter_list) throws exception_list

theknowledgeacademy
234
Exception Features

• try-with-resources
statement
Java’s exception handling • multi-catch
mechanism has been • final rethrow/more
with three new features precise rethrow
expanded beginning with
JDK7:

theknowledgeacademy
235
try-with-resources Statement
• The try-with-resources statement ensures that each resource is closed at the end of the
statement

• When the try block ends, the resource is automatically released

o In the case of a file, it means that it is automatically closed

• The try-with-resources statement can only be used with resources that implement the
AutoCloseable interface defined by java.lang

theknowledgeacademy
236
multi-catch
• It is common that two or more catch clauses will execute the same code to catch
different exceptions

• Two or more exceptions can be caught by the same catch clause using multi-catch

• A multi-catch is created by specifying a list of exceptions separated by the OR operator


within a single catch clause, for example:

catch (SQLException | IOException e)

theknowledgeacademy
237
final Rethrow

The type of exceptions that


can be rethrown are that are not handled by that are a supertype or
restricted to only those a preceding catch subtype of the
checked exceptions that the clause parameter
associated try block throws

The catch parameter must


be effectively final in order
for the final rethrow feature
to be in force

theknowledgeacademy
238
Java’s Built-in Exceptions - Unchecked
Exception Meaning
ArithmeticException Arithmetic error, such as integer divide-by-zero
ArrayIndexOutOfBoundsException Array index is out-of-bounds
ArrayStoreException Assignment to an array element of an incompatible type
ClassCastException Invalid cast
EnumConstantNotPresentException An attempt is made to use an undefined enumeration value
IllegalArgumentException Illegal argument used to invoke a method
IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread
IllegalStateException Environment or application is in incorrect state
IllegalThreadStateException Requested operation not compatible with current thread state
IndexOutOfBoundsException Some type of index is out-of-bounds
NegativeArraySizeException Array created with a negative size
NullPointerException Invalid use of a null reference
NumberFormatException Invalid conversion of a string to a numeric format
SecurityException Attempt to violate security
StringIndexOutOfBoundsException Attempt to index outside the bounds of a string

TypeNotPresentException Type not found


UnsupportedOperationException An unsupported operation was encountered

theknowledgeacademy
239
Java’s Built-in Exceptions - Checked
Exception Meaning
ClassNotFoundException Class not found
CloneNotSupportedException Attempt to clone an object that doesn’t implement the
Cloneable interface
IllegalAccessException Access to a class is denied
InstantiationException Attempt to create an object of an abstract class or
interface
InterruptedException One thread has been interrupted by another thread
NoSuchFieldException A requested field does not exist
NoSuchMethodException A requested method does not exist
ReflectiveOperationException Superclass of reflection-related exceptions

theknowledgeacademy
240
Creating Exception Subclasses

It is possible to create your own exception class by


defining a subclass of Exception

Exception inherits methods provided by Throwable, so


doesn’t have any defined methods of its own

All exceptions have the methods defined by Throwable


available to them

theknowledgeacademy
241
Exercise

Name the three ways that an exception can be generated


What are the three additional features that have been added to
JDK7?
What do each of these features do?

theknowledgeacademy
242
Module 10: Using I/O

theknowledgeacademy
243
Introduction to Streams
It is a large system,
containing most of the
Based upon a hierarchy of
I/O system makes up Java classes, methods, and
classes
interfaces you will ever
use

Streams are flows of data


I/O is performed through
you can read or write Abstract
streams
from/to

Produces or consumes Two main I/O systems,


information byte I/O and character
(output/input) I/O

theknowledgeacademy
244
Byte and Character Streams

Byte Streams Character Streams

• Used for performing input • Handles input and output


and output of bytes of characters.
• Mostly used for working Internationalised by use of
with files Unicode
• Descended from • Needs file’s encoding to
InputStream and work
OutputStream • Descended from Reader
• Byte stream accesses a file and Writer
byte by byte • Character stream reads
file character by character

theknowledgeacademy
245
Byte Stream Classes
• Specified by using two class hierarchies

• Mostly used of these are FileInputStream and FileOutputStream

• InputStream = defines the characteristics common to byte input systems

• OutputStream = defines the behaviour of byte output systems

InputStream/OutputStream

Subclasses Subclasses Subclasses Subclasses Subclasses Subclasses Subclasses

theknowledgeacademy
246
Byte Stream Classes
Byte Stream Class Meaning
BufferedInputStream Buffered input stream

BufferedOutputStream Buffered output stream

ByteArrayInputStream Input stream that reads from a byte array

ByteArrayOutputStream Output stream that writes to a byte array

DataInputStream An input stream that contains methods for reading Java standard data types

DataOutputStream An output stream that contains methods for writing Java standard data types

FileInputStream Input stream that reads from a file

FileOutputStream Output writes to a file

FilterInputStream Implements InputStream

FilterOutputStream Implements OutputStream

InputStream Abstract class that describes stream input

ObjectInputStream Input stream for objects

OutputOutputStream Output stream for objects

OutputStream Abstract class that describes stream output

PipedInputStream Input pipe

PipedOutputStream Output pipe

PrintStream Output stream that contains print() and printIn()

PushbackInputStream Input stream that allows bytes to be returned to the stream

SequenceInputStream Input stream that is a combination of two or more input streams that will be read sequentially, one after the
other.

theknowledgeacademy
247
Character Stream Classes
• Easier to use to write programs which are not dependent on a specific character
encoding

• Can be more efficient than byte code

• Specified by using two class hierarchies topped by two abstract classes Reader and
Writer

• Reader or input. Provides character stream analogues to byte stream

• Writer for output. Provides stream analogues to OutputStream for use with characters

• Classes derived from Reader and Writer operate under Unicode character streams

theknowledgeacademy
248
Character Stream Classes
Character Stream Class Meaning
BufferedReader Buffered input character stream
BufferedWriter Buffered output character stream
CharArrayReader Input stream that reads from a character array
CharArrayWriter Output stream that writes to a character array
FileReader Input stream that reads from a file
FileWriter Output stream that writes to a file
FileterReader Filtered reader
FilterWriter Filtered writer
InputStreamReader Input stream that translates bytes to characters
LineNumberReader Input stream that counts lines
OutputStreamWriter Output stream that translates characters to bytes
PipedReader Input pipe
PipedWriter Output pipe
PrintWriter Output stream that contains print() and printIn()
PushbackReader Input stream that allows characters to be returned to the input stream
Reader Abstract class that describes character stream input
StringReader Input stream that reads from a string
StringWriter Output stream that writes to a string
Writer Abstract class that describes character steam output

theknowledgeacademy
249
Predefined Streams
Java programs System.out is
import java.lang Which defines the standard output
package class System stream (console by
automatically default)

System.in is System.err is
Can be redirected
standard input (the standard error
to any compatible
keyboard by stream (console by
I/O device
default) default)

These are byte


System.out and streams because
System.in is object System.err are they are original
type InputStream objects of type predefined
PrintStream streams from the
original Java

theknowledgeacademy
250
Using Byte Streams
• In general, the methods in InputStream and OutputStream can throw an IOException
on error

• The methods defined by these two abstract classes are available to all of their
subclasses

• Form a set of I/O functions which all byte streams have

• Reading Console Input:

o Use byte or character streams to perform console input

o Preferred method is to use character-oriented stream.Easier to operate directly on


characters, rather than juggling between bytes and characters. Byte streams are
however useful for simple utility programs
theknowledgeacademy
251
Reading Console Input
• System.in is an instance of InputStream

• Automatic access to methods defined by InputStream

• Read() = the only defined input method from InputStream. It reads bytes

• Three different versions of Read()

int read() throws IOException


To read a single character from the keyboard (System.in)
int read(byte data[]) throws IOException
Reads bytes from input stream, putting them into data until either an error appears, the
array is filled, or end of stream is encountered
int read(byte data[], int start, int max) throws IOException
Reads input into data beginning at the location specified by start. Up to max bytes are
stored. Returns the number of bytes read

theknowledgeacademy
252
Writing Console Output
• Byte-based console output is the most commonly used byte stream

• Most easily used with print() and printIn()

• The methods are defined by the class PrintStream

• PrintStream is an output stream derived from OutputStream - implements low-level


method write()

• Creates ability to write to the console:

Simplest form: void write(int byteval)

• PrintStream supplies two additional output methods: printf() and format(). These give
you detailed control over the precise format of data that you output
theknowledgeacademy
253
Reading and Writing Files
Common types of files in Java are disk files

All files are byte-oriented

You can read and write bytes from a file to a file

You can also wrap a byte-oriented file stream within


a character-based object

Using FileInputStream and FileOutputStream


creates a byte stream linked to a file

theknowledgeacademy
254
Reading and Writing Files
• Use FileInputStream to open a file for input

Constructor: FileInputStream(StringfileName) throws


FileNotFoundException

• If the filename does not exist FileNotfoundException subclass will be used from
IOException

To read from file: int read() throws IOException

• read() reads a single byte from the file and returns it as an integer value each time it is
called

• When you are finished with a file use close() to end it


theknowledgeacademy
255
Reading and Writing Files
(Continued)

• This releases the system resources allocated to the file so that they can be used again

General form: void close() throws IOException

theknowledgeacademy
256
Writing to a File
• Design a FileOutputStream object to open up a file for output

• FileNotFoundException will appear if file cannot be created

• When output file is opened in first form, any pre-existing file by the same name is
abolished

• When output file is opened in second form (if append is true), output is appended to the
end of the file, otherwise the file is overwritten

• write() method = void write(int byteval) throws IOException

• Again make sure you close the output file like so:
void close() throws IOException

theknowledgeacademy
257
Closing a File Automatically
• There is a way to automate the closing process when a file is not longer required

• Known as either automatic resource management or as another version of the try


statement: try-with-resources

• The automated device stops anything from being unintentionally released, preventing
problems such as memory leak
General form: try(resource-specification) {
// use the resource
}

• Statement declaring and initialising a resource

• try block ends > resource is released > if it’s a file that file will then be automatically
closed
theknowledgeacademy
258
Writing to a File
Example

theknowledgeacademy
259
Try Statement
There is a possibility for an exception inside a try block to link to another one

In a standard try statement, original exception is lost

With a try-with-resources statement the second exception is supressed

This can only happen when a try block executes and the resource is closed in a finally clause

This can then be accessed if needed by a getSupressed () method

It gets added onto a list of supressed exceptions, linked to the first exception

theknowledgeacademy
260
Reading/Writing Binary Data
If you need to read and
write binary values of Java
A common occurrence is to
primitive types, use
need to read various types
DataInputStream to
of data
implement DataOutput
interface

This will define the methods


Data is written using
which write all Java
internal, binary format
primitive types to a file

DataInputStream uses an Overlays it with methods


InputStream instance as a that read the various Java
foundation types

theknowledgeacademy
261
Random-Access Files
• Often files are accessed in a linear structure, using sequential files

• But you can access contents of a file in random order if needed

• Use RandomAccessFile to compress random-access file

• Implements the DataInput and DataOutput interfaces (defines basic I/O methods)

• You can position the file pointer within the file

• RandomAccessFile implements the read() and write() methods

theknowledgeacademy
262
Random-Access Files
Example

o Source file

theknowledgeacademy
263
Random-Access Files
Example

theknowledgeacademy
264
Using Character-Based Streams
• Byte streams are not always the most efficient way to deal with character-based I/O in
Java

• A program using character streams automatically adapts to the local character set

• Easier for internationalisation without any alterations

• Uses 16-bit Unicode instead of 8-bit bytes like byte streams facilitate

• Applied by Reader and Writer at the top of the character stream hierarchy

• Methods defined by these abstract classes can be found in their subclasses

theknowledgeacademy
265
Methods Defined by Reader
Method Description

abstract void close() Closes the input source. Further read attempts will generate an IOException

void mark(int numChars) Places a mark at the current point in the input stream that will remain valid
until numChars characters are read

boolean markSupported() Returns true if mark()/reset() are supported on this stream

int read() Returns an integer representation of the next available character from the
invoking input stream. -1 is returned when the end of the stream is
encountered

int read(char buffer[ ]) Attempts to read up to buffer.length characters into buffer and returns the
actual number of characters that were successfully read. -1 is returned
when the end of the stream is encountered

theknowledgeacademy
266
Methods Defined by Reader
Method Description

abstract int read(char Attempts to read up to numChars characters into buffer starting at
buffer[ ], buffer[offset], returning the number of characters successfully read. -1 is
int offset, returned when the end of the stream is encountered
int(numChars)

int read(CharBuffer buffer) Attempts to fill the buffer specified by buffer, returning the number of
characters successfully read. -1 is returned when the end of the stream is
encountered. CharBuffer is a class that encapsulates a sequence of characters,
such as a string

Boolean ready() Returns true if the next input request will not wait. Otherwise, it returns false

void reset() Resets the input pointer to the previously set mark

long skip(long numChars) Skips over numChars characters of input, returning the number of characters
actually skipped

theknowledgeacademy
267
Methods Defined by Writer
Method Description

Writer append(char ch) Appends ch to the end of the invoking output stream. Returns
a reference to the invoking stream

Writer append(CharSequence Appends chars to the end of the invoking output stream.
chars) Returns a reference to the invoking stream. CharSequence is an
interface that defines read-only operations on a sequence of
characters

Writer append(CharSequence Appends the sequence of chars starting at begin, stopping with
chars, int begin, int end) end to the end of the invoking stream. CharSequence is an
interface that defines read-only operations on a sequence of
characters.

abstract void close() Closes the output stream. Further write attempts will generate
an IOException

abstract void flush() Causes any output that has been buffered to be sent to its
destination

theknowledgeacademy
268
Methods Defined by Writer
Method Description

void write(int ch) Writes a single character to the invoking output stream.
Parameter is an int, allowing you to call write() with expressions
without having to cast them back to char

void write(char buffer[ ]) Writes a subrange of numChars characters from the array buffer,
beginning at buffer[offset] to the invoking output stream

abstract void write(char buffer[ ], Writes a subrange of numChars characters from the array buffer,
int offset, beginning at buffer[offset] to the invoking output stream
int numChars)

void write(String str) Writes str to the invoking output stream


void write(String str, int offset, int Writes a subrange of numChars characters from the array str,
numChars) beginning at the specifies offset

theknowledgeacademy
269
Console Input
• For code that will be internationalised, inputting from the console using character-based
streams is better

• It is a much more convenient way to read characters from the keyboard

• It supports a buffered input stream, but you need to convert it from the System.in into a
character stream for it to work

theknowledgeacademy
270
How to Construct a BufferedReader
• You need to obtain an InputStreamReader to convert bytes to characters by using
constructors

Constructors

• This constructor can be used to obtain an InputStreamReader object that is linked to


System.in
InputStreamReader(InputStream inputStream)

• Then you can use the object produced to construct a BufferedReader using

BufferedReader(Reader inputReader)

• inputReader is the stream, linked to the instance of BufferedReader being created


theknowledgeacademy
271
Reader Characters
• Characters can be read from System.in using the read() method defined by
BufferedReader. There are three versions:

• int read() throws IOException

o Reads a single Unicode character

• int read(char data[]) throws IOException

o Reads characters from input stream

• int read(char data[], int start, int max) throws IOException

o Reads input data beginning at the location specified by start

theknowledgeacademy
272
How to Construct a BufferedReader
Example

• Using a BufferedReader to read characters from the console:

theknowledgeacademy
273
Console Output
Preferred method of writing to the console is through: PrintWriter

This is a character-based class which means it is easier to


internationalise your program

PrintWriter defines 7 constructors

It supports the print() and printIn() methods for all types including
Object

You can use these methods just as you would System.out

If the argument is not primitive type – PrintWriter will call object’s


toString() method and then print out result

theknowledgeacademy
274
Console Output Using Character Streams
• Writing to the console with PrintWriter:

o Specify System.out for the output stream

o Flush stream after each call to printIn()

o PrintWriter line of code connected to console output:

PrintWriter pw = new PrintWriter(System.out, true);

o System.out is still fine to write simple text output, for example when debugging
programs

o But PrintWriter is better for general, real-world applications


theknowledgeacademy
275
File I/O Using Character Streams
Byte-oriented file
handling is more
popular than They operate
character-based, directly on
but character Unicode characters
streams do have
their advantages

Use FileReader
Making them and FileWriter
better for storing classes to perform
Unicode tect character-based
file I/O

theknowledgeacademy
276
File I/O Using Character Streams
Using a FileWriter

• Creates a Writer for use to write to a file

• Most common constructors:

FileWriter(String fileName) throws IOException

FileWriter(String fileName, Boolean append) throws IOException

Using a FileReader

• Creates a Reader for use to read contents of a file


theknowledgeacademy
277
File I/O Using Character Streams
• Commonly used constructor:

FileReader(String filename) throws FileNotFoundException

theknowledgeacademy
278
Type Wrappers & Numeric Strings
• Reading numeric strings:

o Methods like read() do not provide parallel functionality that reads and converts a
string containing a numeric value into its internal format

o Instead you can use Type wrappers are classes that wrap the primitive types

o A primitive type cannot be passed by reference so Java provides classes that


correspond to each primitive type

o These classes offer a wide array of methods that allow you to fully integrate the
primitive types

o Type wrappers: Double, Float, Long, Integer, Short, Byte, Character, Boolean

theknowledgeacademy
279
Exercise

What is I/O?
Why do you need both byte and character streams?
What is the difference between byte and character streams?
What type of stream is System.in?
What is the Try statement used for?
What have you learnt so far about Reader and Writer?

theknowledgeacademy
280
Module 11: Multithreaded Programming

theknowledgeacademy
281
Multithreading Fundamentals

A multithreaded
program has two Multithreading is a
or more parts that specialised form of
can run multitasking
simultaneously

Multithreading
enables you to Multitasking has
utilise the idle time two distinct types:
that most
• Process-based
programs possess • Thread-based
by executing tasks
during this time

theknowledgeacademy
282
Multithreading Fundamentals

A program that is executing is


Process-based multitasking
essentially a process

Running two or more


For example, browsing the
programs simultaneously is
internet at the same time as using
permitted by process-based
spreadsheet program
multitasking

theknowledgeacademy
283
Multithreading Fundamentals

The smallest unit of


Thread-based multitasking
dispatchable code is the thread

For example, text can be


formatted at the same time
Two or more tasks can be
that it is printing in a text
performed simultaneously by
editor, as long as these actions
one program
are being performed by
different threads

theknowledgeacademy
284
Multithreading Fundamentals
A thread is able to be
in numerous different
states:

Terminated. Running
Execution ends and
cannot be resumed

Ready to run
Blocked. A thread is
waiting for a resource

Suspended. A
Resumed. A temporary halt to a
temporary halt is thread’s execution
ended

theknowledgeacademy
285
Thread Class and Runnable Interface
• The Thread class and Runnable interface (both packaged in java.lang) are what Java’s
multithreading system is built upon

• Creating a new thread means that either the Runnable interface is implemented, or the
program extends Thread

theknowledgeacademy
286
Thread Class Methods
• Below are some methods defined by the Thread class that helps to manage threads:

Method Meaning

final String getName( ) Obtains a thread’s name

final int getPriority( ) Obtains a thread’s priority

final boolean isAlive( ) Determines whether a thread is still running

final void join( ) Waits for a thread to terminate

void run( ) Entry point for the thread

static void sleep(long milliseconds) Suspends a thread for a specified period of milliseconds

void start( ) Starts a thread by calling its run( ) method

theknowledgeacademy
287
Thread Class Methods
(Continued)

• All processes have a least one thread of execution (usually called main thread). Other
threads can be created from the main thread

theknowledgeacademy
288
Creating a Thread
• As mentioned a thread can be created by extending the Thread class or implementing
the Runnable interface

• Extending the Thread class means defining a class that is derived from Thread. An object
of this derived class will be a thread

• The run( ) method must be overridden when a class extends Thread in order for the new
thread to do what you need it to

theknowledgeacademy
289
Creating a Thread
• A thread can be constructed on any object that implements the Runnable interface

• run( ) is the only method defined by Runnable:

public void run( )

• public void run( )

• The new thread will be defined by the code inside run( )

• run( ) can call other methods, use other classes and declare variables like the main
thread

theknowledgeacademy
290
Creating a Thread
Example

theknowledgeacademy
291
Creating a Thread
(Continued)

theknowledgeacademy
292
Creating Multiple Threads
• Your program can create as many threads as it needs

• Threads are not always started in the order that they are created

• Java can schedule the execution of threads in its own way

PRIORITIES
HIGH
MIDDLE
LOW

theknowledgeacademy
293
Determining When a Thread Ends
• You can determine if a thread has ended by calling either:

o isAlive( ) Returns true if the thread is still running. Returns false otherwise

o join( ) Waits until the thread terminates. Additional forms of join( ) allows you to
specify a maximum amount of time to wait for the thread to terminate

theknowledgeacademy
294
Thread Priorities

Each thread has a


The way the operating
priority setting CPU time is not
system implements
associated with it which exclusively determined If a high priority thread
multitasking and
partly determines how by a thread’s priority, is waiting on a resource
scheduling (e.g.
much CPU time a thread there are other factors (e.g. keyboard input)
preemptive vs.
receives in relation to that affect it
nonpreemptive)
other active threads

theknowledgeacademy
295
Synchronisation

Synchronisation is
most commonly
It is also needed The first thread
Synchronisation. used when a shared
when one thread is must then be held
Coordinating the resource, that can
waiting for an event in a suspended state
activities of two or only be used by one
that is caused by until the event has
more threads thread at a time, is
another thread occurred
needed by two or
more threads

theknowledgeacademy
296
Synchronisation
• All objects in Java have a monitor, which controls access to an object

• The concept of the monitor is key to synchronisation. It works by implementing the


concept of a lock:

o When an object is locked by one thread, the object cannot be accessed by any other
threads

o The object is unlocked when the thread exits, making it available to be used by other
threads

• A synchronised method is created by preceding its declaration with the keyword


synchronised

theknowledgeacademy
297
Synchronisation
Example

theknowledgeacademy
298
Synchronisation
(Continued)

theknowledgeacademy
299
Synchronisation
(Continued)

theknowledgeacademy
300
Synchronisation

The preceding example uses


a synchronised block

Using synchronised in this


way would allow you to
synchronise calls on an
object even if the class has
been created by a third
party

Once a synchronised block


has been entered, no other
thread can call a
synchronised method on
the object referred to until
the block has been exited

theknowledgeacademy
301
Thread Communication
For example, a thread (A) is
Threads need to executing inside a
communicate to each other synchronised method and
to optimise access to an needs access to a resource
object (B), which is temporarily
unavailable

A could tie up the object


waiting for B, preventing
other threads from accessing
the object which partially
defeats the advantages of a
multithreaded environment

theknowledgeacademy
302
Thread Communication
• To support the necessary communication, Java provides the following methods:

wait( )

notify( )

notifyAll( )

• Only within a synchronised context should these methods be called

theknowledgeacademy
303
Thread Communication
• wait( ) causes a thread to go to sleep by temporarily blocking it from running, allowing
another thread to use the object

• These are the various forms of wait( ) defined by Object

final void wait( ) throws InterruptedException Waits until notified

final void wait(long millis) throws Waits until notified or until the specified period of
InterruptedException milliseconds has expired

final void wait(long millis, int nanos) throws Allows you to specify the wait period in terms of
InterruptedException nanoseconds

theknowledgeacademy
304
Thread Communication
• notify( ) and notifyAll( ) awaken a sleeping thread when either is called by another
thread that has entered the same monitor

• These are the various forms of notify( ) and notifyAll( ) defined by Object

Form Description

final void notify( ) Resumes one waiting thread

final void notifyAll( ) Notifies all threads, with the highest priority thread gaining access to the object
first

theknowledgeacademy
305
Thread Communication
Example

theknowledgeacademy
306
Thread Communication
(Continued)

theknowledgeacademy
307
Thread Communication
(Continued)

theknowledgeacademy
308
Thread Communication
(Continued)

theknowledgeacademy
309
Suspending, Resuming, and Stopping Threads
• Prior to Java 2 the execution of a thread could be paused, restarted, and stopped using
suspend( ), resume( ) and stop( ) methods, respectively

• These methods were all deprecated by Java 2

• Suspending, resuming, and stopping a thread’s execution is still possible by establishing


two flag variables:

o One for suspend and resume

o One for stop

theknowledgeacademy
310
Exercise

• Fill in the blanks:


o The [?] class and the [?] interface support multithreading in Java

• If you add the synchronised keyword to a method, what is the


effect?

theknowledgeacademy
311
Module 12 : Enumerations, Autoboxing,
Static Import, Annotations

theknowledgeacademy
312
Enumerations
• Enumeration defines a new data type through a list of named constants

• Objects of an enumeration type can hold only values defined by this list

• It allows you to define a new type of data which will have a fixed number of valid values

• Useful for when you need to define a set of values that represent a collection of items

• Offers a more structured approach to what was known in the past as final variables

theknowledgeacademy
313
Enumeration Fundamentals
• Use the enum keyword to create enumeration

//An enumeration of transportation


enum Public Transport Basic example of
{ enumeration
BUS, TRAIN, TAX
}

enumeration constants, public


static member of Transport

• After defining an enumeration, you can create a variable of that type

theknowledgeacademy
314
Enumeration Fundamentals
(Continued)

• Although enumerations define a class type, you cannot instantiate an enum using new

• You have to declare the enumeration like you would a primitive type

theknowledgeacademy
315
Enumeration Fundamentals
Public Transport tp • tp is the variable of enumeration
type Public Transport

tp = Public Transport.BUS; • The only values tp can be assigned


are those defined by its enumeration

if(tp == Public Transport.TRAIN) // • Two enumeration constants can be


compared for equality using ==
//Use an enum to control switch
Switch(tp) { • An enumeration value can be used
case CAR:
to control a switch statement
//…
case TRUCK:
//…

theknowledgeacademy
316
The values() and valueOf() Methods
• Enumerations are class types, so acts like other classes

• This enables enumeration to have capabilities such as constructors, adding instance


variables/methods and implementing interfaces

• Enumerations will automatically include values() and valueOf() predefined methods

• value() = returns array that contains list of enumeration constants

• valueOf() = returns enumeration constant whose value corresponds to string passed in


str

public static enum-


public static enum-
type
type[] values()
valueOf(String str)

theknowledgeacademy
317
Constructors, Methods, Instance Variables,
and Enumerations
• Defining a constructor for an enum:

o Once you define a constructor for an enum, the constructor is called

o Each enumeration constant has the ability to call any method stated by the
enumeration

o They also hold a copy of any instance variables defined by the enumeration

theknowledgeacademy
318
Constructors, Methods, Instance Variables,
and Enumerations
(Continued)

• Restrictions:

o Enumerations are not able to inherit another class

o An enum can also not be made into a superclass, so extending is not possible

theknowledgeacademy
319
Constructors, Methods, Instance Variables,
and Enumerations
Example:

theknowledgeacademy
320
Constructors, Methods, Instance Variables,
and Enumerations
(Continued)

theknowledgeacademy
321
Enumerations Inherit Enum
• All enumerations inherit a superclass automatically: java.lang.Enum

• This defines several methods including:

Ordinal() = final int ordinal()

• Obtains a value that can indicate an enumeration constant’s position in a list of


constants Known as ordinal value

• Returns ordinal value of the invoking constant

• Ordinal values begin at zero

theknowledgeacademy
322
Enumerations Inherit Enum
(Continued)

CompareTo() = final int


compareTo(enum-type e)

• Compares the ordinal value of two constants of the same enumeration

• Both the invoking constant and e must of the same enumeration

• Invoking constant has ordinal value less than e = negative return value

theknowledgeacademy
323
Enumerations Inherit Enum
(Continued)

• Invoking constant has ordinal value more than e = positive return value

• If two ordinal values are the same = zero is returned

theknowledgeacademy
324
Using Enumerations
• Enumerations are particularly useful when your program needs a set of constants

• The actual value of the constants are arbitrary as long as all differ

• This can be a common situation you run into when programming

• An enum can be declared outside or inside a class, but not in a method

Adding new constants on enum is simple and


you can do it without breaking existing code

theknowledgeacademy
325
Autoboxing
• Type Wrappers:

o Autoboxing and unautoboxing simplifies and streamlines code that must convert
primitive types into objects

o Autoboxing and unautoboxing is directly related to type wrappers

• As mentioned previously, these are classes that hold a primitive type within an object
(most commonly used ones are highlighted in bold):

o Double, Float, Long, Integer, Short, Byte, Character, Boolean

theknowledgeacademy
326
Type Wrappers
• All the numeric type wrappers inherit the abstract class Number

• Number declares methods that returns the value of an object in each different numeric
type

• These methods are implemented by each of the numeric type wrappers. They include:

byte byteValue(), double doubleValue(), float floatValue(), int


intValue(), long longValue(), short shortValue()

• All the numeric type wrappers define constructors which allow objects to be
constructed from a given value/string

theknowledgeacademy
327
Type Wrappers
• An example of constructors defined for Integer and Double would be:

Integer(int num)
Integer(String str) throws NumberFormatExeption,
Double(double num),
Double(String str) throws NumberFormat Exception

• If str does not contain valid numeric value, then NumberForatException is used

• All type wrappers override toString()

theknowledgeacademy
328
Type Wrappers
(Continued)

• Returns readable value. Can output the value by passing type wrapper object to
printIn() without converting to primitive type

theknowledgeacademy
329
Autoboxing Fundamentals
• Boxing: Encapsulating a value within an object

• Unboxing: Extracting a value from a type wrapper

• Autoboxing: Automatically encapsulating primitive type into equivalent typewrapper


(boxed)

Primitive Type Object

theknowledgeacademy
330
Autoboxing Fundamentals
(Continued)

• Auto-unboxing: Automatically extracting the value of a boxed object from a


typewrapper (unboxing)

Object Primitive Type

theknowledgeacademy
331
Autoboxing and Methods
• Autoboxing/unboxing
//Autoboxing/Unboxing example
may take place when an //method parameters and return values
argument is passed to a
classAutobox { Receiving
method an Integer
// This method has an Integer parameter
static void m(Inteher v) {
• It can also occur when a value System.out.printIn(“m() received “ + v);
}
is returned by a method
//This method returns an int Returning
static int m2() int
return 10;
}

//This method returns an Integer.


static Integer m3() { Returning
return 99; // Autoboxing 99 into an Integer Integer

theknowledgeacademy
332
Autoboxing/Unboxing in Expressions

When Autoboxing
and unboxing This can occur in Using numeric
takes place The outcome of
exceptions, where objects in an
this expression
It is usually when a numeric object expression
can also be
a conversion into is automatically becomes easier
reboxed
or from an object unboxed with this
is needed

theknowledgeacademy
333
Static Import

An import statement can be used Using this allows you to refer to


to import static members of a This is known as static import static members by their names
class or interface directly

This is especially useful when


Thus simplifying the syntax defining several static members
required to use a static member that are used frequently
throughout a large program

theknowledgeacademy
334
Static Import
Example:

theknowledgeacademy
335
Static Import
• In the previous example sqrt and pow are brought
into view by the import statements

• Once these statements have deployed it is no


longer necessary to qualify sqrt() or pow() with its
class name // Find first solution.
x = (-b + sqrt(pow(b, 2) – 4 * a * c)) / (2 * a);
System.out.printIn(“First solution: “ + x);
• The expression can more conveniently be specified
as: //Find second solution.
x = (-b – sqrt(pow(b, 2) – 4 * a * c)) / (2 * a);
System.out.printIn(“Second solution: “ + x);
}
}

x = (-b + sqrt(pow(b, 2) – 4 * a * c)) / (2 * a);

theknowledgeacademy
336
Annotations (Metadata)
• Annotation a form of metadata (data which contains information about itself)

• It is supplemental information, which has no effect on the Java program

• Annotations can be used in classes, methods, packages, parameters, and variables

• They can be created through a mechanism based on an interface

//Annotation example.
@interface MyAnno {
String str();
int val();
}

theknowledgeacademy
337
Annotations (Metadata)
(Continued)

• The annotation declared is MyAnno


//Annotation example.
• @ is used to signal compiler the @interface MyAnno {
String str();
annotation int val();
type is being declared }

• All annotations consist solely of method


declarations

theknowledgeacademy
338
Annotations Pt. 2
• Annotation types can all automatically reach the Annotation interface

• This means that Annotation becomes a super-interface for all annotations

• Within the package this is declared as java.lang.annotation

• When you apply an annotation, you give values to its members

• When an annotation member is given a value, only its name is used, so the annotation
members begin to look like fields

theknowledgeacademy
339
Annotations
• Marker annotation: An annotation without a parameter, specified without passing any
arguments or using parenthesis. Purely used to mark an item with some attribute

• Built-in annotations imported from java.lang.annotation: @Retention, @Documented,


@Targeted, @Inherited

• Built-in annotations included in java.lang.: @Override, @Deprecated, @SafeVarargs,


@SuppressWarnings, @FunctionalInterface

theknowledgeacademy
340
Exercise

• What does enumeration do?


• When is it useful?
• Which predefined methods does enumeration include?
• Which class do it automatically inherit?
• Define Autoboxing
• What does static import do?

theknowledgeacademy
341
Module 13: Generics

theknowledgeacademy
342
Generics Fundamentals
• Since its inception in Java 5, generics fundamentally reshaped the character of Java

• Generic methods and generic classes allow you to specify a set of related methods or
types with single method or class declarations, respectively

• Compile-time type safety is also provided by generics enabling you to catch invalid types
at compile time

theknowledgeacademy
343
Generics Fundamentals
Example:

theknowledgeacademy
344
Generics Fundamentals
(Continued)

theknowledgeacademy
345
Generic Types
• When declaring an instance type of a generic type, it cannot be a primitive type (such as
int or char), it has to be a reference type

• A reference of one specific version of a generic type is not type-compatible with another
version of the same generic type

iOb = strOb;

• This line of code won’t compile. iOb and strOb are both of type <GenericClassT>;
however they are references to different types because their type arguments differ

theknowledgeacademy
346
Generic Types
• More than one type parameter can be declared in a generic type, for example

TwoGenericClas
s<T, S>

• Two parameters, T and S are specified and separated by a comma

• Two type arguments must now be passed to TwoGenericClass because it has two type
parameters

theknowledgeacademy
347
Exercise

Declare a generic class called BusSched that takes


two generic parameters

theknowledgeacademy
348
Bounded Types
• Bounded type parameters restrict the types that can be used as type arguments in a
parameterised type

• When specifying the parameter use an extend clause to create an upper bound which
declares the superclass that all type arguments must be derived from, for example:

Class NumericFns <T extends Number>

In this case the type argument must be


either Number or a subclass of Number

theknowledgeacademy
349
Wildcard Arguments

Despite its usefulness, type safety can sometimes


obstruct perfectly acceptable constructs

As such, Java generics provides the wildcard


argument which is specified by the ? And represents
an unknown type

Notice how the wildcard argument is used in the following


example:

theknowledgeacademy
350
Wildcard Arguments
Example:

theknowledgeacademy
351
Wildcard Arguments
(Continued)

theknowledgeacademy
352
Wildcard Arguments
(Continued)

theknowledgeacademy
353
Wildcard Arguments
(Continued)

System.out.print (“Averages of iob and dob “);


if iob.sameAvg(dob)){
System.out.println (“are the same.”); In this call, the wildcard
}else{ matches Float
System.out.println (“differ.”);
}

System.out.print (“Averages of iob and fob “);


if iob.sameAvg(fob)){
System.out.println (“are the same.”); In this call, the wildcard
}else{ matches Float
System.out.println (“differ.”);
}
}
}

theknowledgeacademy
354
Bounded Wildcards
• As you have seen, type parameters can be bounded. Similarly, wildcard arguments can
also be bounded in the same way

• This is especially important when you are creating a method that is designed to only
operate on objects that are subclasses of a specific superclass

• Establishing an upper bound for a wildcard uses the following form:

<? extends superclass>

theknowledgeacademy
355
Generic Constructors and Interfaces

All generic method declarations have a type parameter section


delimited by angle brackets that precedes the method’s return type

Each type parameter section contains one or more type


parameters separated by commas

The type parameters can be used to declare the return type and
act as placeholders for the types of the arguments passed to the
generic method, which are known as actual type arguments

theknowledgeacademy
356
Generic Constructors and Interfaces

Similarly, an interface
A constructor can be can also be generic interface interface-
generic, even when its which are specified just name<type-parameter-
class is not like generic classes using list>
this general form:

theknowledgeacademy
357
Generic Constructors and Interfaces
Example:

theknowledgeacademy
358
Generic Constructors and Interfaces
(Continued)

theknowledgeacademy
359
Raw Types and Legacy Code

As generics were
introduced in JDK5,
support for generics did
not exist

Subsequently Java had to


provide some transition
path from pre-generics
code

Java did this by creating a raw


type, which allows a generic It is compatible with The type safety of
class to be used without any legacy code generics is lost
type arguments

theknowledgeacademy
360
Diamond Operator
• Since JDK7 the syntax used to create an instance of a generic type has been shorted by
the diamond operator, for example:

TwoGen<Integer, String> tgOb =


new TwoGen<Integer, String>(42,
“testing”;

• Can be rewritten as:

TwoGen<Integer, String> tgOb =


new TwoGen<>(42 “testing”);

theknowledgeacademy
361
Diamond Operator
(Continued)

Diamond Operator

• The compiler is told to infer the type arguments needed by the constructor in the new
expression

theknowledgeacademy
362
Erasure and Ambiguity Errors
• Erasure is the way that generics are implemented in Java:

o All generic type information is removed

o Type parameters are replaced with their bound type

o If no bound is specified then Object is used

o This approach to generics means no type parameters exist at run time

• When erasure causes two (seemingly) distinct generic declarations to resolve to the
same erased type, a conflict is caused, and ambiguity errors occur

theknowledgeacademy
363
Generic Restrictions
• It is impossible to create an instance of a type parameter

• No static member can use a type parameter declared by the enclosing class

o Static generic methods, which define their own type parameters can be declared

• An array cannot be instantiated whose element type is a type parameter

• An array of type-specific generic references cannot be created

• A generic class cannot extend Throwable

theknowledgeacademy
364
Exercise

Change BusSched’s (from the earlier exercise) second type


parameter so that it is a subclass of its first type parameter

What is the ? in relation to generics?

What is the empty type argument list, <>, called in generics?

theknowledgeacademy
365
Module 14: Swing

theknowledgeacademy
366
Origins of Swing

Created due to AWT had limitations Which meant it


from the start - it Led to frustrating was defined by the
ongoing problems
translated various visual restrictions – platform, not Java,
T Introduced to Java with Java’s Abstract
components into heavyweight using native code
Window Toolkit
corresponding, platform- component opaque resources (heavy
(AWT)
specific equivalents weighting)

theknowledgeacademy
367
Origins of Swing
• Swing was introduced as part of the JF Classes

• It was available as a separate library in Java 1.1

• But it was soon integrating within Java come Java 1.2

• It addressed problems with the AWT’s components, introducing:

1 Lightweight components

2 Pluggable look and feel

theknowledgeacademy
368
Origins of Swing
(Continued)

Lightweight Components Pluggable Look and Feel

• Possible to separate look and feel of a


• A component is written entirely in Java component

• Do not rely on platform-specific peers • Can change the way a component is


rendered without any side effects
• Each component can be consistent
across all platforms • Modified version of model-view-
controller

theknowledgeacademy
369
MVC Architecture
• Model the state information associated with a component

• View determines how component is displayed on screen

• Controller determines how component reacts to the user

• Separating each component allows you to make changes to certain ones without
affecting the other

• Swing used this principle, but altered it to combine the view and controller into a single
entity called UI delegate

theknowledgeacademy
370
Components and Containers
• Swing Graphical user Interface (GUI) made up of components and containers

• Component independent visual control

• Container holds a group of components

• A component can only be displayed if it is held within a container

• So all Swing GUI’s must have one container

• Swing defines a containment hierarchy

• At the top = a top-level container

theknowledgeacademy
371
Components and Containers
Components

• Aside from the four top-level containers, Swing components usually come from the
JComponent class

• JComponent: supplies the functionality common to all components, supporting


pluggable look and feel

• Inherits AWT classes Container and Component

• All Swing’s components are represented by classes defined within javax.swing

theknowledgeacademy
372
Components and Containers
(Continued)

• Commonly used components:

JTextField JButton

1 2 3 4 5

JLabel JCheckBox JList

theknowledgeacademy
373
Components and Containers
Containers

• There are two types of containers from Swing:

Top-Level Containers Lightweight containers

JFrame JPanel

JApplet JScrollPane

JWindow JRootPane

JDialog

theknowledgeacademy
374
Components and Containers
(Continued)

• Top-level do not inherit JComponent

• They do inherit AWT classes Component and Container

• They are heavyweight and top of the hierarchy

• Lightweight containers do inherit JComponent

• They are used to manage related components

• They can be contained within another container

theknowledgeacademy
375
Top-Level Container Panes
• Each top-level container defines a set of panes

• JRootPane is a lightweight container which can be found at the top of the hierarchy

• It manages other panes and helps to manage optional menu bar

• Panes that make up the root pane, glass pane, content pane, layered pane

theknowledgeacademy
376
Top-Level Container Panes
(Continued)

Glass pane top-


Layered pane gives level pane. Covers
components a all other panes.
depth value Sits above. (The
Boss)

GP Allows you to
CP Holds the manage mouse
components that events that affect
the user interacts entire container,
with or to paint over
any other
component
Content pane
used the most.
Use this pane to
add visual
components to it

theknowledgeacademy
377
Layout Managers
• Layout manager: It controls position of components within a container. Presents several
layout managers (AWT and Swing)

• All layout managers are instances of a class that implements the LayoutManager
interface
Description

FlowLayout Simple layout positions components left-to-right, top-to-bottom

BorderLayout Positions components within the centre or the borders of the container Default
layout for a content pane
GridLayout Lays out components within a grid
GridBagLayout Lays out different sized components. Flexible grid
BoxLayout Lays out components vertically/horizontally within a box
SpringLayout Lays out components subject to set of constraints

theknowledgeacademy
378
Layout Managers
Example

theknowledgeacademy
379
Layout Managers
Example

theknowledgeacademy
380
JButton
• One of the most commonly used Swing controls is the push button. Jbutton is an
implementation of this

• Jbutton inherits abstract class AbstractButton

• This defines functionality common to all buttons

• Push buttons may contain text and image

• Provides several constructors such as, Jbutton(String msg)

• Push button pressed: activates ActionEvent

• You can obtain several useful features by using ActionEvent object passed to
actionPerformed() e.g. action command
theknowledgeacademy
381
Work with JTextField
• JTextField commonly used control enabling user to enter a line of text. It

o Inherits abstract class JTextComponent, this is the superclass of all text components

o JTextField defines several constructors including: JTextField(int cols)

o Similar to a Jbutton a JTextField also has an action command string

o This is the current content of the text field by default, but we will more oftenly use
setActionCommand() method to set the action command to a fixed value of your
choice

theknowledgeacademy
382
Create a JCheckBox
• The Check Box: An object of type JCheckBox:

o Inherits AbstractButton and JToggleButton

o Defines several constructors e.g. JCheckBox(String str)

o When a check box is selected or deselected an item event is generated

o These are represented by the ItemEvent class

o Item events are handled by classes that implement the ItemListner interface

theknowledgeacademy
383
Create a JCheckBox
• This interface specifies only one method: itemStateChanged()(ItemEvent ie)

• Use method Object getItem() to obtain a reference to the item that changed

• Reference returned must be cast to component class being handled – JCheckBox

• May obtain text associated with a check box by calling getText()

• Set the text after a check box is created by calling setText()

theknowledgeacademy
384
Working with JList
• JList basic list class, supporting selection of one or more items from a list

• It is possible to create a list of just about any object that can be displayed

• Generic declaration of JList:


class JList<E>

• E represents type of items on list. JList is now type-safe:

JList(E[] items)

• This creates a JList containing the items in an array specified by items

theknowledgeacademy
385
Working with JList
• JScrollPane container automatically providing scrolling for contents. Example:

JScrollPane(Component comp)

• comp specifies component to be scrolled (JList)

• After wrapping JList and JScrollPane, long lists become automatically scrollable, making
it simpler to change number of entries in a list

• JList generate ListSelectionEvent

• Handles by executing ListSelectionListener, packaged in Java.swing.event, listener


specifying valueChanged() method:

void valueChanged(ListSelectionEvent le)


theknowledgeacademy
386
Working with JList
• A JList allows the user to select multiple ranges of items within the list which looks like:

void setSelectionMode(int mode)

• Here mode specifies selection mode

• Must be one of these values defined by ListSelectionModel interface:

SINGLE_SELECTION = user can select just one single item


SINGLE_INTERVAL_SELECTION = user can select one range of items
MULTIPLE_INTERVAL_SELECTION = user can select multiple ranges of items
within list

theknowledgeacademy
387
Working with JList
Example

theknowledgeacademy
388
Working with JList
(Continued)

theknowledgeacademy
389
Working with JList
(Continued)

Output

theknowledgeacademy
390
Exercise

Try creating a Swing-based file comparison utility program


Create file SwingFC.java with import statements
Create SwingFC class
Code the SwingFC constructor, note: action listeners are not added to text fields
Begin creating actioPerformed() event handler by starting with the Compare button
to call method
Finish this by adding code to open files and compare them
Add main() method to finish

theknowledgeacademy
391
Handling Events
With Anonymous Inner Classes

• An effective way to handle events

• Inner classes with no name

• Generated “on the fly” as needed

• Easier to handle implementing types of events with them

• Component that invokes class methods is already known

theknowledgeacademy
392
Handling Events
(Continued)

jbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// Handle action event here.
}
});

theknowledgeacademy
393
Handling Events
With Lambda Expressions

• If you have an event whose listener defines a functional interface, it is possible to


handle this better with lambda expressions

• ActionListener will define only one abstract method

• Using a lambda expression to implement ActionListener provides a compact alternative


to explicitly declare an anonymous inner class

Implementing the action listener in JButton:

jbtn.addActionListener((ae) -> {
// Handle action event here
});

theknowledgeacademy
394
Create Swing Applet
• Swing-based applets are similar to AWT-based applets

• Extends JApplet rather than Applet

• Includes functionality found in Applet, adding support for Swing

• Top-level Swing container, including various panes

• All components added to JApplet’s content pane similar to how they are added to
JFrame’s

• Uses the four life-cycle methods init(), start(), stop(), destroy()

• Override methods needed by your applet. All interaction with components in Swing
applet has to happen on event-dispatching thread
theknowledgeacademy
395
Exercise

Why was Swing introduced?


What did it do?
What does MVC Architecture stand for?
Define component and container
Explain panes.
JList displays a list of items from which the user can select,
true or false?

theknowledgeacademy
396
Module 15: JavaFX

theknowledgeacademy
397
Origins of JavaFX
• JavaFX handles the demands of a modern GUI and the GUI design advancements

• It is a next-generation GUI framework

• Originally a scripting language, it is now fully integrated into Java itself

• Introduced as a comprehensive API in JDK 8

• Will eventually replace Swing

theknowledgeacademy
398
Basic Concepts
• Similarities to GUI, AWT, Swing:

o Lightweight components, managing events simplified, straightforward to us

• Differences to GUI, AWT, Swing:

o Organisation of JavaFX, relationship of main components

• Packages:

o JavaFX framework contained in packages beginning with javafx prefix

o More than 30 JavaFX packages in API library

o Offers wide range of functionality


theknowledgeacademy
399
Basic Concepts
(Continued)

• Stage and Scene Classes:

o Stage: JavaFX central metaphor. A container for scenes. A top-level container

o Primary stage: automatically accessed. Supplied by run-time. Main stage required

o Scene: Defines what is going on in the stage. Includes controls such as check boxes,
push buttons, graphics, text

• Held in JavaFX API through Stage and Scene classes

• Every JavaFX application must contain a stage and a scene

theknowledgeacademy
400
Basic Concepts
(Continued)

• Layouts:

o JavaFX introduced several layout panes to manage the process of placing elements
in a scene
o Example: FlowPane which provides a flow layout

• Application Class:

o Each JavaFX application must be a subclass of Application class


o This is packaged in javafx.application
o Application class defines three life-cycle methods (which your application can
override)
o int(), start(), stop()
theknowledgeacademy
401
Launching JavaFX Application
• First to begin a free-standing application call Launch()

• This method is defined by Application

• It has two forms but we will look at:

public static void launch(String…args)

• This form of launch() starts the subclass of Application

• Second type allows you to specify a different class to the enclosing one implemented at
the start

theknowledgeacademy
402
JavaFX Application Skeleton
• Every JavaFX application has the same basic skeleton

• Becoming familiar with this skeleton will help you to understand the general form that
will be used for all your JavaFX applications

• The skeleton illustrates how to launch a JavaFX application

• It demonstrates when life-cycle methods are called by noting when each life-cycle
method is called

theknowledgeacademy
403
Example

theknowledgeacademy
404
Example
Output

theknowledgeacademy
405
Compiling and Running JavaFX
• You can run the same program in a variety of different execution environments with
JavaFX

• Depending on target execution environment further steps may be needed

• Often easier to compile JavaFX application with the Integrated Development


Environment

Application Thread

• The stage or scene must be constructed on the application thread. However the
application’s constructor and init() method must be done on the launcher thread. They
cannot be used to make a stage/scene. Which is why you must use start()

theknowledgeacademy
406
Label
• JavaFX Control. Control is an essential element to JavaFX because it allows the user to
interact with the application

• There are various controls within the system to be used. Label is a simple control used
to display a message or image

• Learning how to do this will give you the basic idea of how to begin building a scene
graph

• JavaFX label is an instance of Label class. Packaged in: javafx.scene.control

• Inherits: Labeled, defines several common features, Control defines features related to
all controls

theknowledgeacademy
407
Label
• Label constructor. Label(String str). Any control such as the Label must be added to the
scene’s content

• To do this you need to add it to a scene graph, calling getChildren() on the root node of
it

• There it returns a list of child nodes formed as ObservableList<Node>

• ObservableList –> packaged in javafxcollections -> inherits java.util.List (part of JCF)

• List defines collection that represents a list of objects

• Just call add() on child nodes list to pass in label reference

theknowledgeacademy
408
Label
Example

• You can see here how the label is added to the


list of children for which rootNode is the parent
Demonstrating a label:

• It is possible to separate this into two lines if //Create label.


needed Label myLabel = new Label (“This is
JavaFX”);
• To remove a control simply call remove(): //Add the label to the scene graph.
rootNode.getChildren().add(myLabel);

rootNode.getChildren().remove(myLabel);

theknowledgeacademy
409
Buttons and Events
• Handling events: Most GUI controls generate events that are handled by your program

• Buttons, check boxes, lists all generate events when they are activated

• Event handling in JavaFX has many similarities to doing so in Swing

• It is more streamlined and commonly uses the button control

theknowledgeacademy
410
Buttons and Events
Event Basics

• Event: the base class for JavaFX events, it is packaged in javafx.event and inherits
java,util.EventObject

• There are several subclasses of Event defined in Java

• We will look at ActionEvent, this encapsulates action events generated by a button

• To handle an event, register the handler that acts as the listener first

• Then when the event occurs the listener will be called

theknowledgeacademy
411
Buttons and Events
(Continued)

• Events are handled by implementing EventHandler:

Interface EventHandler<T extends Event>

• Event object as parameter is:

void handle (T eventObj)

theknowledgeacademy
412
Button Control
• Push Button Control, found by the Button class javafx.scene.control. Inherits base
classes ButtonBase, Labeled, Control, Region, Parent, Node

• Button supports a wide range of array options. It can contain text as well as graphic

• Buttons default form is: Button(String str)

• str is the message which appears displayed in button

• ActionEvent generates when button is pressed

• This is packaged in javafx.event

• You can use setOnAction() to register listener

theknowledgeacademy
413
CheckBox Control
• CheckBox class, with ButtonBase as its immediate superclass

• Appears in three states: checked, unchecked and indeterminate (or undefined).

• An indeterminate checkbox is usually used to indicate that the state of the checkbox
has not been stated or is not relevant

• You have to explicitly enable an indeterminate state

• Example of CheckBox constructor: CheckBox(String str)

• str is the text specified as label. CheckBox will generate an action event when selected

theknowledgeacademy
414
ListView Control
• ListView, commonly used control that displays a list of entries, from which you can
select one or more

• Features scrollbars that can be automatically added when a number of items in a list
exceeds the number that can be displayed

• Makes efficient use of limited screen space

• A popular alternative to other types of selection controls

• ListView’s generic class: class ListView<T>

• ListView constructor: ListView (ObservableList<T>list)

• Here the list of items to be displayed is specified by list


theknowledgeacademy
415
ListView Control
• list is an object type of ObservableList which supports the list of objects

o By default ListView lets just one item be selected at a time in the list

o You can enable multiple selections in ListView by calling setSelectionMode() on the


ListView model

o In single-selection mode the easiest way to create ObservableList in the ListView is


to use the observableArrayList() factory method

o You will be provided with a default size but you can change these if needed using
setPrefHeight() and setPrefWidth(), or setPrefSize()

theknowledgeacademy
416
Using ListView
• To use ListView you can either obtain the selection in the list when your program needs
it (ignoring the events generated), or:

o Monitor list for changes by registering a change listener

o A change listener is supported by the ChangeListener interface, packaged in


javafx.beans.value

o It defines changed() method:

void changed(ObservableValue<? extends T> changed, T oldVal, T newVal)

theknowledgeacademy
417
TextField Control
• TextField is useful for entering a string of your own choosing, allowing one line of text
to be entered by user

• Good for collecting names, ID strings, addresses etc.

• TextField inherits TextInputControl

• Use default constructor or specify field yourself

• To specify size you can call:

final void setPrefColumnCount(int columns)

theknowledgeacademy
418
TextField Control
(Continued)

• columns value is used by TextField determining size

• To set/get text in a text field: call setText(), or getText()

• Use setPromptText() to set a prompting message

theknowledgeacademy
419
Effects and Transforms
• The great thing about JavaFX is having the ability to change so much

• The look of a control and the node in a scene graph can all be altered

• To do this you want to use the effect and/or transforms applications

• Useful for creating a more stylish and classy appearance

• Sophisticated and modern

theknowledgeacademy
420
Effects and Transforms
Effects

• Effects maintained by Effect class, abstract, with concrete subclasses. Packaged in


javafx.scene.effect

• Effects give you the ability to customise a node in the scene graph. There are several
built-in effects:
Bloom Increases
BoxBlur Blurs a node
DropShadow Displays a shadow that appears behind the node
Glow Produces a glowing effect
InnerShadow Displays a shadow inside a node
Lighting Creates shadow effects of a light source
Reflection Displays a reflection

theknowledgeacademy
421
Effects and Transforms
(Continued)

• The effects shown in the table are available for use with any Node. To set an effect on a
node, you need to call setEffect()

final void setEffect(Effect effect)

• To specify no effect you need to pass null. To add an effect node you need to create
instance of that effect and pass it to setEffect()

• Once done this will be used when the node is rendered. Example: BloxBur = use to blur
a node. Adjusts pixels within a rectangular region. You can control blur amount

BoxBlur(double width, double height, int iterations)

theknowledgeacademy
422
Effects and Transforms
Transforms

• Transforms = maintained by Transform class. Abstract. Rotate, Scale, Shear, Translate all
examples of its subclasses. Packaged in javafx.scene.transform

• Transform gives you the ability for multiple transformations by performing more than
one transform on a node. Inserting a transform by adding it to the node list:

final ObservableList<Transform>getTransforms()

• This returns a reference to the list of transforms

• To add a transform use add(), to clear use clear(), to remove use remove()

theknowledgeacademy
423
Effects and Transforms
• It is also possible to specify a transform directly through setting a Node property

• Setting rotation angle of a node, with a pivot point in the centre:

o Call setRotate() to pass desired angle


o Set scale using setScaleX and setScaleY()
o Translate nodes with setTranslateX(), setTranslateY()

• Rotate constructor:

o angle = number of degrees to rotate


o x, y = specifies the pivot point

Rotate(double angle, double x, double y)

theknowledgeacademy
424
Exercise

What is JavaFX?
Explain Stage and Screen
Name the 3 lifecycle methods application defines
What is launch()?
How would you add a button?
What is the difference between effects and transforms?

theknowledgeacademy
425
The World’s Largest Global Training
Provider
theknowledgeacademy.com

[email protected]

/The.Knowledge.Academy.Ltd

/TKA_Training

/the-knowledge-academy

/TheKnowledgeAcademy

Congratulation
s
426

You might also like