Java Programming - Delegate Pack
Java Programming - Delegate Pack
Java Programming
theknowledgeacademy
About Us
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
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
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
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
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:
• 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
• 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
theknowledgeacademy
11
Java and the Internet
theknowledgeacademy
12
What is Bytecode?
• Bytecode is a sequence of instructions designed to be implemented by the 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
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
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
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
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
• 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
• 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 ;
theknowledgeacademy
22
Keywords & Identifiers
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
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.
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:
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
theknowledgeacademy
30
Integers
theknowledgeacademy
31
Floating-Point Types
• Java has two kinds of floating-point types:
• These types can represent numbers that have fractional components, which integers
cannot
theknowledgeacademy
32
Floating-Point Types
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
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’ ;
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
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
theknowledgeacademy
38
Instructions
Create a new file called Sound.java
To compute the distance, you will multiply 9.6 by 1,100. This value
will then be assigned to a variable
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;
}
}
theknowledgeacademy
40
Literals
• Literals are fixed values that are represented in their human-readable form (also
commonly known as constants)
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
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 ‘%’
type var-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:
int a = 456
o The assignment statement puts the value 456 into the variable
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
theknowledgeacademy
45
Variables
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
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
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
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
theknowledgeacademy
55
Exercise
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
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 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
theknowledgeacademy
67
The for Loop
• Used for repeating a single 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:
• 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
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
• 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
theknowledgeacademy
74
Declaring Loop Control Variables Inside the
for Loop
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
theknowledgeacademy
76
The while Loop
• Just like the for loop, the while loop checks the conditional expression at the top of the
loop
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
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
theknowledgeacademy
82
The break Statement
Example:
theknowledgeacademy
83
The continue Statement
Example:
theknowledgeacademy
84
Exercise
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
• 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
• A class should describe only one logical unit to avoid becoming unrelated and
destructured
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
• The object contains its own copy of each instance variable defined by the class
theknowledgeacademy
90
Defining a Class
(Continued)
Syntax:
theknowledgeacademy
91
How Objects are Created
• You create an object from a class
theknowledgeacademy
92
How Objects are Created
(Continued)
Example:
theknowledgeacademy
93
Reference Variables
• Reference: leads you to something
theknowledgeacademy
94
Methods
• Methods are subroutines that alter the data defined by the class and provide access
• A method has a name (this can be what you like but don’t use Java’s keywords)
theknowledgeacademy
95
Methods
• Syntax:
• Example:
theknowledgeacademy
96
Returning from a Method
• There are following two ways of returning a method:
theknowledgeacademy
97
Returning from a Method
Example of Range() method
theknowledgeacademy
98
Returning from a Method
Void Method
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
theknowledgeacademy
101
Constructor
Example:
theknowledgeacademy
102
New Operator
• The new operator creates a new object of any class type
Syntax:
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
theknowledgeacademy
105
Finalize
• Finalize method is used to terminate an object cleanly
• To add to a class you need to define the method, so that it is used when an object is
about to recycle
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
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
Syntax:
dataType[] arr;
theknowledgeacademy
110
Arrays
Example:
theknowledgeacademy
111
One-Dimensional Arrays
• One-dimensional arrays use this general form:
• 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
• Syntax: There are the following three methods to declare one-dimensional array
theknowledgeacademy
113
One-Dimensional Arrays
Example:
theknowledgeacademy
114
Two-Dimensional Arrays
• The two-dimensional array is the simplest form of the multidimensional array
• 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
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
• 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:
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 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:
theknowledgeacademy
122
The for-each Style for Loop
Example:
theknowledgeacademy
123
Strings
• String is one of the most important data types in Java
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)
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
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
• 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
theknowledgeacademy
136
Passing an Argument
Example:
theknowledgeacademy
137
Passing an Argument
• Passing an object to a method uses call-by-reference
• Implicitly passed
• 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 implements polymorphism
theknowledgeacademy
140
Method Overloading
Example:
theknowledgeacademy
141
Automatic Conversions
• Java includes certain automatic conversions
Example:
theknowledgeacademy
142
Overloading Constructors
• Constructors can also be overloaded just as methods can
• The way that objects are constructed in your class is made flexible by overloading a
class’ constructor
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
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
• 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
• 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
theknowledgeacademy
147
Understanding Static
Example:
theknowledgeacademy
148
The Quicksort
• One of the most popular and best general-purpose sorting algorithms
• Elements are divided into two sides, those that are greater than or equal to partition
value and those that are less
theknowledgeacademy
149
The Quicksort
Example:
theknowledgeacademy
150
Nested and Inner Classes
• Nested class, class declared within another class
• Inner class can access all variables and methods of outer class
• This can directly refer to them similar to outer class, non-static members
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
theknowledgeacademy
153
Varargs
Overloading
• Types of program varargs parameter may differ and cause it to be treated as an array of
the specific type
Ambiguity
theknowledgeacademy
154
Varargs
(Continued)
Example:
theknowledgeacademy
155
Module 7: Inheritance
theknowledgeacademy
156
Foundation Principles
• There are three principles of object-oriented programming:
theknowledgeacademy
157
Foundation Principles
• Different kinds of objects have certain
commonalities with each other
o Subclass name
o Superclass name
theknowledgeacademy
158
Foundation Principles
(Continued)
theknowledgeacademy
159
Foundation Principles
(Continued)
theknowledgeacademy
160
Constructors
• It is possible for both subclasses and
superclasses to have their own constructors, in a
hierarchy
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
super.member
theknowledgeacademy
164
Using super to Call Superclass Constructors
(Continued)
theknowledgeacademy
165
Multilevel Hierarchy
• A is the superclass of 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
o The members that can be accessed is determined by the type of the reference
variable and not the type of object
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
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
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
• 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
• To declare an abstract class just add abstract to the beginning of the class declaration:
theknowledgeacademy
179
Abstract Methods
• An abstract method has no implementation
• To declare an abstract method, just add abstract in front of the method declaration:
theknowledgeacademy
180
Abstract Methods
(Continued)
theknowledgeacademy
181
Using final
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
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
• 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
• 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
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
• 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
• 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
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
• Gives you the ability to use those members directly, without explicit package
qualification
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
theknowledgeacademy
200
Implementing Interfaces
• Implementing an interface, use implements keyword
• Implementing more than one interface can be done with separating commas or extends
clause
theknowledgeacademy
201
Implementing Interfaces
Example
theknowledgeacademy
202
Using Interface References
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
• 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
• JDK8 introduced new default method to define a default implementation for interface
method
theknowledgeacademy
206
Default Interface Models
• Useful for specifying methods in an interface,
that can be optional depending on how that
interface is being used
theknowledgeacademy
207
Default Method Fundamentals
• Interface methods are defined similar to how methods are defined by a class
theknowledgeacademy
208
Default Method Fundamentals
Example
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
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
InterfaceName.super.methodName() Alpha.super.reset();
theknowledgeacademy
212
Multiple Inheritance
Example
theknowledgeacademy
213
Exercise
theknowledgeacademy
214
Module 9: Exception Handling
theknowledgeacademy
215
Exception Handling
theknowledgeacademy
216
The Exception Hierarchy
Throwable
Error Exception
Unchecked Checked
exceptions exceptions
theknowledgeacademy
217
The Exception Hierarchy
theknowledgeacademy
218
The Exception Hierarchy
Your program should
handle errors that
result from program
activity
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 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
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)
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
//…
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
theknowledgeacademy
225
Catching Subclass Exceptions
Put the subclass first in the catch sequence if you want to catch exceptions of
both superclass and subclass types
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
throw exceptOb
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
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
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
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
• 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
theknowledgeacademy
237
final Rethrow
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
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
theknowledgeacademy
241
Exercise
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
theknowledgeacademy
244
Byte and Character Streams
theknowledgeacademy
245
Byte Stream Classes
• Specified by using two class hierarchies
InputStream/OutputStream
theknowledgeacademy
246
Byte Stream Classes
Byte Stream Class Meaning
BufferedInputStream Buffered input stream
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
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
• Specified by using two class hierarchies topped by two abstract classes Reader and
Writer
• 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)
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
• Read() = the only defined input method from InputStream. It reads bytes
theknowledgeacademy
252
Writing Console Output
• Byte-based console output is the most commonly used byte stream
• 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
theknowledgeacademy
254
Reading and Writing Files
• Use FileInputStream to open a file for input
• If the filename does not exist FileNotfoundException subclass will be used from
IOException
• read() reads a single byte from the file and returns it as an integer value each time it is
called
• This releases the system resources allocated to the file so that they can be used again
theknowledgeacademy
256
Writing to a File
• Design a FileOutputStream object to open up a file for output
• 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
• 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
• The automated device stops anything from being unintentionally released, preventing
problems such as memory leak
General form: try(resource-specification) {
// use the 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
This can only happen when a try block executes and the resource is closed in a finally clause
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
theknowledgeacademy
261
Random-Access Files
• Often files are accessed in a linear structure, using sequential files
• Implements the DataInput and DataOutput interfaces (defines basic I/O 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
• 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
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
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)
theknowledgeacademy
269
Console Input
• For code that will be internationalised, inputting from the console using character-based
streams is better
• 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
• Then you can use the object produced to construct a BufferedReader using
BufferedReader(Reader inputReader)
theknowledgeacademy
272
How to Construct a BufferedReader
Example
theknowledgeacademy
273
Console Output
Preferred method of writing to the console is through: PrintWriter
It supports the print() and printIn() methods for all types including
Object
theknowledgeacademy
274
Console Output Using Character Streams
• Writing to the console with PrintWriter:
o System.out is still fine to write simple text output, for example when debugging
programs
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
Using a FileReader
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 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
theknowledgeacademy
283
Multithreading Fundamentals
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
static void sleep(long milliseconds) Suspends a thread for a specified period of milliseconds
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( ) 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
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
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
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
theknowledgeacademy
297
Synchronisation
Example
theknowledgeacademy
298
Synchronisation
(Continued)
theknowledgeacademy
299
Synchronisation
(Continued)
theknowledgeacademy
300
Synchronisation
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
theknowledgeacademy
302
Thread Communication
• To support the necessary communication, Java provides the following methods:
wait( )
notify( )
notifyAll( )
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
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 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
theknowledgeacademy
310
Exercise
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
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
theknowledgeacademy
316
The values() and valueOf() Methods
• Enumerations are class types, so acts like other classes
theknowledgeacademy
317
Constructors, Methods, Instance Variables,
and Enumerations
• Defining a constructor for an enum:
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 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
theknowledgeacademy
322
Enumerations Inherit Enum
(Continued)
• 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
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
theknowledgeacademy
325
Autoboxing
• Type Wrappers:
o Autoboxing and unautoboxing simplifies and streamlines code that must convert
primitive types into objects
• As mentioned previously, these are classes that hold a primitive type within an object
(most commonly used ones are highlighted in bold):
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:
• 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
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
theknowledgeacademy
330
Autoboxing Fundamentals
(Continued)
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;
}
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
theknowledgeacademy
334
Static Import
Example:
theknowledgeacademy
335
Static Import
• In the previous example sqrt and pow are brought
into view by the import statements
theknowledgeacademy
336
Annotations (Metadata)
• Annotation a form of metadata (data which contains information about itself)
//Annotation example.
@interface MyAnno {
String str();
int val();
}
theknowledgeacademy
337
Annotations (Metadata)
(Continued)
theknowledgeacademy
338
Annotations Pt. 2
• Annotation types can all automatically reach the Annotation interface
• 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
theknowledgeacademy
340
Exercise
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 type arguments must now be passed to TwoGenericClass because it has two type
parameters
theknowledgeacademy
347
Exercise
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:
theknowledgeacademy
349
Wildcard Arguments
theknowledgeacademy
350
Wildcard Arguments
Example:
theknowledgeacademy
351
Wildcard Arguments
(Continued)
theknowledgeacademy
352
Wildcard Arguments
(Continued)
theknowledgeacademy
353
Wildcard Arguments
(Continued)
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
theknowledgeacademy
355
Generic Constructors and Interfaces
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
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:
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:
• 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
theknowledgeacademy
364
Exercise
theknowledgeacademy
365
Module 14: Swing
theknowledgeacademy
366
Origins of Swing
theknowledgeacademy
367
Origins of Swing
• Swing was introduced as part of the JF Classes
1 Lightweight components
theknowledgeacademy
368
Origins of Swing
(Continued)
theknowledgeacademy
369
MVC Architecture
• Model the state information associated with a component
• 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
theknowledgeacademy
371
Components and Containers
Components
• Aside from the four top-level containers, Swing components usually come from the
JComponent class
theknowledgeacademy
372
Components and Containers
(Continued)
JTextField JButton
1 2 3 4 5
theknowledgeacademy
373
Components and Containers
Containers
JFrame JPanel
JApplet JScrollPane
JWindow JRootPane
JDialog
theknowledgeacademy
374
Components and Containers
(Continued)
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
• Panes that make up the root pane, glass pane, content pane, layered pane
theknowledgeacademy
376
Top-Level Container Panes
(Continued)
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
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
• 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 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 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
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
JList(E[] items)
theknowledgeacademy
385
Working with JList
• JScrollPane container automatically providing scrolling for contents. Example:
JScrollPane(Component comp)
• After wrapping JList and JScrollPane, long lists become automatically scrollable, making
it simpler to change number of entries in a list
theknowledgeacademy
387
Working with JList
Example
theknowledgeacademy
388
Working with JList
(Continued)
theknowledgeacademy
389
Working with JList
(Continued)
Output
theknowledgeacademy
390
Exercise
theknowledgeacademy
391
Handling Events
With Anonymous Inner Classes
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
jbtn.addActionListener((ae) -> {
// Handle action event here
});
theknowledgeacademy
394
Create Swing Applet
• Swing-based applets are similar to AWT-based applets
• All components added to JApplet’s content pane similar to how they are added to
JFrame’s
• Override methods needed by your applet. All interaction with components in Swing
applet has to happen on event-dispatching thread
theknowledgeacademy
395
Exercise
theknowledgeacademy
396
Module 15: JavaFX
theknowledgeacademy
397
Origins of JavaFX
• JavaFX handles the demands of a modern GUI and the GUI design advancements
theknowledgeacademy
398
Basic Concepts
• Similarities to GUI, AWT, Swing:
• Packages:
o Scene: Defines what is going on in the stage. Includes controls such as check boxes,
push buttons, graphics, text
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:
• 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
• 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
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
• 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
theknowledgeacademy
408
Label
Example
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
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
• To handle an event, register the handler that acts as the listener first
theknowledgeacademy
411
Buttons and Events
(Continued)
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
theknowledgeacademy
413
CheckBox Control
• CheckBox class, with ButtonBase as its immediate superclass
• An indeterminate checkbox is usually used to indicate that the state of the checkbox
has not been stated or is not relevant
• 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
o By default ListView lets just one item be selected at a time in the list
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:
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
theknowledgeacademy
418
TextField Control
(Continued)
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
theknowledgeacademy
420
Effects and Transforms
Effects
• 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()
• 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
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()
• 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
• Rotate constructor:
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
/The.Knowledge.Academy.Ltd
/TKA_Training
/the-knowledge-academy
/TheKnowledgeAcademy
Congratulation
s
426