Object Oriented Programming-Java: OOP Vs POP, Java, Java Technologies
Object Oriented Programming-Java: OOP Vs POP, Java, Java Technologies
Object Oriented Programming-Java: OOP Vs POP, Java, Java Technologies
Programming-Java
1
Prepared by: Said H Said
The University of Dodoma
Procedural Oriented
Programing (POP)
Program is divided into small parts called
functions
Importance is not given to data but to
functions as well as sequence of actions to
be done
Does not have any access specifies
In POP, Data can move freely from function
to function in the system
2
Prepared by: Said H Said
The University of Dodoma
POP Cont…
To add new data and function in POP is not
so easy
In POP, Most function uses Global data for
sharing that can be accessed freely from
function to function in the system
POP does not have any proper way for hiding
data so it is less secure
In POP, Overloading is not possible
Example of POPL are : C, VB, FORTRAN,
Pascal 3
Prepared by: Said H Said
The University of Dodoma
Object Oriented
programing(OOP)
Program is divided into parts called objects
Importance is given to data rather than
procedures or functions to mimic real world
realm
OOP has access specifies named Public,
Private, Protected, etc
In OOP, objects can move and communicate
with each other through member
functions/methods
4
Prepared by: Said H Said
The University of Dodoma
OOP cont…..
OOP provides an easy way to add new data
and function/methods
In OOP, data cannot move easily from
function to function, it can be kept public or
private so we can control the access of data
OOP provides Data Hiding so provides more
security
In OOP, overloading is possible in the form of
Function Overloading and Operator
Overloading 5
Prepared by: Said H Said
Example of OOP are : C++, JAVA, VB.NET,
The University of Dodoma
POP SRUCTURE……
Main Function
Function 2 Function 5
Function N
6
Prepared by: Said H Said
The University of Dodoma
OOP SRUCTURE……
Class 1 { Class 2 {
Data Data
Methods Methods
} }
Class n {
Data
Methods
}
7
Prepared by: Said H Said
The University of Dodoma
Java
General purpose programming language
Is simple
Is scalable
Is object oriented
Is similar to C and C++
8
Prepared by: Said H Said
The University of Dodoma
Java
A Programming Language and a Platform
Java Platform
Java Virtual Machine (Java VM)
Java Application Programming Interface
9
Prepared by: Said H Said
The University of Dodoma
Java
It is Platform Independent (Write Once Run
Anywhere)
10
Prepared by: Said H Said
The University of Dodoma
Advantages of Java
Easy to learn, Familiar C++ like syntax
Pure Object Oriented Language
Extensive API, which means that
programmers write lesser amount of code
Extensive Documentation
Faster Application Development because of
code re-use
Platform Independence
Automatic Garbage Collection
11
Prepared by: Said H Said
The University of Dodoma
History of Java
Project Green by Sun Microsystems to create
a pure object oriented language based on
C++, to overcome the limitations and
complexities of C++ (1990)
Aimed at embedded systems in consumer
electronic devices (interactive television,
VCR, washing machines, etc.)
Originally named ‘Oak’
12
Prepared by: Said H Said
The University of Dodoma
History of Java
Failed to win recognition in embedded
systems and embedded systems were not
making a rapid progress
During the same period world wide web
(www) was going through an exponential
growth
Oak was aimed at supporting interactive web
pages together with the development of a
new web browser, Web Runner (1994)
13
Prepared by: Said H Said
The University of Dodoma
History of Java
‘Oak’ renamed ‘Java’ and ‘Web Runner’
renamed ‘Hot Java’
Formal Announcement of Java Language
and Hot Java browser in Sun World ’95
Commercial web browsers starting with
Netscape begin supporting Java
Later Java evolved into other technologies
like Java applets (interactive web content)
14
Prepared by: Said H Said
The University of Dodoma
Use of Java
Desktop Applications such as acrobat reader,
media player, antivirus etc.
Web Applications such as irctc.co.in,
javatpoint.com etc.
Enterprise Applications such as banking
applications.
Mobile
Embedded System
Smart Card
Robotics
15
Prepared by: Said H Said
Games etc. The University of Dodoma
Different Java Technologies
JVM (Java Virtual Machine): is an abstract machine.
It is a specification that provides runtime
environment in which java bytecode can be
executed.
JVMs are available for many hardware and software
platforms. JVM, JRE and JDK are platform
dependent because configuration of each OS
differs. But, Java is platform independent.
The JVM performs following main tasks:
Loads code
Verifies code
Executes code
Prepared by: Said H Said The University of 16
Dodoma Prepared by: Said H Said
Provides runtime environment The University of Dodoma
Different Java Technologies
JRE: is an acronym for Java Runtime Environment.
It is used to provide runtime environment.
It is the implementation of JVM.
It physically exists.
It contains set of libraries + other files that JVM uses at
runtime.
Implementation of JVMs are also actively released
by other companies besides Sun Micro Systems.
17
Prepared by: Said H Said
The University of Dodoma
Different Java Technologies
JDK is an acronym for Java Development Kit.
It physically exists.
It contains JRE + development tools.
18
Prepared by: Said H Said
The University of Dodoma
Different Java Technologies
19
Prepared by: Said H Said
The University of Dodoma
Different Java Technologies
IDE’s (Integrated Development Environments): are
tools used for efficient software development
Different Components of an IDE :
Editor
Linker
Compiler
Debugger
All the different components are seamlessly
integrated in an IDE making it easy to use
20
Prepared by: Said H Said
The University of Dodoma
IDEs cont…
For different programming languages,
different IDE’s are available
Java Language :
JBuilder, Kawa, NetBeans, eclipse etc.
C Language :
Borland C, Turbo C, etc.
IDE’s have capabilities different from each
other and one has to learn the use of an IDE
to get the maximum return
21
Prepared by: Said H Said
The University of Dodoma
Compilation and Execution of
a Java Program
Create a source file (e.g. :- a file named
“HelloWorld.java”) and type in the source code.
/**
* The HelloWorld class implements an application that
* displays "Hello World!" to the standard output.
*/
public class HelloWorld {
public static void main(String[] args) {
// Display "Hello World!"
System.out.println("Hello World!");
}
}
22
Prepared by: Said H Said
The University of Dodoma
Compilation and Execution of
a Java Program
Compile the source file
Use the Java compiler :
javac HelloWorld.java
A byte code file (i.e. a file understandable by the
Java Virtual Machine) is created
Run the program contained in the byte code
file
Use the command :
java HelloWorld
23
Prepared by: Said H Said
The University of Dodoma
Object Oriented
Programming-Java
Basics
1
Application Programming Interface(API) or
Java Class Libraries(JCL)
⚫ Java programs consist of pieces called classes.
3
Five Phases of Java Program
⚫ Compile
⚫ uses the command javac to compile a program in
command window for windows, mac, and linux.
⚫ Java Compiler is used
⚫ Java compiler translates Java source code into
bytecodes
⚫ Stores them on disk in a file ending with .class
⚫ Bytecodes are executed by the JVM—a part of
the JDK
⚫ JVM abstracts OS and Hardware so that program
only interacts with JVM
⚫ The JVM is invoked by the java command when 4
7
General Structure of a Java
program
//there must be at least one class declaration
public class Sample
{
public static void main(String args[])
{
System.out.print("Hall Java");
}
}
}
}
12
Outputting to the Console count.
⚫ Each format specifier is a placeholder for a value and specifies
the type of data to output.
⚫ Format specifiers also may include optional formatting
information.
13
Inputint from the Console.
⚫ Scanner
import java.util.Scanner;
public class Addition{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int number1;
int number2;
int sum;
System.out.print("Enter first integer");
number1 = input.nextInt();
System.out.print("Enter second integer");
number2 = input.nextInt();
sum = number1 + number2;
System.out.printf("sum is %d\n", sum); }}
Expression: Portions of statements that contain calculation. 14
16
Data Types
17
Primitive Data Types
Keyword Description Size(Range)
int Integer 32 bits(–2, -147, -483, -648
to +2, 147, 483, 647)
byte Byte-Length Integer 8 bits(-128 to 127)
19
Type Conversion & Casting
⚫ A variable can be assigned a value that is different
to its data type
⚫ In cases where precision is not lost, conversion is
automatically handled
⚫ Eg. int x = 5;
long y = x;
⚫ In cases where precision is lost Type Casting has
to be done
⚫ Eg. int x = 5;
short y = (short) x;
20
Variables (Fields)
⚫ A variable is a location in the computer’s memory where a
value can be stored for use later in a program
⚫ Have a name(any valid identifier): Locate variable.
⚫ Have a type: specifies the kind of data stored at that
memory’s location.
⚫ Defining a variable.
AccessSpecifier DataType VariableName = Value;
private int x = 5;
char c = ‘x’;
boolean b; 21
final int i = 8;
Variables naming convention
⚫ Rules
⚫ Can contain small or capital letters, digits,
underscore,
⚫ Other symbols are not allowed except dollar sign.
⚫ Start with small letter.
⚫ Start with underscore symbol.
⚫ Don’t use reserved words
⚫ Recommendations
⚫ Name should have meaning
⚫ Several words in the same name, capitalize the
other name 22
23
Variables (Fields)
⚫ e.g
public class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
24
}//end of class
Operators
⚫ An Operator performs a function on one, two
or three operands
⚫ Categories of Operators in Java :-
⚫ Arithmetic Operators
⚫ Relational and Conditional Operators
⚫ Shift and Logical Operators
⚫ Assignment Operators
⚫ Special Operators
25
Binary Arithmetic Operators
⚫ Java supports various arithmetic operators for all
integer and floating point operators
Operator Use Description
+ op1 + op2 Adds op1 and op2
⚫ Associativity
⚫ x + y + z → (x + y) + z)
⚫ x < y <z → (x < y) < z
⚫ x = y = z → x = (y = z)
31
Relational and Conditional
Operators
⚫ Used to construct decision making expressions
Operator Use Returns true if
&& op1 && op2 op1 and op2 are both true, conditionally
evaluates op2
! ! op op is false
32
Shift and Logical Operators
⚫ Shift Operators perform bit manipulation on data by
shifting the bits of its first operand right or left
34
Shift and Logical Operators
⚫ Bitwise functions of number operands
~ ~ op bitwise complement
35
Shift and Logical Operators
⚫ When its operands are numbers, the & operation
performs the bitwise AND function on each parallel
pair of bits in each operand
36
Shift and Logical Operators
⚫ e.g. :- 13 & 12
1101 //13
& 1100 //12
-------
1100 //12
37
Assignment Operators
⚫ Basic assignment operator (=) is used to assign
one value to another
⚫ Shortcut Assignment Operators
Operator Use Equivalent to
+= op1 += op2 op1 = op1 + op2
-= op1 -= op2 op1 = op1 - op2
*= op1 *= op2 op1 = op1 * op2
/= op1 /= op2 op1 = op1 / op2
%= op1 %= op2 op1 = op1 % op2
&= op1 &= op2 op1 = op1 & op2 38
Special Operators
Operator Description
?: Shortcut if-else statement
41
Special Operators
⚫ The instanceof Operator :-
Tests whether first operand is an instance of
the second
op1 instanceof op2
op1 must be the name of an object and op2
must be the name of a class
42
Object Oriented
Programming-Java
Control structure,
Arrays and Strings
1
Prepared by: Mr Said H Said
The University of Dodoma
Control Structure:
Sequence
Program executes sequentially line by line without
skipping starting from the top.
e.g
public class A{
public static void main(String[] args){
int x;
x = 5;
int y;
y=12;
int z;
z = x + y;
System.out.println(x);
System.out.println(y);
System.out.println(z);
2
} Prepared by: Mr Said H Said
The University of Dodoma
}
Control Structure:
Single Selection(if statement)
Program may skip some of the lines based on the condition
Single because there is only one option to execute based on the condition.
syntax
If (conditional expression)
{
Statement;
}
e.g
import java.util. Scanner;
public class A{
public static void main(String[] args){
Scanner x = new Scanner(System.in);
System.out.println(“Enter marks”);
int n = x.nextInt();
if(n>= 40){
System.out.print(“PASS”);
}
} 3
Prepared by: Mr Said H Said
} The University of Dodoma
Control Structure:
double Selection (if-else
statement)
To selectively execute statements depending
on some criteria
if (conditional expression) {
statement(s)
} else {
statement(s)
}
4
Prepared by: Mr Said H Said
The University of Dodoma
Control Structure:
double Selection (if-else statem)
e.g.
import java.util. Scanner;
public class A{
public static void main(String[] args){
Scanner x = new Scanner(System.in);
System.out.println(“Enter marks”);
int n = x.nextInt();
if(n>= 40){
System.out.println(“PASS”);
}
else
System.out.print(“FAIL”);
}
}
5
Prepared by: Mr Said H Said
The University of Dodoma
Control Structure:
double Selection(if-else stat)
Exercise
Write a program to calculate the grade of a
student given the average
Marks < 0 or Marks > 100 give Error Message
0 <= Marks < 40 – Grade = C
40 <= Marks < 70 – Grade = B
70 <= Marks <= 100 – Grade = A
6
Prepared by: Mr Said H Said
The University of Dodoma
Control Structure:
double selection(if-else stat)
Class Grade {
public static void main (String[] args){
int mark = 75;
if ( (mark<0) or (mark>100) ) {
System.out.println(‘Error’);
} else if (mark<40) {
System.out.println(‘C’);
} else if (mark<70) {
System.out.println(‘B’);
} else {
System.out.println(‘A’);
}
}
}
7
Prepared by: Mr Said H Said
The University of Dodoma
Control Structure:
multiple selection(switch stat)
Evaluates a variable and executes
statements according to it’s value
switch (variable) {
case value1: statement(s);
break;
case valueN: statement(s);
break;
case default: statement(s);
break;
8
} Prepared by: Mr Said H Said
The University of Dodoma
Control Structure:
multiple selection(switch stat)
Eg.
switch (day) {
case 1: System.out.println(“Sunday”); break;
case 2: System.out.println(“Monday”); break;
case 3: System.out.println(“Tuesday”); break;
case 4: System.out.println(“Wednesday”); break;
case 5: System.out.println(“Thursday”); break;
case 6: System.out.println(“Friday”); break;
case 7: System.out.println(“Saturday”); break;
} Prepared by: Mr Said H Said
9
Eg
for (int i=0; i<5; i++) {
System.out.println(“Iteration “ + i);
} 12
Prepared by: Mr Said H Said
The University of Dodoma
Control Structure:
repetition (For Statement)
Write a method to calculate the factorial of a given
integer
14
Prepared by: Mr Said H Said
The University of Dodoma
Control Structure:
repetition (While Statement)
Eg.
int x=0;
while (x<5) {
System.out.println(“Iteration ” + x);
x++;
}
15
Prepared by: Mr Said H Said
The University of Dodoma
Control Structure:
repetition (While Statement)
Eg.
publicclassMyClass {
while(x<= 10)
{
System.out.println(x);
x++;
}
}
16
} Prepared by: Mr Said H Said
The University of Dodoma
Control Structure:
repetition (do-While Statement)
do {
statement(s)
} while (conditional expression);
17
Prepared by: Mr Said H Said
The University of Dodoma
Control Structure:
repetition (do-While Statement)
int x=0;
do {
System.out.println(“Iteration ” + x);
x++;
} while (x<5);
18
Prepared by: Mr Said H Said
The University of Dodoma
Control Structure:
Iterations
It will be covered in Methods
19
Prepared by: Mr Said H Said
The University of Dodoma
Exercise
20
Prepared by: Mr Said H Said
The University of Dodoma
Branching Statements
break
Used to terminate a switch statement or a loop
Eg.
public class A{
public static void main(String[] args){
int x=0;
while (true) {
System.out.println(“Iteration” + x);
x++;
if (x==5) {
break;
} //end if
} //end while
} //end main
} //end class 21
Prepared by: Mr Said H Said
The University of Dodoma
Branching Statements
continue
Used to skip a part of an iteration in a loop
Eg.
public class A{
public static void main(String[] args){
int x=0;
while (x<5) {
x++;
if (x==2) {
continue;
} //end if
System.out.println(“Iteration ” + x);
} //end while
} //end main 22
Prepared by: Mr Said H Said
} //end class The University of Dodoma
Branching Statements
return
Used to come out of a method
Eg.
public void method1() {
System.out.println(“Method 1”);
return;
}
public int method2() {
System.out.println(“Method 2”);
return 1;
23
} Prepared by: Mr Said H Said
The University of Dodoma
Nesting
Task
Find out about nested Selection Statements and
nested loops
24
Prepared by: Mr Said H Said
The University of Dodoma
Arrays-Single Dimensional
A structure that holds multiple values of the
same type
Single dimensional array has one row and n-
number of columns
The length of an array is established when
the array is created (at runtime)
After creation it is a fixed-length structure
25
Prepared by: Mr Said H Said
The University of Dodoma
Arrays-Single Dimensional
Array is declared and created
Array is a no-primitive or reference data type
The following declaration and array-creation expression
create an array object containing 12 int elements and store
the array’s reference in variable c, that reference point to 0
index of that array.
int c[] = new int[ 12 ];
Other ways of declaring and creating an array
double[] array1, array2;// declaration
int[] arr = {13,10,11,21,16};
int[] arr = new int[5];
int[] arr = new int[]{13,10,11,21,16};
int arr[] = {13,10,11,21,16};
After creation receives a default value depending on 26
Arrays of Objects
String[] anArray = { "One", "Two", "Three" };
MyClass[] mcArray = new MyClass[5]; // No Items
30
Prepared by: Mr Said H Said
The University of Dodoma
Arrays-Two Dimensional
Arrays of Arrays, an array with multiple rows
and columns
or 2D Arrays can be defined
String[][] 2DArray = new String[3][4];
31
Prepared by: Mr Said H Said
The University of Dodoma
Arrays-Two Dimensional
int b[][]= { { 1, 2 }, { 3, 4 } };
nested arrays form rows
Number of elements in nested arrays form columns
So 1 and 2 initialize b[ 0 ][ 0 ] and b[ 0 ][ 1 ],
respectively, and 3 and 4 initialize b[ 1 ][ 0 ] and b[ 1 ][ 1
], respectively.
int b[][] = new int[ 3 ][ 4 ];
3 specifies number of rows
4 specifies number of columns
32
Prepared by: Mr Said H Said
The University of Dodoma
Arrays-Two Dimensional
e.g
Import java.util.Scanner;
public class Array{
public static void main( String args[] ){
int arr[][] = new int[3][4];
Scanner input = new Scanner(System.in);
for(int row=0; row <arr.length; row++){
for(int col=0; col <arr[row].length; col++){
System.out.print("Enter an interger");
arr[row][col] = input.nextInt();
}
}
for(int row=0; row <arr.length; row++){
for(int col=0; col <arr[row].length; col++){
System.out.print(arr[row][col] );
} 33
Prepared by: Mr Said H Said
System.out.print("\n");}}} The University of Dodoma
Exercise
Using single dimensional array and two
dimensional do the following tasks:
Create and array of 100 integer elements
Perform summation of all elements
Perform average
Perform sorting of elements in ascending order
Perform sorting of elements in descending order
34
Prepared by: Mr Said H Said
The University of Dodoma
Strings
Next to numbers, strings are the most important
data type that most programs use
A string is a sequence of characters, e.g., “Hello”
In Java strings are enclosed in quotation marks,
which are not themselves part of the string
You can declare variables that hold strings
String name = “John”
Use assignment to place a different string into the
variable
name = “Godfrey”
35
Prepared by: Mr Said H Said
The University of Dodoma
String Data Type
The number of characters in a string is called the length
of the string
E.g., the length of “Hello, World” is 13.
Compute the length of the string with the length method
int n = name.length();
Unlike numbers, strings are objects.
See that String is a class because it starts with an
uppercase letter
The basic data types int and double start with a
lowercase letter
Thus, can call methods on strings, e.g., name.length()
36
Prepared by: Mr Said H Said
The University of Dodoma
Substrings
Can extract substrings, and can glue smaller strings together to
forma larger ones
To extract substring, use the substring method:
s.substring(start, pastEnd)
Returns a string that is made up from the characters in the string s,
starting at character start, and containing all characters up to, but
not including, the character pastEnd.
E.g.,
String greeting = “Hello, World!”;
String sub = greetings.substring(0,4); //sub is “Hell”
H e l l o , W o r l d !
0 1 2 3 4 5 6 7 8 9 10 11 12
37
Prepared by: Mr Said H Said
The University of Dodoma
Substrings
The position number of the last character (12 for the
string “Hello, World!”) is 1 less than the length of the
string
E.g., to extract the substring “World”, count characters
starting at 0, not 1.
Find that W, the 8th character, has position number 7.
String w = greeting.substring(7,12);
He l l o , W o r l d !
0 1 2 3 4 5 6 7 8 9 10 11 12 38
Prepared by: Mr Said H Said
The University of Dodoma
Substrings
Must specify the position of the first character that you
do want and then the first character that you don’t want
One advantage to this setup is, can easily compute the
length of the substring: pastEnd - start
If you omit the second parameter of the substring
method, then all characters from the starting position to
the end of the string are copied
E.g.,
String tail = greeting.substring(7); //tail is “World!”
Equivalent to
String tail = greeting.substring(7, greeting.length());
39
Prepared by: Mr Said H Said
The University of Dodoma
Concatenation
Given two strings, such as “Snuffer” and “Dog-Dog”, you
can concatenate them to one long string:
String fname = “Snuffer”;
String lname = “Dog-Dog”;
String name = fname + lname;
The + operator concatenates two strings
The resulting string is “SnufferDog-Dog”
We would-like the first and last name separated by a
space.
String name = fname + “ “ + lname;
Now we’ve concatenated three strings: “Snuffer”, “ “, and
“Dog-Dog”.
The result is “Snuffer Dog-Dog” 40
Prepared by: Mr Said H Said
The University of Dodoma
Concatenation
If one of the expressions, either to the left or the right of a +
operator, is a string, then the other one is automatically
forced to become a string as well, and both strings are
concatenated
E.g.,
String a = “Agent”;
int n = 7;
String bond = a + n;
Since a is a string, n is converted from the integer 7 to the
string “7”.
The two strings “Agent” and “7” are concatenated to form
the string “Agent7”
41
Prepared by: Mr Said H Said
The University of Dodoma
Concatenation
Can reduce the number of System.out.print
instructions
E.g.
System.out.print(“The total is”);
System.out.println(total);
To the single call
System.out.println(“The total is “ + total);
The concatenation “The total is “ + total computes a
single string that consists of the string “The total is “,
followed by the string equivalent of the number total.
42
Prepared by: Mr Said H Said
The University of Dodoma
toUpperCase, toLowerCase
The toUpperCase and toLowerCase methods make
strings with only upper- or lowercase characters.
String greeting = “Hello”;
System.out.println(greetings.toUpperCase() + “ “ +
greetings.toLowerCase());
Display HELLO hello
The toUpperCase and toLowerCase do not change the
original String object greeting.
They return new String objects that contain the uppercased
and lowercased versions of the original string
No String methods modify the string object on which they
operate – called mutable objects. 43
Prepared by: Mr Said H Said
The University of Dodoma
Converting between Numbers
and Strings
In general to convert a numbe to a string, yo can
concatenate with the empty string:
int age = 19;
String ageString = “” + age;
Some programmers prefer to use the toString
methods of the Integer and Double classes,
because it is more explicit:
String ageString = Integer.toString(age);
44
Prepared by: Mr Said H Said
The University of Dodoma
Converting between Numbers
and Strings
To convert a string containing just digits to its integer value
use the static parseInt method of the Integer class.
String password = “hjh19”
String ageString = password.substring(3);
int age = ageString; // ERROR
int age = Integer.parseInt(ageString); // age is the
number 19
To convert a string containing floating-point digits to its
floating-point value, use the static parseDouble method of
the Double class.
45
Prepared by: Mr Said H Said
The University of Dodoma
Converting between Numbers
and Strings
String priceString = “$3.95”;
double price =
Double.parseDouble(priceString.substring(1));
// sip “$” and convert to a number
The parseInteger and parseDouble methods are
useful for processing input
46
Prepared by: Mr Said H Said
The University of Dodoma
publicclassMyClass{
publicstaticvoid main(String args[]){
String myString = "Hallow Java";
//Concatenation
String s = “s”;
String t = “top”;
String p = “s + t”;
int n = 1;
String x = “1”;
Int m = n+ n; ->2
String g = x+x; ->”11”
String f = n+s; ->”11”
String s = “”;//empty string,leght 0
String s = “ ”;//space character, legth 1
String j = “halloo”;
String r = j.substring(2,4);->”ll”
String r = j.substring(0,2);->”He”
String r = j.substring(2);->”llo!”
System.out.println(myString);
intmyStringLength = myString.length();
System.out.println(myStringLength);
String myStringLowCase = myString.toLowerCase();
System.out.println(myStringLowCase);
String myStringUpCase = myString.toUpperCase();
System.out.println(myStringUpCase);
String myStringReplacedA = myString.replace('a','e');
System.out.println(myStringReplacedA); 47
intmyStringIndices = myString.indexOf('J'); Prepared by: Mr Said H Said
The University of Dodoma
Object Oriented
Programming
Methods, Objects,
Classes, Encapsulation
and, Constructors
1
Prepared by: Mr.Said H Said
The University of Dodoma
OOP Concepts
Object
Class
Encapsulation
Inheritance
Polymorphism
Abstraction
2
Prepared by: Mr.Said H Said
The University of Dodoma
Methods
A piece of code which execute some logic
Performs some tasks and returns results or control
Defines behavior of objects
Used for communication between objects
Allow you to modularize a program by separating
its tasks into self contained units
Statements in the method bodies are written only
once, reused from several parts of program, are
hidden from other methods.
Allow divide-and-conquer
3
4
Prepared by: Mr.Said H Said
The University of Dodoma
Methods
e.g. :-
public int getNumber();
private void setData(String name, int age)
protected DefinedClass getDefinedClass()
Return Types
void
Primitive types
Object Type
Array Type
5
Prepared by: Mr.Said H Said
The University of Dodoma
Methods-Parameters and
Arguments
Parameter list is a comma separated list of variable
declarations within the parentheses of a method
Each parameter identifies the parameter’s type and a
name by which the parameter can be referenced
A parameter may be referenced anywhere within the
method
Arguments are data values passed to parameters
during a method call
Method arguments may be constants, variables or
expressions.
6
Prepared by: Mr.Said H Said
The University of Dodoma
Methods-Parameters and
Arguments
//Declaration of a method with parameters
7
Prepared by: Mr.Said H Said
The University of Dodoma
Methods
Methods are used by invoking them with
respect to an object reference
Syntax :
objectName.methodName(argument List)
e.g. :-
String treeName = tree.getName( value );
8
Prepared by: Mr.Said H Said
The University of Dodoma
Methods-call
There are three ways to call a method:
Using a method name by itself to call another
method of the same class.
Using a variable that contains a reference to an
object, followed by a dot (.) and the method name
to call a method of the referenced object.
Using the class name and a dot (.) to call a static
method of a class.
A method can either return results(value) or a
control to the collar
9
Prepared by: Mr.Said H Said
The University of Dodoma
Methods-call
Two ways to pass arguments in method calls in many
programming languages are pass-by-value and pass-
by-reference (also called call by-value and call-by-
reference).
When an argument is passed by value, a copy of the
argument’s value is passed to the called method.
The called method works exclusively with the copy.
When an argument is passed by reference, the called
method can access the argument’s value in the caller
directly and modify that data, if necessary.
In java all arguments are passed by value-copy of
primitive value or copy of reference to object. 10
Prepared by: Mr.Said H Said
The University of Dodoma
Methods-array as parameters
and arguments
Array
double hourlyTemperatures[] = new double[ 24 ];
Specify an array parameter.
void modifyArray( int b[] )
In method call, provide the name of array without
angle brackets as an argument.
modifyArray( hourlyTemperatures );
11
Prepared by: Mr.Said H Said
The University of Dodoma
Methods-array as parameters
and arguments
public class PassArray{
public static void main( String args[] ){
int array[] = { 1, 2, 3, 4, 5 };
System.out.println("Effects of passing reference to entire array:\n" + "The values of the original array are:" );
for ( int value : array ) // output original array elements
System.out.printf( " %d", value );
modifyArray( array ); // pass array reference
System.out.println( "\n\nThe values of the modified array are:" );
for ( int value : array ) // output modified array elements
System.out.printf( " %d", value );
System.out.printf("\n\nEffects of passing array element value:\n" + "array[3] before modifyElement: %d\n", array[ 3
] );
modifyElement( array[ 3 ] ); // attempt to modify array[ 3 ]
System.out.printf("array[3] after modifyElement: %d\n", array[ 3 ] );
} // end main
public static void modifyArray( int array2[] ){ // multiply each element of an array by 2
for ( int counter = 0; counter < array2.length; counter++ )
array2[ counter ] *= 2;}
public static void modifyElement( int element ){ // multiply argument by 2
element *= 2; 12
Prepared by: Mr.Said H Said
System.out.printf("Value of element in modifyElement: %d\n", element );}} The University of Dodoma
Methods-static
Static methods apply to the class as a whole rather than an
instance of the class
Static methods can be invoked using the same notation as non-
static methods
However it is more appropriate to invoke static methods using
the class name rather than a variable name
To declare a method as static, place the keyword static before
the return type in the method’s declaration.
Note that a static method can call only other static methods of
the same class directly (i.e., using the method name by itself)
and can manipulate only static fields in the same class directly.
Java does not allow a static method to access non-static
members of the same class directly.
To access the class’s non-static members, a static method 13
Prepared by: Mr.Said H Said
must use a reference to an object of the class. The University of Dodoma
Methods
e.g no parameters, no return type
Public class MyClass
{
public static void main(String args[])
{
myMethod();
}
21
Prepared by: Mr.Said H Said
The University of Dodoma
What is an Object?
22
Prepared by: Mr.Said H Said
The University of Dodoma
What is an Object?
23
Prepared by: Mr.Said H Said
The University of Dodoma
What is a Class?
A class is a group of objects that has common
properties.
It is a template or blueprint from which objects are
created.
It is a blueprint that defines the variables and
methods common to all objects of a certain kind
A data type/structure in which you can define some
member variable and member methods
Eg. ‘Your Mobile Phone’ is one Object belonging to
the Class, Phone
An Object holds values for the Variables defined in 24
Prepared by: Mr.Said H Said
the class (e.g. Make = Nokia) The University of Dodoma
What is a Class?
A class in java can contain:
data member
method
constructor
block
25
Prepared by: Mr.Said H Said
The University of Dodoma
Class Vs Object
27
Prepared by: Mr.Said H Said
The University of Dodoma
Syntax for declaring/defining a
class and Creating an object
//class definition/declaration
public class <className>
{
data member;
method;
}
//object creation
<className> ob = new <className> (); 28
Prepared by: Mr.Said H Said
The University of Dodoma
Class and Object
Program creates a class Student1 that have two data members
regNum and name. Creates the object of the Student1 class by
new keyword and prints the objects value.
public class Student1{
int regNum; //data member (also instance variable)
String name; //data member(also instance variable)
public static void main(String[] args){
Student1 s1 = new Student1(); //creating an object of Student
System.out.println(s1. regNum);
System.out.println(s1.name);}}
The new keyword is used to allocate memory at runtime
A variable that is created inside the class but outside the
method, is known as instance variable. Instance variable
doesn't get memory at compile time. It gets memory at runtime
when object(instance) is created. That is why, it is known29 as
instance variable. Prepared by: Mr.Said H Said
The University of Dodoma
Encapsulation
30
Prepared by: Mr.Said H Said
The University of Dodoma
Encapsulation
Class
31
Prepared by: Mr.Said H Said
The University of Dodoma
Encapsulation
32
Prepared by: Mr.Said H Said
The University of Dodoma
Constructors
A Constructor is a special method
used to construct an object (instance)
from a class.
Used for the initialization of the object.
40
Prepared by: Mr.Said H Said
The University of Dodoma
Objects and Classes
//class
public class Grade{
public void displayMessage(){
System.out.println( "Welcome to the Grade!" );
}
}
42
Prepared by: Mr.Said H Said
The University of Dodoma
Objects and Classes
public class GradeBook{ import java.util.Scanner;
private String courseName; public class GradeBookTest{
public static void main( String args[] ){
public void setCourseName(
Scanner t=new Scanner( System.in );
String name ){
GradeBook myGradeBook = new
courseName = name; GradeBook();
} System.out.printf( "Initial course name
is: %s\n\n",
public String getCourseName(){ myGradeBook.getCourseName());
return courseName; System.out.println( "Please enter the
} course name:" );
String theName = input.nextLine();
public void displayMessage(){
myGradeBook.setCourseName(
System.out.printf( "Welcome to theName );
the grade book for\n%s!\n", System.out.println();
getCourseName());}} myGradeBook.displayMessage();
43
}} Prepared by: Mr.Said H Said
The University of Dodoma
Objects and Classes
//class
public class GradeBook{
public void displayMessage( ){
System.out.printf( "Welcome to the grade book for\n%s!\n",
courseName ); } }
Public Y Y Y Y
Protected Y Y Y N
No modifier Y Y N N
Private Y N N N
47
Prepared by: Mr.Said H Said
The University of Ddoma
this reference
Allow object to access reference to itself
When a non-static method is called for a
particular object, the method’s body
implicitly uses keyword this to refer to the
object’s instance variables and other
methods.
48
Prepared by: Mr.Said H Said
The University of Dodoma
this reference
public class A{
public static void main(String[] args){
A t = new A(15, 30, 19);
System.out.println(t.B());
}}
class B{
private int x;
private int y;
private int z;
public B(int x, int y, int z){
this.x = x;
this.y = y;
this.z = z;
49
}} Prepared by: Mr.Said H Said
The University of Dodoma
Scope
The scope of a declaration is the portion of the program
that can refer to the declared entity by its name.
The basic scope rules are as follows:
The scope of a parameter declaration is the body of the
method in which the declaration appears.
The scope of a local-variable declaration is from the point at
which the declaration appears to the end of that block.
The scope of a local-variable declaration that appears in the
initialization section of a for statement’s header is the body of
the for statement and the other expressions in the header.
The scope of a method or field of a class is the entire body of
the class. This enables non-static methods of a class to use
the class’s fields and other methods.
If a local variable or parameter in a method has the same50
Prepared by: Mr.Said H Said
name as a field, the field is “hidden” until the block
The university of Dodoma
Scope
// Scope class demonstrates field and local variable scopes.
public class Scope{ // Application to test class Scope.
// field that is accessible to all methods of this class
private int x = 1; public class ScopeTest
// method begin creates and initializes local variable x
// and calls methods useLocalVariable and useField
{
public void begin(){
int x = 5; // method's local variable x shadows field x
// application starting point
System.out.printf( "local x in method begin is %d\n", x );
useLocalVariable(); // useLocalVariable has local x
public static void main( String args[] )
useField(); // useField uses class Scope's field x {
useLocalVariable(); // useLocalVariable reinitializes local x
useField(); // class Scope's field x retains its value Scope testScope = new Scope();
System.out.printf( "\nlocal x in method begin is %d\n", x );
} // end method begin testScope.begin();
// create and initialize local variable x during each call
public void useLocalVariable() } // end main
{
int x = 25; // initialized each time useLocalVariable is called } // end class ScopeTest
System.out.printf("\nlocal x on entering method useLocalVariable is %d\n", x );
++x; // modifies this method's local variable x
System.out.printf("local x before exiting method useLocalVariable is %d\n", x
);
} // end method useLocalVariable
// modify class Scope's field x during each call
public void useField() {
System.out.printf("\nfield x on entering method useField is %d\n", x );
x *= 10; // modifies class Scope's field x
System.out.printf("field x before exiting method useField is %d\n", x );
} // end method useField 51
Prepared by: Mr.Said H Said
} // end class Scope The University of Dodoma
Variable-length argument lists
With variable-length argument lists, you can create
methods that receive an unspecified number of
arguments
An argument type followed by an ellipsis (...) in a
method’s parameter list indicates that the method
receives a variable number of arguments of that
particular type.
This use of the ellipsis can occur only once in a
parameter list, and the ellipsis, together with its type,
must be placed at the end of the parameter list.
52
Prepared by: Mr.Said H Said
The University of Dodoma
Variable-length argument lists
public class VarargsTest{
public static double average(double... numbers){
double total = 0.0; // initialize total
for ( double d : numbers )
total += d;
return total /numbers.length;}
public static void main( String args[] ){
double d1 = 10.0;
double d2 = 20.0;
double d3 = 30.0;
double d4 = 40.0;
System.out.printf( "d1 = %.1f\nd2 = %.1f\nd3 = %.1f\nd4 = %.1f\n\n", d1, d2, d3, d4
);
System.out.printf( "Average of d1 and d2 is %.1f\n", average( d1, d2));
System.out.printf( "Average of d1, d2 and d3 is %.1f\n", average( d1, d2, d3 ));
System.out.printf( "Average of d1, d2, d3 and d4 is %.1f\n", average( d1, d2, d3, 53
d4
));}} Prepared by: Mr.Said H Said
The University of Dodoma
Command-line arguments
On many systems it is possible to pass arguments from the
command line (these are known as command-line arguments)
to an application by including a parameter of type String[] (i.e.,
an array of Strings) in the parameter list of main
By convention, this parameter is named args.
When an application is executed using the java command,
Java passes the command-line arguments that appear after the
class name in the java command to the application’s main
method as Strings in the array args.
The number of arguments passed in from the command line is
obtained by accessing the array’s length attribute.
54
Prepared by: Mr.Said H Said
The University of Dodoma
Command-line arguments
For example, the command
"java MyClass a b" passes two command-line
arguments, a and b, to application MyClass.
Note that command-line arguments are separated by
white space, not commas.
When this command executes, MyClass’s main
method receives the two-element array args (i.e.,
args.length is 2) in which args[ 0 ] contains the String
"a" and args[ 1 ] contains the String "b".
Common uses of command-line arguments include
passing options and file names to applications.
55
Prepared by: Mr.Said H Said
The University of Dodoma
Command-line arguments
public class InitArray{
public static void main(String args[]){
// check number of command-line arguments
if(args.length != 3)
System.out.println("Error: Please re-enter the entire command, including\n" + "an array size, initial value and
increment." );
else{
// get array size from first command-line argument
int arrayLength = Integer.parseInt( args[ 0 ] );
int array[] = new int[ arrayLength ]; // create array
// get initial value and increment from command-line arguments
int initialValue = Integer.parseInt( args[ 1 ] );
int increment = Integer.parseInt( args[ 2 ] );
// calculate value for each array element
for ( int counter = 0; counter < array.length; counter++ )
array[ counter ] = initialValue + increment * counter;
System.out.printf( "%s%8s\n", "Index", "Value" );
// display array index and value
for ( int counter = 0; counter < array.length; counter++ )
System.out.printf( "%5d%8d\n", counter, array[ counter ] );
} // end else
56
} // end main Prepared by: Mr.Said H Said
} // end class InitArray The University of Dodoma
Compiling many classes
In different files
Both must be compiled
e.g javac A.java B.java
Only class with main method should be run(executed)
57
Prepared by: Mr.Said H Said
The University of Dodoma
Composition (has-a)
A class can have references to objects of other
classes as members.
Such a capability is called composition and is
sometimes referred to as a has-a relationship.
58
Prepared by: Mr.Said H Said
The University of Dodoma
Composition (has-a)
class Employee{
int id;
String name;
Address address;//Address is a class
...
}
59
Prepared by: Mr.Said H Said
The University of Dodoma
Composition (has-a)
class Operation{
int square(int n){
return n*n;
}
}
class Circle{
Operation op;//aggregation
double pi=3.14;
double area(int radius){
op=new Operation();
int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
return pi*rsquare;
}
public static void main(String args[]){
Circle c=new Circle();
double result=c.area(5);
System.out.println(result);
} 60
} Prepared by: Mr.Said H Said
The University of Dodoma
final Keyword
placed before class, method or variable
a final class cannot be subclassed
a final method cannot be overridden by
subclasses
a final variable can only be initialized once
If a final variable is not initialized, a compilation
error occurs.
61
Prepared by: Mr.Said H Said
The University of Dodoma
Final keywors
e.g //client class
package lesson1; Public class MyClass{
Public class Hello { public static void main(String args[]){
public final double PIE; Hello hel = newHello();
Hello(){ //hel.pie = 10;
pie = 3.14; }
} }
}
62
Prepared by: Mr.Said H Said
The University of Dodoma
Static Keyword Example
publicclass Hello {
Public static int age;
Public static String doSomething(String messege){
Return messege;
}
public String doSomethingElse(String messege){
Return messege;
}}
//client class
Public class MyClass{
publicstaticvoid main(String args[]){
//all instances hel1,hel2,hel 3 share same static member
Hello hel1 = newHello();
Hello hel2 = newHello();
Hello hel3 = newHello();
Hello.doSomething("Said");
hel1.doSomethingElse("Java");
Hello.age = 10;
System.out.println(Hello.age); 63
Prepared by: Mr.Said H Said
}} The University of Dodoma
Creating your own Packages
placed before class, method or variable
a final class cannot be subclassed
a final method cannot be overridden by
subclasses
a final variable can only be initialized once
If a final variable is not initialized, a compilation
error occurs.
64
Prepared by: Mr.Said H Said
The University of Dodoma
Creating your own Packages
Packaging
package packageName;
Importing
import packageName ClassName;
1
Prepared by: Mr.Said H Said
The University of Dodoma
OOP Concepts
Object
Class
Encapsulation
Inheritance
Polymorphism
Abstraction
2
Prepared by: Mr.Said H Said
The University of Dodoma
Inheritance
Inheritance in java is a mechanism in which one
class inherits the properties of another class.
Class from which properties have been inherited is
called Superclass and class that inherits is called
Subclass.
Inheritance represents the IS-A relationship, also
known as parent-child relationship.
When you inherit from an existing class, you can
reuse methods and fields of parent class, and you
can add new methods and fields also.
3
Prepared by: Mr.Said H Said
Help in code reusability The University of Dodoma
Inheritance
4
Prepared by: Mr.Said H Said
The University of Dodoma
Inheritance
Syntax
class Employee{
float salary = 40000;
}
11
Prepared by: Mr.Said H Said
The University of Dodoma
Inheritance-visibility
It is possible to treat superclass objects and subclass objects
similarly—their commonalities are expressed in the members of
the superclass.
However, superclass objects cannot be treated as objects of their
subclasses.
A class’s public members are accessible wherever the program
has a reference to an object of that class or one of its subclasses.
A class’s private members are accessible only from within the
class itself.
A superclass’s private members are not inherited by its
subclasses.
Methods of a subclass cannot directly access private members of
their superclass.
A subclass can change the state of private superclass instance
variables only through non-private methods provided in the
12
superclass and inherited by the subclass. Prepared by: Mr.Said H Said
The University of Dodoma
Inheritance-visibility
A superclass’s protected members can be accessed by
members of that superclass, by members of its subclasses
and by members of other classes in the same package
All public and protected superclass members retain their
original access modifier when they become members of the
subclass
public members of the superclass become public
members of the subclass,
and protected members of the superclass become
protected members of the subclass.
Subclass methods can refer to public and protected
members inherited from the superclass simply by using the
member names.
When a subclass method overrides a superclass method, the
superclass method can be accessed from the subclass by
preceding the superclass method name with keyword super 13
Prepared by: Mr.Said H Said
The University of Dodoma
Inheritance-visibility
The first task of any subclass constructor is to call
its direct superclass’s constructor, either explicitly
or implicitly (if no constructor call is specified), to
ensure that the instance variables inherited from
the superclass are initialized properly.
14
Prepared by: Mr.Said H Said
The University of Dodoma
Polymorphism
A concept by which we can perform a single action
by different ways
A Greek word: poly= many, morphs = forms, so
polymorphism means many forms
In java OOP, it is the ability of an object to have
different or many forms
You can define reference of a base class that
point to the object of the subclass
When reference of base class point to the object of
subclass, it is called upcasting
Methods must have the same signature 15
Prepared by: Mr.Said H Said
The University of Dodoma
Polymorphism
public class Bank{
public class MyMain{
int getInterestRate(){
public static void main(String[] args){
return 0;
}}
Bank b1;
public class NMB extends Bank{
b1= new NMB();// upcasting
int getInterestRate(){
Bank b2 = new CRDB(); //upcasting
return 5;
Bank b3 = new NBC(); //upcasting
}}
public class CRDB extends Bank{
System.out.println(b1.getInterestRate());
int getInterestRate(){
System.out.println(b2.getInterestRate());
return 6;
System.out.println(b3.getInterestRate());
}}
public class NBC extends Bank{
}}
int getInterestRate(){
In upcasting a reference variable of 16
return 7;
superclass refer to thePrepared
object of
by: Mr.Said H Said
The University of Dodoma
}}
Method Overriding
The same methods in different classes of the
inheritance hierarchy have different
implementation, hence do different things.
Subclass provides specific implementation of
the method that has been provided by one of
its parent class, it is known as method
overriding.
Methods must have the same signature
Ensure uniform treatment of methods, but
diversity of what is excecuted.
17
Prepared by: Mr.Said H Said
The University of Dodoma
Method overriding
public class Bank{
public class MyMain{
int getInterestRate(){
public static void main(String[] args){
return 0;
}}
Bank b1;
b1= new Bank();
public class NMB extends Bank{
//this method overrides the superclass method
//Bank b1;
int getInterestRate(){
//b1= new NMB();// upcasting
return 5;
}
System.out.println(b1.getInterestRate());
}
}
}
}
You can either upcast or not
Data members are not
overriden 18
Prepared by: Mr.Said H Said
The University of Dodoma
Super keyword
Is a reference variable used to refer to the
immediate superclass object.
Whenever you create the instance of subclass,
an instance of superclass is created implicitly
and can be referred by super variable.
hence, used to invoke superclass member
variables and methods and constructors
19
Prepared by: Mr.Said H Said
The University of Dodoma
Super keyword- to invoke
superclass instance variable
public class Vehicle{
int speed = 50;
}
class Bike extends Vehicle{
int speed = 100;
void display(){
System.out.println(speed);//will print speed of bike
System.out.println(super.speed);//will print speed of vehicle
}
public static void main(String args[]){
Bike b = new Bike();
b.display();
20
23
Prepared by: Mr.Said H Said
The University of Dodoma
instanceof operator
24
Prepared by: Mr.Said H Said
The University of Dodoma
instanceof operator
public class Animal
{
}
public class Dog extends Animal
{
public static void main(String args[])
{
Dog d = new Dog();
System.out.println(d instanceof Animal); //true
}
25
Final variable
In case of final variable, it stops variable value change,
however for blank final variables(uninitialized final
variable) can only be initialized through constructors
Parameters can also be made final, meaning you cant
change its value.
final method
In case of final method, it stops method overriding,
however it can be inherited.
final class
In case of final class, it stops class inheritance. 26
Prepared by: Mr.Said H Said
The University of Dodoma
Static and Dynamic Binding
Binding means connecting a method call to a
method body
Static binding(early binding)
name resolution is done at compile time
e.g in method overloading, method names are
resolved in compile time.
A call to overloaded method is resolved at compile-
time
Dynamic binding(late binding)
name resolution is done at run time
e.g in method overriding, method names are
resolved at run time.
27
A call to overridden method is resolved at run-time
Prepared by: Mr.Said H Said
The University of Dodoma
Abstraction
Abstraction is the process of hiding implementation
details and showing only functionality to the user
Eg
Driving a care
Sending a message
Interface(100%)
28
Prepared by: Mr.Said H Said
The University of Dodoma
Abstraction
Abstract class,
A class declared with abstract keyword
It cannot be instantiated, you cant create an object of abstract
class
It has at least one abstract method, however you can make a
class abstract even without having any abstract class.
You just want its property to serve its subclasses
Can be extended to a concrete class or abstract class
The opposite of abstract class is concrete class(normal class)
Abstract methods,
A method declared with abstract keyword
It does not have implementation, no body.
All abstract methods must be implemented in subclasses
Constrictors, static methods and final methods cannot be abstract 29
Prepared by: Mr.Said H Said
The University of Dodoma
Abstraction
public abstract class Bank{
public class MyMain{
abstract int getInterestRate();
public static void main(String[] args){
/* int getInterestRate(){
return 0;
Bank b1 = new NMB();
}*/
Bank b2 = new CRDB();
public class NMB extends Bank{
Bank b3 = new NBC();
int getInterestRate(){
return 5;
System.out.println(b1.getInterestRate());
}}
System.out.println(b2.getInterestRate());
public class CRDB extends Bank{
System.out.println(b3.getInterestRate());
int getInterestRate(){
return 6;
}
}}
}
public class NBC extends Bank{
int getInterestRate(){ 30
Prepared by: Mr.Said H Said
The University of Dodoma
return 7;
Interfaces
Interface in java act like a blueprint of class
A mechanism of achieving full abstraction in java
An interface cannot be instantiated
All methods in interface are abstract and public by default
All attributes in interface are public, static and final by default
Interface cannot be extended,
It can only be implemented
Provides full abstraction layers
Exposes services to users
Hide implementation details
Achieves multiple inheritance in java
Can change implementation without changing interface 31
Prepared by: Mr.Said H Said
The University of Dodoma
Interfaces
Class class extends
Interface class impliments, implementing all
methods
Interface abstract-class impliments,
implementing some of method
Interface interface extends, by adding abstract
methods
32
Prepared by: Mr.Said H Said
The University of Dodoma
Interfaces
A class can implement multiple interfaces
Name conflicts
Same methods name
34
Prepared by: Mr.Said H Said
The University of Dodoma
Interfaces
35
Prepared by: Mr.Said H Said
The University of Dodoma
Interfaces
36
Prepared by: Mr.Said H Said
The University of Dodoma
Interfaces
public interface Bank{
int getInterestRate();
}
37
Prepared by: Mr.Said H Said
The University of Dodoma
Interfaces-multiple inheritance
Multiple inheritance in java
implements extends
Class
interface
38
Prepared by: Mr.Said H Said
The University of Dodoma
Interfaces-multiple inheritance
public interface Vehicle{
void move();
}
public interface Car{
void drive();
}
public class Honda impliments Vehicle, Car{
public void move(){System.out.println(“Moving”);}
public void drive(){System.out.println(“Driving”);}
1
Prepared by: Mr.Said H Said
The University of Dodoma
Exceptions
Exception is an event which occurs during
execution of a program, that disrupts the
normal flow of program's instructions.
Exception Handling is a mechanism of
making a program more robust by
enabling them to handle exceptions.
This is also known as making your
program fault tolerant.
2
Prepared by: Mr.Said H Said
The University of Dodoma
Exceptions
Statement 1
Statement 2
Statement 5
Statement 6
Statement 8
Statement 9
Stack
Exceptions-Hierarchy
6
Prepared by: Mr.Said H Said
The University of Dodoma
Exceptions-Types
Checked Exceptions
Unchecked Exception
Error
7
Checked Exception
The classes that extent Throwable except
RuntimeException and Error are known as
checked exceptions. e.g IOException etc
8
Unchecked Exceptions
The classes that extent RuntimeException
are known as unchecked exceptions e.g
arithmeticException etc
9
Error
Error is irrecoverable
e.g
OutOfMemoryError,
VirtualMachineError,
AssertionError etc
10
Exception Handling keywords
Try
Catch
Finally
Throw
Throws
11
Catching an Exception
Consists of Three Blocks, try, catch & finally
try {
//statementCausingTheException;
} catch (TheException e) {
//exceptionHandlingCode;
} finally {
//cleanUpCode;
}
The finally block is reached even if no Exception
occurs 12
Catching an exceptions
//does not excecute
public class MyClass{
public static void main(String args[]){
int a = 11/0;
System.out.println("..................");
}
}
13
Prepared by: Mr.Said H Said
The University of Dodoma
Catching an exceptions
//excecutes
public class MyClass{
public static void main(String args[]){
int b[] = new int[2];
try{
int a = 11/0;
System.out.println(b[3]);
}catch(ArithmeticException e){
System.out.println(e);
}/*catch(Exception e){
System.out.println(e);
}*/
14
System.out.println(“Rest of code"); }} Prepared by: Mr.Said H Said
The University of Dodoma
Catching an Exception
Eg.-
public void someMethod() {
String someString = “xyz”;
int someInt;
try {
someInt = Integer.parseInt(someString);
} catch (NumberFormatException nfe) {
System.err.println(" NumberFormatException: " +
nfe.getMessage());
}
} 15
Finally block
It consists of the finally keyword, followed by code enclosed in
curly braces
It is optional
It is placed after the last catch block,
Finally block will execute whether or not an exception is thrown
in the corresponding try block or any of its corresponding catch
blocks.
Finally block will execute if a try block exits by using a return,
break or continue statement, or simply by reaching the try
block’s closing right brace.
Finally block will not execute if the application exits early from a
try block by calling method System.exit.
Because a finally block almost always executes, it typically
contains resource-release code, releasing resource is allocated
16
in a try block, eg closing files or connectios Prepared by: Mr.Said H Said
The University of Dodoma
Finally block
try
{
statements
resource-acquisition statements
} // end try
catch ( AKindOfException exception1 )
{
exception-handling statements
} // end catch
.
.
catch ( AnotherKindOfException exception2 )
{
exception-handling statements
} // end catch
finally
{
statements
17
resource-release statements Prepared by: Mr.Said H Said
The University of Dodoma
} // end finally
Finally block
public class MyClass{
public static void main(String args[]){
try{
int a = 11/0;
System.out.println(a);
}catch(ArithmeticException e){
System.out.println(e);
}
finally{
System.out.println(“finally block is always excecuted”);
}
System.out.println(“Rest of code");
}
}
18
Prepared by: Mr.Said H Said
The University of Dodoma
Throwing an Exception
When an exception is caught, an Exception
has to be thrown inside that method (throw
clause)
21
Prepared by: Mr.Said H Said
The University of Dodoma
Throwing an Exception
Eg.-
public void myMethod() throws myException {
for (int i=1; i<10; i++) {
if (i == 5) {
throw new myException();
}
}
}
22
Defining an Exception
New types of Exceptions can be defined by
sub-classing the Exception class or any of its
subclasses.
24
Advantages of Exceptions
Separating Error Handling Code from Regular Code
Eg.-
try {
statementThatThrowsException1;
statementThatThrowsException2;
} catch (Exception1) {
doSomething; The order is important.
If you give a parent
} catch (Exception2) { class first & a child class
later, the second catch
doSomething; will not be reached
}
25
Advantages of Exceptions
Propagation Errors up the Call Stack
Eg.-
method1 {
call method2; Should be caught here
}
27
Files and Streams
Data Hierarchy
Bit
-0 and 1.
2-Bytes
-Character(Unicode for java).
Field
-convey meaning.
Record
-related fields.
File
-related records. 28
Prepared by: Mr.Said H Said
The University of Dodoma
Files and Streams
Data hierarchy
29
Prepared by: Mr.Said H Said
The University of Dodoma
Files and Streams
30
Prepared by: Mr.Said H Said
The University of Dodoma
Files and Streams
Stream refers to ordered data that is read from or
written to a file.
File is a group of related records.
Java views each file as a sequential stream of
bytes.
File streams can be used to input and output data
as either characters or bytes.
31
Prepared by: Mr. Said H Said
The University of Dodoma
Files and Streams
Streams that input and output bytes to files are
known as byte-based streams, storing data in its
binary format.
Streams that input and output characters to files
are known as character based streams, storing
data as a sequence of characters.
Files that are created using byte-based streams
are referred to as binary files
files created using character-based streams are
referred to as text files.
32
Prepared by: Mr. Said H Said
The University of Dodoma
Files and Streams
Writing to the file
import java.io.*;
class FileWrite{
public static void main(String[] args){
try{
FileOutputStream f = new FileOutputStream("abc.txt");
String s = "Java Programming";
byte b[] = s.getBytes(); //convert string into byte array
f.write(b);
f.close();
System.out.println("successs");
}catch(Exception e){System.out.println(e);}
33
}} Prepared by: Mr. Said H Said
The University of Dodoma
Files and Streams
Reading from the file
import java.io.*;
class FileRead{
public static void main(String[] args){
try{
FileInputStream f = new FileInputStream("abc.txt");
int i = 0;
while((i = f.read())!=-1){
System.out.println((char)i);
}
f.close();
}catch(Exception e){System.out.println(e);} 34
Prepared by: Mr. Said H Said
}} The University of Dodoma
Files and Streams
Reading from a file and Writing to another file
import java.io.*;
public class FileWriteRead{
public static void main(String[] args)throws Exception
{
FileInputStream f1 = new FileInputStream("A.java");
FileOutputStream f2 = new FileOutputStream("B.java");
int i = 0;
while((i=f1.read())!=-1)
{
f2.write((byte)i);
}
f1.close(); 35
Prepared by: Mr. Said H Said
}} The University of Dodoma
Files and Streams
Writing to the file
import java.io.File;
import java.io.PrintWriter;
public class Demo{
public static void main(String [] args){
try{
file file = new File(“FileName.txt”);
if(!file.exists()){
file.createNewFile();
}
PrintWriter pw = new PrintWriter(“file”);
pw.println(“thie is file content”);
pw.println(10000);
pw.close();
}catch(IOException e){e.printStackTrace();}
36
}} Prepared by: Mr. Said H Said
The University of Dodoma
Files and Streams
Reading from file
import java.io.FileReader;
import java.io.BufferReader;
import java.io.IOException;
public class Demo{
public static void main(String [] args){
BufferReader br = null;
try{
br = new BufferReader(new
FileReader(“C:\\Users\\said\\Desktop\\FF\\filename.txt”));
String line;
While((line = br.readLine()) != null){
System.out.println(line);
}
}catch(IOException e){e.printStackTrace();}
finally{br.close();} 37
Prepared by: Mr. Said H Said
}} The University of Dodoma
Object Oriented
Programming
GUI, Events
1
Prepared by: Mr.Said H Said
The University of Dodoma
GUI
A graphical user interface (GUI) presents a
user-friendly mechanism for interacting with
an application.
GUIs are built from GUI components.
A GUI component is an object with which the
user interacts via the mouse, the keyboard or
another form of input, such as voice
recognition.
AWT, Swing, JavaFX
2
Prepared by: Mr.Said H Said
The University of Dodoma
AWT
Choice
List
Container
Window Panel
Applet
4
Frame Dialog Prepared by: Mr.Said H Said
The University of Dodoma
AWT
Container
Is a component in AWT that can contain another
components like buttons, textfields, labels, etc
The classes that extends container class are known as
container such as Frame, Dialog and Panel.
Window
Is the container that have no borders and menu bars. You
must use frame, dialog, or another window for creating a
window.
Panel
Is the container that doesn’t contain title bar and menu bars.
It can have other components like button, textfield etc
Frame
Is a container that contains title bar an d can have menu 5
bars. It can have other components like button, textfield
Prepared etc.
by: Mr.Said H Said
The University of Dodoma
AWT
6
Prepared by: Mr.Said H Said
The University of Dodoma
Example of AWT by inheritance
import java.awt.*;
public class First extends Frame{
First(){
Button b = new Button(“click me”);
b.setBounds(30, 100, 80, 30); //position button
add(b); //add button into frame
setSize(300, 300); //frame size
setLayout(null); // no layout manage
setVisible(true); //make frame visible, by default not
}
public static void main(String args[]){
First f = new First(); Prepared by: Mr.Said H Said
7
9
Prepared by: Mr.Said H Said
The University of Dodoma
Swing GUI components from
package javax.swing
Component Description
JLabel Displays uneditable text or icons.
JTextField Enables user to enter data from the keyboard. Can also be used to
display editable or uneditable text.
JTextArea
JButton Triggers an event when clicked with the mouse.
JRadioButton
JMenu
JColorChooser
JCheckBox Specifies an option that can be selected or not selected.
JComboBox Provides a drop-down list of items from which the user can make a
selection by clicking an item or possibly by typing into the box.
JList Provides a list of items from which the user can make a selection by
clicking on any item in the list. Multiple elements can be selected.
JPanel Provides an area in which components can be placed and organized. 10 Can
Prepared by: Mr.Said H Said
also be used as a drawing area for graphics. The University of Dodoma
Hierarchy of java swing
classes
Object
JLabel
Component
JList
JTable
Container JComponent
JComboBox
Applet JMenu
JButton 11
Prepared by: Mr.Said H Said
The University of Dodoma
Swing
To create a Swing, you need a frame
There are two ways to create a frame in
AWT
By extending Frame class (inheritance)
By creating the object of Frame class
(association)
Code of swing can be written inside the
main(), constructor, or other methods
12
Prepared by: Mr.Said H Said
The University of Dodoma
Example Swing-code inside
main()
import javax.swing.*;
public class MySwing{
public static void main(String args[]){
JFrame f = new JFrame();
JButton b = new JButton(“click”);
b.setBounds(130,100,100,40); //x, y, w, h
f.add(b); //add button in frame
f.setSize(400,500);
f.setLayout(null);
f.setVisible(true); 13
Prepared by: Mr.Said H Said
17
Prepared by: Mr.Said H Said
The University of Dodoma
Example JButton class-image
import javax.swing.*;
public class ImageButton{
ImageButton(){
JFrame f = new JFrame();
JButton b =new JButton(new ImageIcon(“b.jpg”));
b.setBounds(130,100,100,40);
f.add(b);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[]){
new ImageButton(); }} 18
Prepared by: Mr.Said H Said
The University of Dodoma
JRadioButton class
Is used to create a radio button
Is used to choose one option from multiple options
It should be added in ButtonGroup to select one radio
button only
RadioButtonGroup class is used to group multiple
buttons so that at a time only one button can be
selected.
JRadionButton class extends the JToggleButton class
that extends AbstractButton class.
Commonly used constructors
JRadioButton(): creates an unselected radio button with no text
JRadioButton(String s): creates an unselected radio button with
specified text
JRadioButton(String s, Boolean selected): creates aby:radio
Prepared Mr.Said H Said
19
27
Prepared by: Mr.Said H Said
The University of Dodoma
Example of JTable class
import javax.swing.*;
public class MyTable {
JFrame f;
MyTable(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
// f.setLayout(null);
f.setVisible(true);
} 28
public static void main(String[] args) { Prepared by: Mr.Said H Said
The University of Dodoma
JComboBox class
29
Prepared by: Mr.Said H Said
The University of Dodoma
Example of JComboBox class
import javax.swing.*;
public class Combo {
JFrame f;
Combo(){
f=new JFrame("Combo ex");
String country[]={"India","Aus","U.S.A","England","Newzeland"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args) { 30
new Combo(); } } Prepared by: Mr.Said H Said
The University of Dodoma
JColorChooser class:
31
Prepared by: Mr.Said H Said
The University of Dodoma
Example of JColorChooser class
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class JColorChooserExample extends JFrame implements ActionListener{
JButton b;
Container c;
JColorChooserExample(){
c=getContentPane();
c.setLayout(new FlowLayout());
b=new JButton("color");
b.addActionListener(this); c.add(b);
}
public void actionPerformed(ActionEvent e) {
Color initialcolor=Color.RED;
Color color=JColorChooser.showDialog(this,"Select a color",initialcolor);
c.setBackground(color);
}
public static void main(String[] args) {
JColorChooserExample ch=new JColorChooserExample();
ch.setSize(400,400);
ch.setVisible(true); 32
Prepared by: Mr.Said H Said
ch.setDefaultCloseOperation(EXIT_ON_CLOSE); } } The University of Dodoma
Graphics in swing:
java.awt.Graphics class provides many methods
for graphics programming.
Commonly used methods of Graphics class:
public abstract void drawString(String str, int x, int
y): is used to draw the specified string.
public void drawRect(int x, int y, int width, int
height): draws a rectangle with the specified width
and height.
public abstract void fillRect(int x, int y, int width, int
height): is used to fill rectangle with the default color
and specified width and height.
public abstract void drawOval(int x, int y, int width,
int height): is used to draw oval with the specified 33
Prepared by: Mr.Said H Said
The University of Dodoma
Graphics in swing:
Commonly used methods of Graphics class:
public abstract void fillOval(int x, int y, int width, int
height): is used to fill oval with the default color and
specified width and height.
public abstract void drawLine(int x1, int y1, int x2, int
y2): is used to draw line between the points(x1, y1)
and (x2, y2).
public abstract boolean drawImage(Image img, int x,
int y, ImageObserver observer): is used draw the
specified image.
public abstract void drawArc(int x, int y, int width, int
height, int startAngle, int arcAngle): is used draw a
circular or elliptical arc. 34
Prepared by: Mr.Said H Said
The University of Dodoma
Graphics in swing:
Commonly used methods of Graphics class:
public abstract void fillArc(int x, int y, int width, int
height, int startAngle, int arcAngle): is used to fill a
circular or elliptical arc.
public abstract void setColor(Color c): is used to set
the graphics current color to the specified color.
public abstract void setFont(Font font): is used to
set the graphics current font to the specified font.
35
Prepared by: Mr.Said H Said
The University of Dodoma
Example of Displaying Graphic
import java.awt.*;
import javax.swing.JFrame;
public class DisplayGraphics extends Canvas{
public void paint(Graphics g) {
g.drawString("Hello",40,40);
setBackground(Color.WHITE);
g.fillRect(130, 30,100, 80);
g.drawOval(30,130,50, 60);
setForeground(Color.RED);
g.fillOval(130,130,50, 60);
g.drawArc(30, 200, 40,50,90,60);
g.fillArc(30, 130, 40,50,180,40);
}
public static void main(String[] args) {
DisplayGraphics m=new DisplayGraphics();
JFrame f=new JFrame();
f.add(m);
f.setSize(400,400);
36
//f.setLayout(null); Prepared by: Mr.Said H Said
The University of Dodoma
JavaFX
37
Prepared by: Mr.Said H Said
The University of Dodoma
Event and Listener(Java Event
Handling)
Event refers to change of state of an object
e.g click on button, dragging mouse etc.
java.awt.event package provides many event
classes and listener interfaces for event
handling.
38
Prepared by: Mr.Said H Said
The University of Dodoma
Event and Listener(Java Event
Handling)
An Event is used to get User Input from a
GUI
An Event Listener is needed to capture these
Events
Event Listeners are Interfaces that have to be
implemented by the Event Source
Each Event Source can have Multiple
Listeners
39
Prepared by: Mr.Said H Said
The University of Dodoma
Event Handling
Event Classes and Listener
Interfaces
Event Class Listener Interface
ActionEvent ActionListener
MouseEvent MouseListener and
MouseMotionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowsEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
41
42
Prepared by: Mr.Said H Said
The University of Dodoma
Implementing an Event Handler
The Class has to implement the relevant Event
Handler
public class MyClass implements ActionListener {
Some EventListeners
ActionListener
MouseListener
MouseMotionListener
KeyListener
Action Listener
The ActionListener is used for Events which
are generated by a user performing an Action
on a Component
Clicking a Button
Entering text into a TextField
Choosing a MenuItem
51
Prepared by: Mr.Said H Said
The University of Dodoma
Example JRadioButton wt Event
import javax.swing.*;
import java.awt.event.*;
public class Radio extends Jframe implements ActionListener{
JRadioButton rb1, rb2;
JButton b;
Radio(){
rb1 = new JRadioButton(“Male”);
rb1.setBounds(100,50,100,30);
rb2 = new JRadioButton(“Female”);
rb2.setBounds(100,100,100,30);
ButtonGroup bg = new ButtonGroup();
bg.add(rb1); bg.add(rb2);
b = new JButton(“click”);
b.setBounds(100,150,80,30);
b.addActioListener(this);
add(rb1); add(rb2); add(b);
setSize(300,300); 52
setLayout(null); Prepared by: Mr.Said H Said
The University of Dodoma
Example event handling within
class
import java.awt.*;
import java.awt.event.*;
public class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
tf = new TextField();
tf.setBounds(60, 50, 170, 20);
Button b = new Button(“click me”);
b.setBounds(100, 120, 80, 30);
b.addActionListener(this);
add(b);
add(tf);
setSize(300, 300);
setLayout(null);
setVisible(true);
} //end constructor
public void actionPerformed(ActionEvent e){
tf.setText(“welcome”);
}//end actionPerformed
public static void main(){
new AEvent(); 53
}//end main Prepared by: Mr.Said H Said
The University of Dodoma
Example Event Handling by
other class
import java.awt.*; import java.awt.event.*;
import java.awt.event.*; public class Outer implemets ActionListener{
public class AEvent extends Frame{ AEvent obj;
TextField tf;
AEvent(){ Outer(AEvent obj){
tf = new TextField(); this.obj = obj;
tf.setBounds(60, 50, 170, 20); }
Button b = new Button(“click me”); public void actionPerformed(ActionEvent e){
b.setBounds(100, 120, 80, 30); obj.tf.setText(“welcome”);
Outer o = new Outer(this); }
b.addActionListener(o); } //end class
add(b);
add(tf);
setSize(300, 300);
setLayout(null);
setVisible(true);
} //end constructor
public static void main(){
new AEvent();
54
}//end main Prepared by: Mr.Said H Said
} //end class The University of Dodoma
Example Event Handling by
Anonymous class
import java.awt.*;
import java.awt.event.*;
public class AEvent extends Frame {
TextField tf;
AEvent(){
tf = new TextField();
tf.setBounds(60, 50, 170, 20);
Button b = new Button(“click me”);
b.setBounds(100, 120, 80, 30);
b.addActionListener(new ActionListener(){
public void nactionPerformed(){
tf.setText(“hello”);
}
});
add(b);
add(tf);
setSize(300, 300);
setLayout(null);
setVisible(true);
} //end constructor
public static void main(String[] args){ 55
Prepared by: Mr.Said H Said
new AEvent(); The University of Dodoma
Object Oriented
Programming
Threads
1
Prepared by: Mr.Said H Said
The University of Dodoma
Multitasking
2
Prepared by: Mr.Said H Said
The University of Dodoma
Process-based multitasking
Process is a executing instance of a program.
Each process have its own address space in
memory i.e each process allocates separate
memory area.
Process is heavy weight.
Cost of communication between the
processes is high.
Switching from one process to another
requires sometime for saving and loading
registers, memory maps, updating lists etc.
3
Prepared by: Mr.Said H Said
The University of Dodoma
Thread-based multitasking
Thread-based multitasking(multithreading)
Threads share the same address space
Thread is light weight
Cost of communication between the thread is
low
Multithreading is more preferred than
multiprocessing because:
threads share a common memory space.
they don’t allocate separate memory space, so
saves memory,
context switching btn the threads takes less time
4
than process. Prepared by: Mr.Said H Said
The University of Dodoma
Threads
A thread is a single sequential execution within
a program.
The smallest unit of processing or execution.
Also called an execution context or a
lightweight process
Thread is a subset of a process
Threads share the address space of a process.
They are independent , each with its own
callstack
Thread scheduler decides which thread to run
at a time using preemptive or time slicing 5
6
Prepared by: Mr.Said H Said
The University of Dodoma
Multithreading
Multithreading refers the process of executing
multiple threads concurrently, multiple threads
run simultaneously within a single program.
The power of programming with threads is about
the use of multiple threads within a single program,
running at the same time and performing different
tasks.
7
Prepared by: Mr.Said H Said
The University of Dodoma
Multithreading
The HotJava Web browser is an example of a multi
threaded application
e.g. :- Scroll a page while downloading an image
A thread runs within the context of a full blown
program and takes advantage of the resources
allocated for the program and its environment
(lightweight process)
A thread must carve out some of its own resources
within a running program such as its own execution
stack and a program counter (execution context)
8
Prepared by: Mr.Said H Said
The University of Dodoma
Life cycle of a Thread(Thread
states)
New
if you create instance of Thread class,
Runnable
after invocation of start() method
Running
if the thread scheduler has selected it
Non-Runnable(Blocked)
when the thread is still alive, but is currently not
eligible to run
Terminated
is in termination or dead state when its run()
Prepared by: Mr.Said H Said
9
Non-Runnable
(Blocked)
Running
Sleep, block on I/O,
wait for lock,
suspend, wait
run() method exits
Terminated
10
Prepared by: Mr.Said H Said
The University of Dodoma
Creating Threads
Threads can be implemented in Java by
providing a run() method to a Runnable
object that defines the thread’s running
behavior
There are two ways to create our own thread
object.
Subclassing the Thread class and
instantiating the new object.
Implementing the Runnable interface.
In both cases the run() method should be
implemented and start() method be called. 11
Prepared by: Mr.Said H Said
The University of Dodoma
Subclassing Thread class
The java.lang.Thread class implements the
behavior of a thread with an empty run() method.
A thread can be implemented by defining a class
which is a subclass of the Thread class and
overriding its empty run() method to do something
Thread class provides constructors and methods
to create and perform operations on thread.
Thread class implements Runnable interface.
12
Prepared by: Mr.Said H Said
The University of Dodoma
Thread class methods
run(): is used to perform action for a thread
start(): starts the execution of the thread, JVM calls the run()
method on the thread
sleep(): causes the currently executing thread to sleep for
specified miliseconds
join(): waits for a thread to die
getPriority(): return the priority of the thread
setPriority(): change the priority of the thread
getName(): return the name of the thread
currentThread(): changes the name of the thread
getId(): return the id of the thread
getState(): return the state of the thread
suspend(): used to suspend the thread
resume(): used to resume the suspended thread 13
Prepared by: Mr.Said H Said
The University of Dodoma
Example1 for Subclassing
Thread class
public class MultiThread extends Thread{
public void run(){
System.out.println(“thread is running….”);
}
public static void main(String args[]){
MultiThread t1 = new MultiThread();
t1.start();
}
}
Thread constructor is implicitly invoked using super() 14
to allocate a new thread object. Prepared by: Mr.Said H Said
The University of Dodoma
Example2 for Subclassing
Thread class
public class SimpleThread extends Thread {
public SimpleThread(String str) {
super(str);
}
public void run() {
for (int i = 0; i < 4; i++) {
System.out.println(i + " " + getName());
try {
sleep((long)(Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("DONE! " + getName());
} 15
Prepared by: Mr.Said H Said
} The University of Dodoma
Example2 for Subclassing
Thread class cont…
public class TwoThreadsDemo {
public static void main (String[] args) {
SimpleThread t1= newSimpleThread(“Tanzania”);
t1. start();
SimpleThread t2= new SimpleThread(“Kenya”);
t2. start();
}
}
17
Prepared by: Mr.Said H Said
The University of Dodoma
Implementing the Runnable
interface.
Runnable interface should be implemented
by any class whose instances are intended to
be executed by a thread.
Runnable interface has only one method
named run()
A thread can be created by implementing the
Runnable interface and implementing the
run() method defined in it
If a class must sub class some other class
(such as Applet), Runnable interface should
be implemented to get the behavior of a 18
Prepared by: Mr.Said H Said
thread The University of Dodoma
Example for implementing
Runnable interface
public class Multi implements Runnable{
public void run(){
System.out.println(“thread is running….”);
}
public static void main(String args[]){
Multi m1 = new Multi();
Thread t1 = new Thread(m1);
t1.start(); }}
If you are not extending the Thread class, your class
object would not be treated as a thread object.
So you need to explicitly create Thread class object and
pass the object of the class that implement Runnable so 19
Prepared by: Mr.Said H Said
that the class run() method may execute. The University of Dodoma
sleep() method
20
Prepared by: Mr.Said H Said
The University of Dodoma
Example-sleep() method
public class MyThread extends Thread{
public void run(){
for(int i=1; i<5; i++){
try{
Thread.sleep(500);
}catch(InterruptedException e){
System.out.println(e);
}//end catch
System.out.println(i);
}//end for
}//end run
public static void main(String args[]) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start();
t2.start(); 21
Prepared by: Mr.Said H Said
}} The University of Dodoma
Run() vs Start()
22
Prepared by: Mr.Said H Said
The University of Dodoma
Run() vs Start() cont…
public class MyThread extends Thread{
public void run(){
for(int i=1; i<5;i++){
try{
Thread.sleep(500);
}catch(InterruptException e){
System.out.println(e);
}//end catch
System.out.println(i);
}//end for
}//end run
public static void main(String args[]){
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.run(); //does not start a separate call stack
t2.run();
} }//end class
Wills not start separate call stack, it will use the main callstack
No context-switching between t1 ant t2 becausePreparedthere t1 and 23
by: Mr.Said H Said
t2
will be treated as normal objects. The University of Dodoma
Run() vs Start() cont…..
No separate callstack, use main callstack
run()
run()
main()
Stack 24
Prepared by: Mr.Said H Said
(main thread) The University of Dodoma
Run() vs Start() cont…
public class MyThread extends Thread{
public void run(){
for(int i=1; i<5;i++){
try{
Thread.sleep(500);
}catch(InterruptException e){
System.out.println(e);
}//end catch
System.out.println(i);
}//end for
}//end run
public static void main(String args[]){
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start(); //does not start a separate call stack
t2.start();
}}//end class
Will start separate callstack.
There will be context-switching between t1 antPrepared
t2 because 25
by: Mr.Said H Said
there t1 and t2 will be treated as thread objects .
The University of Dodoma
Run() vs Start() cont…..
Each thread use separate callstsack
Syntax
public void join() throws InterruptedException{
}
27
Prepared by: Mr.Said H Said
The University of Dodoma
join() method
public class MyThread extends Thread{
public void run(){
for(int i=1; i < 5; i++){
try{
Thread.sleep(500);
}catch (Exception e){System.out.println(e);} //end catch
System.out.println(i);
} //end for
} //end run
public static void main(String args[]){
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
t1.start();
try{
t1.join(); //you can also specify join time in milliseconds e.g join(1500)
}catch(Exception e){System.out.println(e);}
t2.start(); 28
t3.start();} //end main } //end class Prepared by: Mr.Said H Said
The University of Dodoma
getName(),setName(),getId()
method
Help in naming a thread and getting the thread name and id
Syntax
public string getName();
public void setName();
public long getId();
public class MyThread extends Thread(){
public void run(){
System.out.println(“running…”);
}
public static void main(){
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
System.out.println(“name of t1:” + t1.getName);
System.out.println(“name of t2:” + t2.getName);
System.out.println(“id of t1:” + t1.getId);
t1.start();
t2.start();
t1.setName(“CS 213”); 29
Prepared by: Mr.Said H Said
System.out.println(“After changing name of t1:” + t1.getName()); }}Dodoma
The University of
currentThread() method
Return a reference to currently executing thread object
Syntax
public static Thread currentThread();
e.g
public class MyThread extends Thread(){
public void run(){
System.out.println(Thread.currentThread().getName());
} // end run
public static void main(){
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start();
t2.start();
} //end main
30
} //end class Prepared by: Mr.Said H Said
The University of Dodoma
Thread Priority
Each thread have a priority.
Priorities are separated by a number ntn 1 to 10.
In most cases, thread scheduler schedules the
threads according to their priority(known as
preemptive scheduling).
But it is not guaranteed because it depends on JVM
specification, which scheduling scheme it choses.
Three constants from Thread class are used
public static int MIN_PRIORITY
public static int NORM_PRIORITY
public static int MAX_PRIORITY
Default priority of a thread is 5(NORM_PRIORITY)
The value of MIN_PRIORITY is 1 31
Prepared by: Mr.Said H Said
The value of MAX_PRIORITY is 10 The University of Dodoma
Thread Priority
public class MyThread extends Thread{
public void run(){
System.out.println(“running thread name is:” +
Thread.currentThread().getName());
System.out.println(“running thread name is:” +
Thread.currentThread().getPriority());
}
public static void main(String args[]){
MyThread t1 = new MyThread();
MyThread t1 = new MyThread();
t1.setPriority(Thread.MIN_PRIORITY);
t1.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2,.start();
} 32
Prepared by: Mr.Said H Said
} The University of Dodoma
Performing single task by
multiple threads
Use only one run() method.
37
Prepared by: Mr.Said H Said
The University of Dodoma
Threads Synchronization
38
Prepared by: Mr.Said H Said
The University of Dodoma
Threads Synchronization
Mutual Exclusive
By synchronized method
By synchronized block
By static synchronization
39
Prepared by: Mr.Said H Said
The University of Dodoma
A problem without
Synchronization
public class Table{ class MyMain(){
void prinTable(in n){ //method not synchronized public static void main(String args[]){
for(int i = 1; i < = 5; i++){ Table obj = new Table();//only one object
System.out.println(n*i); MyThread1 t1 = new MyThread1(obj);
try{ MyThread2 t2 = new MyThread2(obj);
Thread.sleep(400); t1.start();
}catch(Exception e){System.out.println(e);} t2.start();
} // end for }
} //end prinTable }
} //end class
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){this.t=t;}
public void run(){t.printable(5);}
} //end class
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){this.t=t;}
public void run(){t.printable(100);} 40
Prepared by: Mr.Said H Said
} //end class The University of Dodoma
Synchronized Method
Used to lock an object for any shared
resource
When a thread invokes a synchronized
method, automatically acquires the lock for
the object and releases it when it
completes its task
Syntax
synchronized dataType methodName(){
}
41
Prepared by: Mr.Said H Said
The University of Dodoma
Synchronized Method
public class Table{
synchronized void prinTable(in n){ //synchronized
for(int i = 1; i < = 5; i++){ class MyMain(){
System.out.println(n*i); public static void main(String args[]){
try{ Table obj = new Table();//only one object
Thread.sleep(400); MyThread1 t1 = new MyThread1(obj);
}catch(Exception e){System.out.println(e);} MyThread2 t2 = new MyThread2(obj);
} // end for t1.start();
} //end prinTable t2.start();
} //end class }
class MyThread1 extends Thread{ }
Table t;
MyThread1(Table t){this.t=t;}
public void run(){t.printable(5);}
} //end class
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){this.t=t;}
public void run(){t.printable(100);}
} //end class
42
Prepared by: Mr.Said H Said
The University of Dodoma
Synchronized Block
45
Prepared by: Mr.Said H Said
The University of Dodoma
Static Synchronization
class Table{
synchronized static void prinTable(in n){
//synchronized public class MyMain(){
for(int i = 1; i < = 5; i++){ public static void main(String args[]){
System.out.println(n*i); MyThread1 t1 = new MyThread1();
try{ MyThread2 t2 = new MyThread2();
Thread.sleep(400); MyThread3 t3 = new MyThread3();
}catch(Exception e){System.out.println(e);} MyThread4 t4 = new MyThread4();
} // end for t1.start();
} //end prinTable t2.start();
} //end class t3.start();
class MyThread1 extends Thread{ t4.start();
public void run(){ }
Table.prinTable(1); }
} //end run
} //end class
class MyThread2 extends Thread{
public void run(){
Table.prinTable(10);
} //end run
} //end class 46
Prepared by: Mr.Said H Said
class MyThread3 extends Thread{ The University of Dodoma
Coordination(Inter-Thread
communication)
Is about allowing synchronized threads to
communicate with each other
A mechanism in which a thread is paused
running in its critical section and another
thread is allowed to enter (or lock) in the
same critical section to be executed.
The following methods of Object class are
used to implement
wait();
notify();
notifyAll();
47
Prepared by: Mr.Said H Said
The University of Dodoma
Coordination(Inter-Thread
communication)
class customer{ class MyMain{
int amount = 10000; public static void main(String args[]){
final Customer c = new Customer();
synchronized void withdraw(int amount){
System.out.println(“going to withdraw…”); new Thread(){
if(this.amount < amount){ public void run(){
System.out.println(“going to withdraw…”); c.withdraw(15000);
} //end run
try{ }.start();//end Thread
wait();
}catch(Exception e){} new Thread(){
public void run(){
}//end if c.deposite(10000);
this.amount-=amount; } //end run
System.out.println(“withdraw completed…”); }.start();//end Thread
}//end withdraw } //end main
synchronized void deposite(int amount){ } //end class
System.out.println(“going to deposite…”);
this.amount+=amount;
System.out.println(“deposite completed…”); 48
notify(); Prepared by: Mr.Said H Said
The University of Dodoma
Garbage Collection
In java garbage means unreferenced objects.
Garbage Collection is a process of reclaiming
runtime unused memory automatically.
In other words it is a way to destroy unused objects.
C uses free() and C++ uses delete() function to
clear garbage from memory.
In Java, it is performed automatically, so it provides
better memory management.
Garbage collection is performed by a daemon
thread called Garbage Collector(GC).
49
Prepared by: Mr.Said H Said
The University of Dodoma
Unreferenced Objects
By nulling the reference
Employee e = new Employee();
e = null;
By assigning a reference to another
Employee e1 = new Employee();
Employee e2 = new Employee();
e1 = e2; //now the 1st object referred by e1 is unreferenced
By anonymous object
new Employee();
etc
50
Prepared by: Mr.Said H Said
The University of Dodoma
finalize() method
Garbage collector of JVM collects only those
objects that are created by new keyword,
So if you have created any object without new
keyword, you can use finalize keyword to
perform cleanup processing.
It is invoked each time before the object is
garbage collected
Can be used to perform clean up processing
This method is defined in Object class
Syntax
protected void finalize(){}
51
Prepared by: Mr.Said H Said
The University of Dodoma
gc() method
The gc() method is used to invoke the garbage
collector to perform clean up processing.
The gc() is found in System and Runtime
classes
Syntax
public static void gc();
52
Prepared by: Mr.Said H Said
The University of Dodoma
Example
public class MyGarbage{
public void finalize(){
System.out.println(“object is garbage collected”);
}
public static void main(String args[]){
MyGarbage obj1 = new MyGarbage();
MyGarbage obj2 = new MyGarbage();
obj1.null;
obj2.null;
System.gc();
}
}
Note; neither finalization nor garbage collection is 53
1
Prepared by: Mr.Said H Said
The University of Dodoma
Drawing and Event Handling
⚫ Applets inherit drawing and event handling methods
of java.awt.Component class
⚫ Applets and applications use classes of AWT
(Abstract Windowing Toolkit) to produce user
interfaces
⚫ Drawing refers to anything related to representing
an applet on screen
e.g. :- drawing images, presenting user interface
components such as buttons
⚫ Event Handling refers to detecting and processing
user input such as mouse clicks, key presses,
saving files, minimizing windows, etc.
2
Drawing
⚫ Using java.awt.Graphics class directly for display has many
limitations
e.g. :- it doesn’t support scrolling
⚫ Using pre-made User Interface (UI) components overcomes
these limitations
⚫ UI components supplied by AWT
⚫ Buttons (java.awt.Button)
⚫ Checkboxes (java.awt.Checkbox)
⚫ Single-line text fields (java.awt.TextField)
⚫ Drawing areas (java.awt.Canvas)
⚫ Menus (java.awt.Menu, java.awt.MenuItem,
java.awt.CheckboxMenuItem)
⚫ Containers (java.awt.Panel, java.awt.Window and its subclasses), etc.
3
Drawing
⚫ Because Applet class inherits from the AWT
Container class adding components and
setting layout managers (to control the
components’ online positions) is easy
⚫ Some of the Container methods applets use
⚫ add - Adds the specified Component
⚫ remove - Removes the specified Component
⚫ setLayout - Sets the layout manager
4
Drawing
⚫ E.g. :- ScrollingSimple applet which uses a scrolling, non-editable text field
import java.applet.Applet;
import java.awt.TextField;
TextField field;
5
Drawing
//Add the text field to the applet.
add(field);
validate(); //this shouldn't be necessary
addItem("initializing... ");
}
6
Event Handling
⚫ Applets inherit a group of event-handling
methods from the Component class
⚫ The Component class defines
⚫ Set of methods for handling particular types of
events (e.g. :- mouseDown, keyUp)
⚫ handleEvent method which is a catch-all method
⚫ To react to an event, an applet must override
either the appropriate event-specific method
or the handleEvent method
7
Event Handling
⚫ E.g. :- Making the Simple applet respond to
mouse clicks
import java.awt.Event;
...
public boolean mouseDown(Event event, int x, int y) {
addItem("click!... ");
return true;
}
Output :
8
Object Oriented
Programming-Java
JDBC
1
Prepared by: Mr.Said H Said
The University of Dodoma
JDBC
⚫ JDBC Drivers
⚫ 5 Steps to connect to the database
⚫ Connectivity with Oracle using JDBC
⚫ Connectivity with MySQL using JDBC
⚫ Connectivity with Java DB using JDBC
⚫ Classes and Interfaces used in JDBC
2
JDBC
⚫ Java JDBC is a java API to connect and
execute query with the database.
⚫ JDBC API uses jdbc drivers to connect with
the database.
3
5 Steps to connect to the
database using JDBC
⚫ Register the driver class
⚫ Creating connection
⚫ Creating statement
⚫ Executing queries
⚫ Closing connection
4
1st Step
⚫ Register the driver class
⚫ The forName() method of class Class is used to register
the driver class. This method is used to dynamically
load the driver class.
System.out.println(rs.getInt(1)+" "+rs.getString(2));
5th Step
⚫ Close the connection object
⚫ By closing connection object statement a ResultSet will
be closed automatically. The close() method of
Connection interface is used to close the connection.
mysqlconnector.jar;.; as C:\folder\mysql-connector-java-5.0.8-bin.jar;.;
Connectivity with Oracle using
JDBC
⚫ Driver class: The driver class for the oracle database is
oracle.jdbc.driver.OracleDriver.
⚫ Connection URL: The connection URL for the oracle10G
database is jdbc:oracle:thin:@localhost:1521:xe
⚫ where jdbc is the API, oracle is the database, thin is the driver,
localhost is the server name on which oracle is running, we may
also use IP address, 1521 is the port number and XE is the
Oracle service name. You may get all these informations from the
tnsnames.ora file.
⚫ Username: The default username for the oracle database
is system.
⚫ Password: Password is given by the user at the time of
13
installing the oracle database.
Connectivity with Oracle using
JDBC…Example
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver"); //have to be loaded first to command line or IDE
//step2 create the connection object
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
//step3 create the statement object
Statement stmt=con.createStatement();
//step4 execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
//step5 close the connection object
con.close();
}catch(Exception e){ System.out.println(e);} 14
}}
Connectivity with Oracle using
JDBC…Example
To connect java application with the Oracle database ojdbc14.jar file is required to be loaded.
Two ways to load the jar file:
1. paste the ojdbc14.jar file in jre/lib/ext folder
2. set classpath
1) paste the ojdbc14.jar file in JRE/lib/ext folder:
Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file here.
2) set classpath:
There are two ways to set the classpath:
⚫ temporary
⚫ permanent
How to set the temporary classpath:
Firstly, search the ojdbc14.jar file then open command prompt and write:
1. C:>set classpath=c:\folder\ojdbc14.jar;.;
How to set the permanent classpath:
Go to environment variable then click on new tab. In variable name write classpath and in variable
value paste the path to ojdbc14.jar by appending ojdbc14.jar;.; as
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar;.;
15
Connectivity with Java DB
using JDBC
⚫ Driver class: The driver class for the Java DB database is
org.apache.derby.jdbc.EmbeddedDriver.
⚫ Connection URL: The connection URL for the Java DB
database is jdbc:derby://localhost:1527/Employee
⚫ where jdbc is the API, derby is the database, localhost is the server
name on which Java DB is running, we may also use IP address,
1527 is the port number and Employee is the database name. We
may use any database.
⚫ Username: User name is given by user during creation of
database.
⚫ Password: Password is given by the user during creation of
database.
16
Connectivity with JavaDB using
JDBC….Example
import java.sql.*;
Class JavaDBCon{
public static void main(String args[]){
try{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); //for NetBean it is loaded
Connection con = DriverManager.getConnection(
"jdbc:derby://localhost:1527/Employee", "said", "said");
//here Employee is database name, said is username and password
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}catch(Exception e){ System.out.println(e);} 17
}}
Classes and Interfaces used
DriverManager class
Connection interface
Statement interface
ResultSet interface
PreparedStatement interface
ResultSetMetaData interface
DatabaseMetaData interface
CallableStatement interface
RowSet interface
18
DriverManager class
⚫ The DriverManager class acts as an interface between user
and drivers. It keeps track of the drivers that are available and
handles establishing a connection between a database and the
appropriate driver. The DriverManager class maintains a list of
Driver classes that have registered themselves by calling the
method DriverManager.registerDriver().
• public static void registerDriver(Driver is used to register the given driver with
driver): DriverManager.
• public static void is used to deregister the given driver
deregisterDriver(Driver driver): (drop the driver from the list) with
DriverManager.
• public static Connection is used to establish the connection with
getConnection(String url): the specified url.
• public static Connection is used to establish the connection with
getConnection(String url,String the specified url, username and 19
userName,String password): password.
Connection interface
⚫ A Connection is the session between java application and database. The
Connection interface is a factory of Statement, PreparedStatement, and
DatabaseMetaData i.e. object of Connection can be used to get the object of
Statement and DatabaseMetaData. The Connection interface provide many
methods for transaction management like commit(), rollback() etc.
21
Example of Statement interface
//insert, update and delete the record.
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:x
e","system","oracle");
Statement stmt=con.createStatement();
//stmt.executeUpdate("insert into emp765 values(33,'Irfan',50000)");
//int result=stmt.executeUpdate("update emp765 set
name='Vimal',salary=10000 where id=33");
int result=stmt.executeUpdate("delete from emp765 where id=33");
System.out.println(result+" records affected"); 22
con.close(); }}
ResultSet interface
⚫ The object of ResultSet maintains a cursor pointing to a row of a table. Initially,
cursor points to before the first row.
⚫ By default, ResultSet object can be moved forward only and it is not updatable.
⚫ But we can make this object to move forward and backward direction by passing
either TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in
createStatement(int,int) method as well as we can make this object as updatable by:
1. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
2. ResultSet.CONCUR_UPDATABLE);
public boolean next(): is used to move the cursor to the one row next from the current
position
public boolean previous(): is used to move the cursor to the one row previous from the current
position.
public boolean first(): is used to move the cursor to the first row in result set object.
public boolean last(): is used to move the cursor to the last row in result set object.
public boolean absolute(int row) is used to move the cursor to the specified row number in the
ResultSet object
public boolean relative(int row) is used to move the cursor to the relative row number in the ResultSet
object, it may be positive or negative.
public int getInt(int columnIndex): is used to return the data of specified column index of the current row
as int. 23
public String getString(int columnIndex): is used to return the data of specified column index of the current row
as String.
Example of Scrollable ResultSet
// 3rd row.
import java.sql.*;
class FetchRecord{
public static void main(String args[]) throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syst
em","oracle");
Statement
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.C
ONCUR_UPDATABLE);
ResultSet rs=stmt.executeQuery("select * from emp765");
//getting the record of 3rd row
rs.absolute(3);
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close(); 24
}}