Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Object Oriented Programming-Java: OOP Vs POP, Java, Java Technologies

Download as pdf or txt
Download as pdf or txt
You are on page 1of 393

Object Oriented

Programming-Java

OOP vs POP, Java,


Java Technologies,

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 1 Function 2 Function 3

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.

⚫ These classes are grouped into packages—collections


of related classes
⚫ Classes include pieces called methods that perform
tasks
⚫ Java contain a collection of ready made clasess called
Java class libraries, which are also known as the Java
APIs (Application Programming Interfaces).
⚫ Class libraries are embedded in compilers by compiler
vendors
⚫ You can either use ready made classes or create your
own classes (user defined classes) 2
Five Phases of Java Program
⚫ Edit
⚫ Creasing a program
⚫ Writing source code using
⚫ Editors e.g. notepad etc are used, some
editors are integrated in IDEs.
⚫ Written program is saved in secondary
storage in a file with .java extension

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

you run a program.


Five Phases of Java Program
⚫ Load
⚫ program is placed in primary memory(RAM)
before it can execute
⚫ Loader is used for program loading
⚫ loader takes the .class files containing the
program’s bytecodes and transfers them to
primary memory(RAM).
⚫ The class loader also loads any of the .class
files provided by API or JCL that your program
uses.
⚫ The .class files can be loaded from a disk on
your system or over a network/Internet. 5
Five Phases of Java Program
⚫ Verify
⚫ as the classes are loaded, the bytecodes are
examined to ensure that they are valid and do
not violate Java’s security restrictions.

⚫ bytecode Verifier is used for Java code


verification

⚫ java enforces strong security, to make sure


that Java programs arriving over the network
do not damage your files or your system.
6
Five Phases of Java Program
⚫ Execute
⚫ the JVM executes the program’s bytecodes,
thus performing the actions specified by the
program.
⚫ translates the bytecodes into the underlying
computer’s machine language.

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");
}
}

( ) parentheses indicate method


{ } braces forming blocks to delimit the body of declaration
“ ” double quotation
‘ ’ quotation
; semicolon to terminate statement 8

Statements-perform method’s task


General Structure of a Java
program
⚫ Class: keyword is used to declare a class
⚫ Public: keyword is an access modifier which represents visibility.
⚫ Static: is a keyword, class method or static method. There is no
need to create object to invoke the static method. The main method
is executed by the JVM, so it doesn't require to create object to
invoke the main method. So it saves memory.
⚫ Void: is the return type of the method, it means it doesn't return any
value.
⚫ Main: represents startup of the program.
⚫ String[] args: is used for command line argument. We will learn it
later.
⚫ System.out: output object which allow output of characters to
command-line.
9
Outputting to the Console cont…

⚫ print: does not place output cursor at the beginning of a new


line
e.g
public class Sample
{
public static void main(String args[])
{
System.out.print("Hall Programing");
System.out.print("Hall Java");
}
} 10
Outputting to the Console cont…

⚫ println: place output cursor at the beginning of a new line


e.g
public class Sample
{
public static void main(String args[])
{
System.out.println("Hall Programing");
System.out.println("Hall Java");
}
}
11
Outputting to the Console count.
⚫ printf: formats output
⚫ E.g

public class Sample


{
public static void main(String args[])
{
System.out.printf("%s", "Hall World");
System.out.printf( "%s\n%s\n", "Welcome to", "Java Programming!" );

}
}

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.

⚫ Format specifiers example:


%s: placeholder for string
%d: placeholder for integers
%f: placeholder for doubles
%c: placeholder for character

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

System.in: standard input object reads of information typed by the user.


Escape Sequence
⚫ \: backslash is called escape character.
⚫ \n: Newline. Position the screen cursor at the
beginning of the next line.
⚫ \t: Horizontal tab. Move the screen cursor to the next
tab stop.
⚫ \r: Carriage return. Position the screen cursor at the
beginning of the current line—do not advance to the
next line. Any characters output after the carriage
return overwrite the characters previously output on
that line.
⚫ \\: Backslash. Used to print a backslash character.
⚫ \“: Double quote. Used to print a double-quote
character. For example displays 15
Comments
⚫ Comments make the code Readable
⚫ Give Comments wherever necessary
⚫ Eg.
⚫ // This is a single line of comments
⚫ /* This is a block
of comments */

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)

short Short Integer 16 bits(-32,768 to 32,767 )


long Long Integer 64 bits(-9, 223, 372, 036,
854, 775, 808 to 9, 223,
372, 036, 854, 775, 807)
float Single-Precision Floating Point 32 bits(……………………)

double Double-Precision Floating Point 64 bits(……………………)

char A Single Character 16 bits(0 to 65, 535)

boolean A Boolean Value (true or false) 1 bit(0, 1) 18


Data Types
⚫ Find out default value for every data type

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

⚫ Constants should be in capital letters


Variables (Fields)
⚫ Types of Variables
⚫ Local Variable: A variable that is declared
inside the method is called local variable.
⚫ Instance Variable: A variable that is declared
inside the class but outside the method is
called instance variable . It is not declared as
static.
⚫ Static variable: A variable that is declared as
static is called static variable. It cannot be
local.

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

- op1 - op2 Subtracts op2 from op1


* op1 * op2 Multiplies op1 by op2
/ op1 / op2 Divides op1 by op2
% op1 % op2 Computes the remainder
of dividing op1 by op2 26
Unary Arithmetic Operators
⚫ Shortcut increment decrement operators

Operator Use Description


++ op++ Increments op by 1; evaluates to the value
of op before it was incremented
++ ++op Increments op by 1; evaluates to the value
of op after it was incremented
-- op-- Decrements op by 1; evaluates to the value
of op before it was decremented
-- --op Decrements op by 1; evaluates to the value
of op after it was decremented
27
Unary Arithmetic Operators
⚫ E.g
public class A
{
public static void main(String[] args)
{
int x =5;
System.out.print(++x);
}
} 28
Relational and Conditional
Operators
⚫ Compares two values and determines the
relationship between them

Operator Use Returns true if


> op1 > op2 op1 is greater than op2

>= op1 >= op2 op1 is greater than or equal to op2


< op1 < op2 op1 is less than op2

<= op1 <= op2 op1 is less than or equal to op2


== op1 == op2 op1 and op2 are equal
!= op1 != op2 op1 and op2 are not equal 29
Operators precedency and
association
Operator Associativity Type

* / % Left to right Multiplicative

+ - Left to right Additive

< <= > >= Left to right Relational

== != Left to right Equality

= Right to left Assignment

The operators are shown from top to bottom in


decreasing order of precedence. 30
Operator precedency and
associativity
⚫ Precedency
⚫ y = a * x * x + b * x + c; → y = ( a * x * x ) + ( b * x ) + c;
⚫ z = p * r % q + w / x - y; →

⚫ 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

|| op1 || op2 either op1 or op2 is 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

Operator Use Description


>> op1 >> op2 shift bits of op1 right by
distance op2
<< op1 << op2 shift bits of op1 left by
distance op2
>>> op1>>>op2 shift bits of op1 right by
distance op2 (unsigned)
33
Shift and Logical Operators
⚫ e.g. :- 13 >> 1
Shifting 1101 (13) to right by one position
results in 110 (6)

34
Shift and Logical Operators
⚫ Bitwise functions of number operands

Operator Use Description


& op1 & op2 bitwise and

| op1 | op2 bitwise or

^ op1 ^ op2 bitwise xor

~ ~ 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

op1 op2 Result


0 0 0
0 1 0
1 0 0
1 1 1

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

[] Used to declare arrays, create arrays, and


access array elements
. Used to form qualified names

( params ) Delimits a comma-separated list of


parameters
( type ) Casts (converts) a value to the specified type

new Creates a new object or a new array

instanceof Determines whether its first operand is an


instance of its second operand
39
Special Operators
⚫ op1 ? op2 : op3 (ternary operator)
returns op2 if op1 is true or returns op3 if op1
is false
⚫ [ ] operator
e.g. :-
float[] arrayOfFloats = new float[10];
arrayOfFloats[6] accesses the 7th element of
the array
40
Special Operators
⚫ Dot (.) Operator :-
Accesses instance members of an
object or class members of a class
⚫ The ( ) operator :-
Used to list arguments when calling a method
⚫ The new operator :-
Used to create new objects
e.g. :- Integer anInteger = new Integer(10);

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

The University of Dodoma


Control Structure:
multiple selection(switch stat)
 e.g.
public class MyClass {

public static void main(String args[]){


Scanner scan = new Scanner(System.in);
System.out.println("enter the score");

int score = scan.nextInt();


//byte, short, int or char
switch(score){
case 90:
System.out.println("very good");
break;
case 60:
System.out.println("good");
break;
case 40:
System.out.println("ok");
break;
default:
System.out.println("value is not defineed");
break;
} 10
Prepared by: Mr Said H Said
} The University of Dodoma
Control Structure:
multiple selection(switch stat)
 Write a method to output the following
 Grade = A – ‘Very Good’
 Grade = B – ‘Good’
 Grade = C – ‘Bad’

public void printResult(char grade) {


switch (grade) {
case ‘A’: System.out.println(“Very Good”); break;
case ‘B’: System.out.println(“Good”); break;
case ‘C’: System.out.println(“Bad”); break;
}
} 11
Prepared by: Mr Said H Said
The University of Dodoma
Control Structure:
repetition (For Statement)
 To repeat an operation several times

 for (initialization; termination; increment) {


statement(s)
}

 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

public void factorial(int number) {


int result = 1;
for (int i=1; i<=number; i++) {
result = result * i;
}
}
13
Prepared by: Mr Said H Said
The University of Dodoma
Control Structure:
repetition (While Statement)
 Continuously executes some statements
while a condition remain true

 while (Conditional Expression) {


statement(s)
}

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 {

publicstaticvoid main(String[] args)


{
intx = 1;

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

 Write a program to calculate the factorial of a


positive integer
 Using a While Loop
 Using a Do-While Loop

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

the data type Prepared by: Mr Said H Said


The University of Dodoma
Arrays-Single Dimentional
public class MyClass{
public static void main(String args[]){
int[] arr = new int[5];
//Inserting
arr[0] = 12;
arr[1] = 23;
arr[2] = 45;
arr[3] = 9;
arr[4] = 31;
//printing
System.out.println(arr[0]);
System.out.println(arr[1]);
System.out.println(arr[2]);
System.out.println(arr[3]);
27
System.out.println(arr[3]); }} Prepared by: Mr Said H Said
The University of Dodoma
Arrays-Single Dimensional
 e.g
 public class ArrayDemo {
public static void main(String[] args) {
int[] anArray; // declare an array of integers
anArray = new int[10]; // create an array of integers

// assign a value to each array element and print


for (int i = 0; i < anArray.length; i++) {
anArray[i] = i+10;
System.out.print(anArray[i] + " ");
}
System.out.println();
}
} 28
Prepared by: Mr Said H Said
//you can also use enhanced for loop i.e for(int elem:anArray)
The University of Dodoma
Arrays-Single Dimentional
public class MyClass{
public static void main(String args[]){
int[] arr = {13,10,11,21,16};
int index = 0;
//System.out.println(arr[index]);
while(index< 5) {
System.out.println(arr[index]);
index++;
}
}
} 29
Prepared by: Mr Said H Said
The University of Dodoma
Arrays-Single Dimentional
 Array Initializing
 boolean[] answers = { true, false, true, true, false };

 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.

 The first character that you don’t want, !, is the


character at position 12
 The appropriate substring command is:

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

 Allow software reusability Prepared by: Mr.Said H Said


The University of Dodoma
Methods
Syntax :
Access modifiers returnType methodName(parameterList)
{
//Method Body
}

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

int myMethod(int x, double y)


{
//code
}

//invoking a method and passing arguments


objectName.myMethod(5, 4.9);

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();
}

public static void myMethod()


{
System.out.println("Hallow Java");
} 14
Prepared by: Mr.Said H Said
The University of Dodoma
Methods
e.g Parameters
Public class MyClass{
public static void main(String args[]){
myMethod("said");
add(23,56);
add(45,89);
add(56,577);
add(34,67);
}
public static void myMethod(String name){
System.out.println("hellow " + name);
}
public static void add(inta, intb){
System.out.println(a + b);
}
15
} Prepared by: Mr.Said H Said
The University of Dodoma
Methods
 e.g Returning a value
public class MyClass{
public static void main(String args[]){
int sum = add(23,56);
System.out.println(sum);
}

public static void myMethod(String name){


System.out.println("hellow " + name);
}

public static int add(inta, intb){


return(a + b);
}
}
16
Prepared by: Mr.Said H Said
The University of Dodoma
Method Overloading
 Several methods with the same name declared in
the same class but perform different logic or tasks
 These methods have different signature, differ in
type of parameter, number of parameters and
order of the parameters.
 Return type may be different or the same
 The compiler distinguishes overloaded methods by
their signature—a combination of the method’s
name and the number, types and order of its
parameters.
17
Prepared by: Mr.Said H Said
The University of Dodoma
Method Overloading
 e.g
public class MyClass{
public static void main(String args[]){
System.out.println(Add(1,36));
System.out.println(Add(5.656,40.66));
System.out.println(Add("Hellow ","World"));
}
public static int Add(int a, int b){
return (a + b);
}
public static double Add(double a, double b){
return ( a+ b);
}
public static String Add(String a, String b){
return (a + b);
}
18
} Prepared by: Mr.Said H Said
The University of Dodoma
What is an Object?
 In real world, object is an entity that have state and
behavior.
 e.g. chair, bike, marker, pen, table, car, phone etc

 State(variables, attribute, field): represents data (value) of


an object
 State change time to time and Methos are responsible for
change of state
 Behavior: represents the behavior (functionality) of an
object such as deposit, withdraw etc.
 e.g. Your Mobile phone
 State – Make, Model, Color

 Behavior – Receiving, Sending

 An object can be physical or logical (tangible and 19


Prepared by: Mr.Said H Said

intangible). The University of Dodoma


What is an Object?
 An Object in Software is a bundle of variables (state)
and related methods (operations).
 Object is an instance of a class. Class is a template or
blueprint from which objects are created. So object is
the instance(result) of a class.
 Objects have identities
 Object identity is typically implemented via a unique
ID.
 The value of the ID is not visible to the external
user.
 But,it is used internally by the JVM to identify each
object uniquely.
20
Prepared by: Mr.Said H Said
The University of Dodoma
What is an Object?

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

 class and interface

25
Prepared by: Mr.Said H Said
The University of Dodoma
Class Vs Object

 NumberOfGears is called a Class Variable and holds


the same value for all Objects of the Class
26
Prepared by: Mr.Said H Said
The University of Dodoma
Class vs Object
 Class is the logical entity only whereas
Object is the physical as well as logical entity.
 Class is a template or blueprint from
which objects are created whereas Object
is an instance of a class(result of a class).

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

 Enclose data inside an object


 Cannot be accessed directly from outside
 Provides data security

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.

 If not specified, the default constructor


is used.
 Class can have more than one
constructor 33
Prepared by: Mr.Said H Said
The University of Dodoma
Constructors
 Each class you declare can provide a constructor that
can be used to initialize an object of a class when the
object is created
 constructor call is indicated by the class name
followed by parentheses
 the constructor must have the same name as the
class.
 Keyword new calls the class’s constructor to perform
the initialization.
 By default, the compiler provides a default
constructor with no parameters in any class that
does not explicitly include a constructor 34
Prepared by: Mr.Said H Said
The University of Dodoma
Constructors
 If class does not declare any constructor, a compiler creates
default constructor to initialize objects to their default values
 If a class declares constructor, compiler will not create default
constructor. In this case to specify default initialization for object
of your class you must declare a no-argument constructor
 Default constructors and no-argument constructors are invoked
with empty parentheses.
 If a class has constructors, but none of the public constructors
are no-argument constructors, and a program attempts to call a
no-argument constructor to initialize an object of the class, a
compilation error occurs.
 A constructor can be called with no arguments only if the class
does not have any constructors (in which case the default
constructor is called) or if the class has a public no-argument 35
Prepared by: Mr.Said H Said
constructor. The University of Dodoma
Constructors
public class Cube {
int length;
int breadth;
int height;
Cube(){
length = 10;
breadth = 20;
height = 30;
}
public int getCubeVolume(){
return (length * breadth * height);
}
}
//client class
Public class MyClass{
Public static void main(String args[]{
Cube cube1 = new Cube(); 36
Prepared by: Mr.Said H Said
System.out.println(cube1.getCubeVolume());}} The University of Dodoma
Constructors
publicclass Cube {
int length;
int breadth;
int height;
Public int getCubeVolume(){
return (length * breadth * height);
}
Cube(){
length = 10;
breadth = 20;
height = 30;
}
Cube(intl, intb, inth){
length = l;
breadth = b;
height = h; }}
//client class
Public class MyClass{
publicstaticvoid main(String args[]){
Cube cube1 = new Cube();
System.out.println(cube1.getCubeVolume());
Cube cube2 = new Cube(20,20,20); 37
Prepared by: Mr.Said H Said
System.out.println(cube2.getCubeVolume()); }} The Universisty of Dodoma
Constructors
public class GradeBook{ public class GradeBookTest
private String courseName; {
public GradeBook( String name ) { public static void main( String args[] )
courseName = name; {
} GradeBook gradeBook1 = new
public void setCourseName( String GradeBook("CS101 Introduction to
name ) { Java Programming" );
courseName = name; GradeBook gradeBook2 = new
} GradeBook("CS102 Data Structures
in Java" );
public String getCourseName() {
System.out.printf( "gradeBook1
return courseName; course name is: %s\n",
} gradeBook1.getCourseName() );
public void displayMessage() { System.out.printf( "gradeBook2
System.out.printf( "Welcome to the course name is: %s\n",
grade book for\n%s!\n", gradeBook2.getCourseName() );
getCourseName() ); } } } 38
Prepared by: Mr.Said H Said
The University of Dodoma
Constructors
import java.util.Scanner;
public class Account{ public class AccountTest{
private double balance; public static void main( String args[] ) {
Account account1 = new Account( 50.00 );
public Account(double initialBalance){ Account account2 = new Account( -7.53 );
System.out.printf( "account1 balance:$%. 2f\n",
if ( initialBalance > 0.0 ) account1.getBalance() );
balance = initialBalance; System.out.printf( "account2 balance:$%. 2f\n\n",
account2.getBalance() );
} Scanner input = new Scanner( System.in );
double depositAmount;
public void credit(double amount) { System.out.print( "Enter deposit amount for account1: " );
depositAmount = input.nextDouble();
balance = balance + amount; System.out.printf( "\nadding%.2f to account1 balance\n\n",
} depositAmount );
account1.credit( depositAmount );
public double getBalance() System.out.printf( "account1 balance:account1.getBalance() );
System.out.printf( "account2 balance:$%.2f\n\n",
{ account2.getBalance() );
System.out.print( "Enter deposit amount for account2: " );
return balance; depositAmount = input.nextDouble();
} System.out.printf( "\nadding %.2f to account2 balance\n\n",
depositAmount );
} account2.credit( depositAmount );
System.out.printf( "account1 balance:$%.2f\n",
account1.getBalance() ); System.out.printf( "account2
39
balance:$%.2f\n", account2.getBalance() );
Prepared by: Mr.Said H Said
}} The University of Dodoma
Defining a Class

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!" );
}
}

//class with main


public class GradeTest{
public static void main( String args[] ){
Grade myGrade = new Grade();
myGrade.displayMessage();
} 41
Prepared by: Mr.Said H Said
} The University of Dodoma
Objects and Classes
 When each object of a class maintains its own copy of an
attribute, the field that represents the attribute is also known as
an instance variable—each object (instance) of the class has a
separate instance of the variable in memory.

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 ); } }

//class with main


import java.util.Scanner;
public class GradeBookTest{
public static void main( String args[] ){
Scanner input = new Scanner( System.in );
GradeBook myGradeBook = new GradeBook();
System.out.println( "Please enter the course name:" );
String nameOfCourse = input.nextLine(); 44
Prepared by: Mr.Said H Said
myGradeBook.displayMessage( nameOfCourse ); } } The University of Dodoma
Some Standards
 Class Names Start with a Uppercase and be a noun.
 String, Button etc

 Variable Names Start with a Lowercase


 myVariable

 Method Names start with a Lowercase and be a verb


 print(), display()

 Interface name start with uppercase and be an adjective


 Runable, remote etc

 Package name should be in lowercase letters


 lang, util etc

 Constants name should be in uppercase


 RED, PIE etc

 Always give meaningful names 45


Prepared by: Mr.Said H Said

 Use Indentation where necessary The University of Dodoma


Access Modifiers
 The access modifiers public, private and protected
control access to a class’s variables and methods.
 Public
 Variables or methods declared with access modifier public are
accessible to methods of other classes (class’s client) in which they
are not declared.
 Public class members are directly accessible outside the class.
 Private:
 Variables or methods declared with access modifier private are
accessible only to methods of the class in which they are declared.
 Private class members are not directly accessible outside the class.
 Declaring instance variables with access modifier private is known as
data hiding.
 Protected
 An intermediate access modifier between private and public 46
Prepared by: Mr.Said H Said
The University of Dodoma
Access Modifiers

Modifier Class Package Subclass World

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)

 In the same file


 Only class with main method should be public
 .class files are produced for both

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;

 For multiple classes


 Import packageName .*;
 javac -d . Time1.java
 -d specifies exact directory to store a class 65
Prepared by: Mr.Said H Said
The University of Dodoma
Object Oriented
Programming
Inheritance,
polymorphism,
abstraction

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 SubclassName extends SuperclassName


{
//methods and fields
}

 The extends keyword indicates that you are


making a new class that derives properties from
from an existing class. Prepared by: Mr.Said H Said
The University of Dodoma
5
Types of inheritance
 Single inheritance

class Employee{
float salary = 40000;
}

class Programmer extends Employee{


int bonus = 10000;
public static void main(String args[]){
Programmer p = new Programmer();
System.out.println(“Programmer salary is:” + p.salary);
System.out.println(“Bonus of Programmer is:” + p.bonus);
}
} Prepared by: Mr.Said H Said
6

The University of Dodoma


Types of inheritance
 Single inheritance
Public class Polygon {
Protected int height;
Protected int width;
Public void setValue(int a, int b){
height = a;
width = b;
}}
Public class Rectangle extends Polygon{
Public double area(){
return (width * height)/2;
}}
Public class MyClass{
Public static void main(String args[]){
Rectangle rec = newRectangle();
rec.setValue(10, 10); 7
Prepared by: Mr.Said H Said
System.out.println(rec.area()); }} The University of Dodoma
Types of inheritance
 Multilevel inheritance
class A{
float salary=100000;
}
class B extends A{
int bonusB = 20000;
}
class C extends B{
int bonusC =10000;
}
public class MyMain{
public static void main(String args[]){
C obj = new C();
System.out.println("A earning is:" + obj.salary);
System.out.print("B earning is: ");
System.out.println(obj.salary + obj.bonusB );
System.out.print("C earning is: "); 8
Prepared by: Mr.Said H Said
System.out.println(obj.salary+ obj.bonusB + obj.bonusC ); }The} University of Dodoma
Types of inheritance
 Hierarchical inheritance
class Employee{
float salary = 40000;
}
class Programmer extends Employee{
int bonusP=20000;
public static void main(String args[]){
Programmer p = new Programmer();
System.out.println("Programmer salary is:” + p.salary);
System.out.println("Bonus of Programmer is:” + p.bonus); } }
class Accountant extends Employee{
int bonusA=10000;
public static void main(String args[]){
Accountant a = new Accountant();
System.out.println(“Accountant salary is:"+a.salary);
9
System.out.println("Bonus of Accountant is:"+a.bonusA);
Prepared by: } }
Mr.Said H Said
The University of Dodoma
Types of inheritance
 Hierarchical inheritance
Public class Polygon {
Protected int height;
Protected int width;
Public void setValue(int a, int b){
height = a;
width = b; }}
Public class Rectangle extends Polygon {
Public double area(){
return (width * height)/2; }}
Public class Triangle extends Polygon{
Public double area(){
return (width * height); }}
public class MyClass{
Public static void main(String args[]){
Rectangle rec = new Rectangle();
Triangle tri = new Triangle();
rec.setValue(10, 10);
tri.setValue(10, 10);
10
System.out.println(rec.area()); Prepared by: Mr.Said H Said
The University of Dodoma
System.out.println(tri.area()); }}
Types of inheritance
 To reduce the complexity and simplify the
language, multiple inheritance is not
supported in java.

 Multiple inheritance  Hybrid inheritance

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

}} Prepared by: Mr.Said H Said


The University of Dodoma
Super keyword-to invoke
superclass constructor
public class Vehicle{
Vehicle(){
System.out.println(“vehicle created”);
}}
class Bike extends Vehicle{
Bike(){
super(); //will invoke parent class constructor
System.out.println(“bike created”);
}
public static void main(String args[]){
Bike b = new Bike();
}}

 however, if super keyword is not provided compiler will implicitly provide it as


the first statement of the constructor you have created 21
Prepared by: Mr.Said H Said
The University of Dodoma
Super keyword-to invoke superclass
methods
 Used in case the subclass contain the same method(s) as its
superclass, otherwise no need to use super keyword
public class MyMain
public class Vehicle{
{
void message(){
public static void main(String args[])
System.out.println(“this is vehicle”);
{
}}
Bike b = new Bike();
class Bike extends Vehicle{
b.display();
void message(){
}
System.out.println(“this is bike”);
}
}
void display(){
message(); //will invoke current class
message
super.message(); //will invoke
superclass message 22
Prepared by: Mr.Said H Said
The University of Dodoma
}}
instanceof operator

 Instanceof operator is used to test whether the


object is an instance of a specified type(class,
subclass or type)
 It is also known as type comparison operator
because it compares instance with the type
 It returns either true or false

23
Prepared by: Mr.Said H Said
The University of Dodoma
instanceof operator

public class person


{
public static void main(String args[])
{
person p = new Person();
System.out.println(s instanceof Person); //true
}
}

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

} Prepared by: Mr.Said H Said


The University of Dodoma
More on final keyword

 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

 Ways of achieving abstraction in java


 Abstract class(0 to 100%)

 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

 Different return type: error

 Same return type, different parameter type:


implement each method (overloading)
 Same return typr and parameter: implement
once
 Same variable name

 Solved with prefix


33
Prepared by: Mr.Said H Said
The University of Dodoma
Interfaces

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();
}

public class NMB impliments Bank{


public int getInterestRate(){
return 5;
}
Public static void main(String args[]){
Bank b = new Bank();
b.getInterestRate();
}
}

37
Prepared by: Mr.Said H Said
The University of Dodoma
Interfaces-multiple inheritance
 Multiple inheritance in java

interface interface interface interface

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”);}

public static void main(String args[]){


Honda = new Honda();
obj.move();
obj.drive();
} 39
Prepared by: Mr.Said H Said
The University of Dodoma
}
Object Oriented
Programming
Exceptions, Files and
Streams

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 7 //exception occurs

 Statement 8

 Statement 9

 Statement 10 Prepared by: Mr.Said H Said


3

The University of Dodoma


Exceptions
 Eg-
 Dividing an integer number by zero,
ArithmeticException, int a = 50/0;
 Accessing an Out of Bounds Array Element,
ArrayIndexOutOfBoundsException, int a[] = new
int[5]; a[10] =50;
 Accessing non existing file, NullPointerException,
String s= null;System.out.print(s.length());
 a value which does not match,
NumberFormatException, String s= “abc”; int
i=Integer.prseInt(s);
 Down casting to wrong object, ClassCastException,
Vehicle v = new Car(); Bike b = (Bike)v; 4
Exceptions
 An Exception has to be thrown so that it could be
caught at a later time
 When the system encounters exception, an
Exception Object is created
 It contains the details of the Exception
 The exception is then handed over to the Runtime
System to be handled
 This is called Throwing an Exception
 It has to be Caught and Handled so that we can take
measures to recover from the error
 The thrown Exception is propagated up the Call 5

Stack
Exceptions-Hierarchy

6
Prepared by: Mr.Said H Said
The University of Dodoma
Exceptions-Types

 According to sun microsystems there are 3


types of exceptions:

 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

 Checked exceptions are checked at compile


time
 Not Runtime Exceptions

8
Unchecked Exceptions
 The classes that extent RuntimeException
are known as unchecked exceptions e.g
arithmeticException etc

 Unchecked exceptions are not checked at


compile time
 They are checked at runtime
 Run time exceptions

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)

 Then that method throws the Exception to the


outside (throws clause in the method definition)

 Any Object derived


from the Throwable
Class can be thrown
19
Throws
 A throws clause specifies the exceptions the
method throws.
 This clause appears after the method’s parameter
list and before the method’s body.
 It contains a comma-separated list of the
exceptions that the method will throw if a problem
occurs. Such exceptions may be thrown by
statements in the method’s body or by methods
called from the body.
 A method can throw exceptions of the classes
20

listed in its throws clause or of their subclasses.


Prepared by: Mr.Said H Said
The University of Dodoma
Throw
 The throw statement is executed to indicate that an
exception has occurred.
 A throw statement specifies an object to be thrown.

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.

public class MyException extends Exception {


public MyException() {
super("My Exception");
}
}
23
Defining an Exception
 Normally done when the required type of
exception is not provided by Java
 Possible to implement a hierarchy of
exceptions

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
}

method2 throws someException {


call method3;
}

method3 throws someException {


someCode;
}
26
Advantages of Exceptions
 Grouping Error Types and Error Differentiation

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

 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.

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

 Abstract Windowing Toolkit is an API to


develop GUI
 AWT are platform-dependent i.e components
are displayed according to the view of
operating system.
 AWT is heavyweight i.e its components uses
the resources of system.
 The java.awt package provides classes for
AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
3
Prepared by: Mr.Said H Said
The University of Dodoma
AWT-class hierarchy
Button
Object
Label
Component
Checkbox

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

 To create simple AWT, 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)

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

The University of Dodoma


Example of AWT by association
import java.awt.*;
public class First{
First(){
Frame new Frame();
Button b = new Button(“click me”);
b.setBounds(30, 100, 80, 30); //position button
f.add(b); //add button into frame
f.setSize(300, 300); //frame size
f.setLayout(null); // no layout manage
f.setVisible(true); //make frame visible, by default not
}
public static void main(String args[]){
8
First f = new First(); }} Prepared by: Mr.Said H Said
The University of Dodoma
Swing
 It is built on top of AWT API
 Entirely written in Java
 It is platform independent
 Lightweight components
 Javax.swing package contain classes for
swing API
 Provides more powerful components than
AWT

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

Window Panel JSlider

Applet JMenu

Frame Dialog AbstractButton

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

}} The University of Dodoma


Example Swing-by association
inside constructor.
import javax.swing.*;
public class MySwing{
JFrame f;
MySwing(){
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);
}
public static void main(String args[]){
14
new MySwing(); Prepared by: Mr.Said H Said
The University of Dodoma
Example Swing-by inheritance.
import javax.swing.*;
public class MySwing extends JFrame{
JFrame f;
MySwing(){
JButton b = new JButton(“click”);
b.setBounds(130,100,100,40); //x, y, w, h
add(b); //add button in frame
setSize(400,500);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new MySwing();
15
}} Prepared by: Mr.Said H Said
The University of Dodoma
Swing
import javax.swing.*;
public class Student{
public static void main(String[] args){
String str1= JOptionPane.showInputDialog(“Enter the fitrst
integer” );
String str2= JOptionPane.showInputDialog(“Enter the
second integer” );

int num1 = Integer.parseInt(str1);


int num2 = Integer.parseInt(str2);
int sum = num1 + num2;
JOptionPane.showMessageDialog(null, “The sum is: ” + sum,
“Sum of two integers”, JOptionPane.PLAIN_MESSAGE );
} 16
Prepared by: Mr.Said H Said
} The University of Dodoma
JButton class
 Used to create a button that have platform-
independent implementation
 It extends AbstractButton class.
 Commonly used constructors
 JButton(): create button with no text and icon
 JButton(String s): create button with the specified text
 JButton(Icon i): create button with the specified icon object

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

button with the specified text and selected status.


The University of Dodoma
Example JRadioButton class
import javax.swing.*;
public class Radio{
JFrame f;
Radio(){
f = new JFrame();
JRadioButton r1 = new JRadioButton(“A) Male”);
JRadioButton r2 = new JRadioButton(“B) Female”);
r1.setBounds(50,100,70,30);
r2.setBounds(50,150,70,30);
ButtonGroup bg = new ButtonGroup();
bg.add(r1); bg.add(r2);
f.add(r1); f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){ 20
new Radio(); } } Prepared by: Mr.Said H Said
The University of Dodoma
JTextArea class
 Is used to create a text area.
 It creates a multiple area that displays the
plain text only.
 Commonly used constructors
 JTextArea(): create a text area that displays no
text initially.
 JTextArea(String s): create a text area that
displays a specified text initially;
 JTextArea(int row, int column): create a text area
with specified number of rows and columns that
displays no text initialy.
 JTextArea(String s, int row, int column): create a
text area with specified number of rows and 21

columns that displays specified text. Prepared by: Mr.Said H Said


The University of Dodoma
Example JTextArea class
import java.awt.Color;
import javax.swing.*;
public class Text{
JTextArea area;
JFrame f;
Text(){
f = new JFrame();
area = new JTextArea();
area.setBounds(10,30,300,100);
area.setBackground(Color.black);
area.setForeground(Color.white);
f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[]){
22
new Text(); }} Prepared by: Mr.Said H Said
The University of Dodoma
Jslider class
 The JSlider is used to create the slider.
 By using JSlider a user can select a value from a
specific range.
 Commonly used Constructors of JSlider class:
 JSlider(): creates a slider with the initial value of 50 and
range of 0 to 100.
 JSlider(int orientation): creates a slider with the specified
orientation set by either JSlider.HORIZONTAL or
JSlider.VERTICAL with the range 0 to 100 and initial value
50.
 JSlider(int min, int max): creates a horizontal slider using the
given min and max.
 JSlider(int min, int max, int value): creates a horizontal slider
using the given min, max and value.
 JSlider(int orientation, int min, int max, int value):
Prepared creates
by: Mr.Said H Said a
23

The University of Dodoma


Example of JSlider class
import javax.swing.*;

public class Slider extends JFrame{


public Slider () {
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
JPanel panel = new JPanel();
panel.add(slider);
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String s[]) {
Slider frame= new Slider();
frame.pack();
frame.setVisible(true); 24
Prepared by: Mr.Said H Said
}} The University of Dodoma
JProgressBar class:
 The JProgressBar class is used to display the
progress of the task.
 Commonly used Constructors of JProgressBar class:
 JProgressBar(): is used to create a horizontal progress bar
but no string text.
 JProgressBar(int min, int max): is used to create a horizontal
progress bar with the specified minimum and maximum
value.
 JProgressBar(int orient): is used to create a progress bar
with the specified orientation, it can be either Vertical or
Horizontal by using SwingConstants.VERTICAL and
SwingConstants.HORIZONTAL constants.
 JProgressBar(int orient, int min, int max): is used to create a
progress bar with the specified orientation, minimum and
maximum value. 25
Prepared by: Mr.Said H Said
The University of Dodoma
Example of JProgressBar class
import javax.swing.*;
public class MyProgress extends JFrame{
JProgressBar jb;
int i=0,num=0;
MyProgress(){
jb = new JProgressBar(0,2000);
jb.setBounds(40,40,200,30);
jb.setValue(0);
jb.setStringPainted(true);
add(jb); setSize(400,400);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void iterate(){
while(i<=2000){
jb.setValue(i);
i=i+20;
try{Thread.sleep(150);}catch(Exception e){}
} }
public static void main(String[] args) {
MyProgress m=new MyProgress(); 26
Prepared by: Mr.Said H Said
m.setVisible(true); The University of Dodoma
JTable class

 The JTable class is used to display the data


on two dimensional tables of cells.
 Commonly used Constructors of JTable
class:
 JTable(): creates a table with empty cells.
 JTable(Object[][] rows, Object[] columns): creates
a table with the specified data.

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

 The JComboBox class is used to create the


combobox (drop down list). At a time only
one item can be selected from the item list.
 Comonly used constructors
 JComboBox()
 JComboBox(Object[] items)
 JComboBox(Vector<?> items)

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:

 The JColorChooser class is used to create a


color chooser dialog box so that user can
select any color.
 Commonly used Constructors of
JColorChooser class:
 JColorChooser(): is used to create a color
chooser pane with white color initially.
 JColorChooser(Color initialColor): is used to
create a color chooser pane with the specified
color initially.

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

 Read about 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

FocusEvent FocusListener Prepared by: Mr.Said H Said


The University of Dodoma
Steps to perform Event
Handling
 Implement the Listener interface and
override its methods
 Register the component with the Listener

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 {

 The Listener has to be added to the components


component.addActionListener(instanceOfMyClass);

 The methods of the Interface have to be


implemented
public void actionPerformed(ActionEvent e) {
...//code that reacts to the action...
}
Implementing an Event Handler
import javax.swing.*;
import java.awt.*;
import java.awt.event. *;

public class Beeper extends JApplet implements ActionListener {


JButton button;
public void init() {
button = new JButton("Click Me");
getContentPane().add(button, BorderLayout.CENTER);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
System.out.println(“Button Clicked!!!”);
}
}
Event Listeners
 The Event Handler Methods pass the Event Object
as a parameter
 Information about the event can be found from this
Object
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
}

 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

 ActionListener Interface has a method that


any Class using it has to implement
 public void actionPerformed(ActionEvent e) { }
Mouse & Mouse Motion
Listeners
 Mouse Events occur when the user uses the mouse
to interact
 Mouse Click
 Mouse Press
MouseListener
 Mouse Release
 Enter the Components On-Screen Area
 Exit the Components On-Screen Area
 Mouse Move
MouseMotionListener
 Mouse Drag

 A Class that implements the MouseListener /


MouseMotionListener Interface will be notified of
these Events
Key Listener
 Key Events occur when the user uses the
Keyboard

 A Class that implements the KeyListener


Interface will be notified of these Events
 Key Typed
 Key Pressed
 Key Released
Window Listener
 Window Events occur when a Window is
 Opened or Closed
 Iconified or Deiconied
 Activated or Deactivated

 By implementing the WindowListener Interface


these Events can be captured
Registering
 For registering the component with the listener, many
classes provide the registration methods
 e.g
 Button
 public void addActionListener(ActionListener a){}
 MenuItem
 public void addActionListener(ActionListener a){}
 TextField
 public void addActionListener(ActionListener a){}
 public void addTextListener(TextListener a){}
 TextArea
 public void addTextListener(TextListener a){}
 Checkbox
 public void addItemListener(ItemListener a){}
 Choice
 public void addItemListener(ItemListener a){}
 List
50
 public void addActionListener(ActionListener a){} Prepared by: Mr.Said H Said
The University of Dodoma
 public void addItemListener(ItemListener a){}
Event Handling code
 Can be placed:
 In the same class
 In another class
 In anonymous class

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

 Multitasking is the computer’s ability to


execute multiple tasks concurrently.
 More than one program are running concurrently.

 Multitasking can be achieved by using two


ways.
 Process-based multitasking(multiprocessing)
 Thread-based multitasking(multithreading)

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

model Prepared by: Mr.Said H Said


The University of Dodoma
Threads
 A thread itself is not a
program; It cannot run
on its own; Rather it
runs within a
program/process
 The concept having a
single thread within a
program is nothing new
since all the programs
have a single thread

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

method exits The University of Dodoma


Life cycle of a Thread(Thread
states)
New

start() Sleep done, I/O


complete, lock available,
resume, notify
Runnable

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();
}
}

 The execution of the thread is started and the run()


method is invoked by calling the start() method 16
Prepared by: Mr.Said H Said
The University of Dodoma
Example 2 for Subclassing
Thread class cont…
 Output of TwoThreadsDemo :-
0 Jamaica
0 Fiji
1 Fiji
1 Jamaica
2 Jamaica
2 Fiji
3 Fiji
3 Jamaica
4 Fiji
DONE! Fiji
4 Jamaica
DONE! Jamaica

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

 Used to sleep a thread for the specified


amount of time
 Syntax
 public static void sleep(long milliseconds)
throws InterruptedException{
}
 public static void sleep(long milliseconds, int
nanos) throws InteruptedException {
}

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()

 run() starts a current call stack


 start() starts a new call stack

 Invoking the run() method from main thread,


the run() method goes onto the current call
stack rather than at the beginning of a new
call stack

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

main() run() run()

Stack A Stack B Stack C


(main thread) ( t1 thread) (t2 thread)
26
Prepared by: Mr.Said H Said
The University of Dodoma
join() method
 Waits for a thread to die
 cause the currently running threads to stop executing
until the thread it joins with completes its task.

 Syntax
public void join() throws InterruptedException{
}

public void join(long milliseconds) 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.

public class MyThread extends Thread{


public void run(){
System.out.println(“task one”);
}
public static void main(String args[]){
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
t1.start();
t2.start();
t3.start();
}
} 33
Prepared by: Mr.Said H Said
The University of Dodoma
Performing single task by
multiple threads cont…..
 Each thread use separate callstsack

main() run() run() run()

Stack A Stack B Stack C Stack B


(main thread) ( t1 thread) (t2 thread) (t3 thread)
34
Prepared by: Mr.Said H Said
The University of Dodoma
Performing multiple tasks by
multiple threads
 Use more than one run() methods.
public class MyThread extends Thread{
public void run(){
System.out.println(“task one”);
}
}
public class YourThread extends Thread{
public void run(){
System.out.println(“task two”);
}
}
public class MyMain{
public static void main(String args[]){
MyThread t1 = new MyThread();
YourThread t2 = new YourThread();
t1.start();
t2.start();
35
} Prepared by: Mr.Said H Said
The University of Dodoma
Synchronization
 The ability to control the access of multiple
threads to any shared resource
 Used when we want to allow only one thread
or process to access the shared resource
 Used to prevent threads or processes from
interfering with one another while sharing
data.
 Used to provide a desired consistency
 Types
 Process synchronization
 Thread synchronization 36
Prepared by: Mr.Said H Said
The University of Dodoma
Synchronization
 Synchronization in java is built around an
entity called lock or monitor
 Every object has a lock associated with it
 A thread that needs consistence access to an
object’s fields has to acquire the objects lock
before accessing them and then release the
lock when it is done with them.
 java.util.concurrent.locks contain several lock
implementations

37
Prepared by: Mr.Said H Said
The University of Dodoma
Threads Synchronization

 A thread level synchronization.


 Types of thread synchronization
 Mutual exclusive
 Cooperation (Inter-thread communication)

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

 Used to perform synchronization on any


specific resource of a method
 e.g 5 lines out of 100 lines of codes in the
method
 Used to lock an object for any shared
resource
 Scope of synchronized block is smaller than
method
 Syntax
synchronized(object reference expression){
//code block 43
Prepared by: Mr.Said H Said

} The University of Dodoma


Synchronized Block
public class Table{
void prinTable(in n){
for(int i = 1; i < = 5; i++){ class MyMain(){
synchronized(this){ //synchronized block public static void main(String args[]){
System.out.println(n*i); Table obj = new Table();//only one object
try{ MyThread1 t1 = new MyThread1(obj);
Thread.sleep(400); MyThread2 t2 = new MyThread2(obj);
}catch(Exception e){System.out.println(e);} t1.start();
} // end for t2.start();
} //end of block }
} //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;}
44
public void run(){t.prinTable(100);} Prepared by: Mr.Said H Said
The University of Dodoma
} //end class
Static Synchronization

 If you make any static method as synchronized,


the lock will be on the class not on object
 Static synchronization is all about applying
synchronized keyword on the static method to
perform static synchronization
 Syntax
Synchronised static void methodName(){
}

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

guaranteed. Prepared by: Mr.Said H Said


The University of Dodoma
Object Oriented
Programming
Events,

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;

public class ScrollingSimple extends Applet {

TextField field;

public void init() {


//Create the text field and make it uneditable.
field = new TextField();
field.setEditable(false);

//Set the layout manager so that the text field will be


//as wide as possible.
setLayout(new java.awt.GridLayout(1,0));

5
Drawing
//Add the text field to the applet.
add(field);
validate(); //this shouldn't be necessary

addItem("initializing... ");
}

public void start() {


addItem("starting... ");
}

public void stop() {


addItem("stopping... ");
}

public void destroy() {


addItem("preparing for unloading...");
}

void addItem(String newWord) {


String t = field.getText();
System.out.println(newWord);
field.setText(t + newWord);
}
}

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.

⚫ Syntax of forName() method


⚫ public static void forName(String className)throws
ClassNotFoundException

⚫ Example to register the OracleDriver class


⚫ Class.forName("oracle.jdbc.driver.OracleDriver"); 5
2nd Step
⚫ Create the connection object
⚫ The getConnection() method of DriverManager class is used
to establish connection with the database.
⚫ Syntax of getConnection() method
⚫ public static Connection getConnection(String url) throws
SQLException
⚫ public static Connection getConnection(String url,String
name,String password) throws SQLException
⚫ Example to establish connection with the Oracle
database
⚫ Connection con=DriverManager.getConnection(
⚫ "jdbc:oracle:thin:@localhost:1521:xe","system","password");
6
3rd Step
⚫ Create the Statement object
⚫ The createStatement() method of Connection interface
is used to create statement. The object of statement is
responsible to execute queries with the database.

⚫ Syntax of createStatement() method


⚫ public Statement createStatement() throws
SQLException

⚫ Example to create the statement object


⚫ Statement stmt = con.createStatement(); 7
4th Step
⚫ Execute the query
⚫ The executeQuery() method of Statement interface is used to
execute queries to the database. This method returns the object
of ResultSet that can be used to get all the records of a table.

⚫ Syntax of executeQuery() method


⚫ public ResultSet executeQuery(String sql) throws
SQLException

⚫ Example to execute query


⚫ ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()) 8

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.

⚫ Syntax of close() method


⚫ public void close() throws SQLException

⚫ Example to close connection


⚫ con.close();
9
Connectivity with MySQL using
JDBC
⚫ Driver class: The driver class for the mysql database is
com.mysql.jdbc.Driver.
⚫ Connection URL: The connection URL for the mysql
database is jdbc:mysql://localhost:3306/name of
database(mpaki) created
⚫ where jdbc is the API, mysql is the database, localhost is the server
name on which mysql is running(we may also use IP address), 3306
is the port number and mpaki is the database name. We may use any
database.
⚫ Username: The default username for the mysql database is
root.
⚫ Password: Password is given by the user at the time of
installing the mysql database. In this example, we are going 10

to use root as the password.


Connectivity with MySQL using
JDBC….Example
import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("com.mysql.jdbc.Driver");
//step2 create the connection object
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
//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();
11
}catch(Exception e){ System.out.println(e);}
}}
Connectivity with MySQL using
JDBC….Example
To connect java application with the mysql database mysqlconnector.jar file is required to be
loaded.
Two ways to load the jar file:
1. paste the mysqlconnector.jar file in jre/lib/ext folder
2. set classpath
1) paste the mysqlconnector.jar file in JRE/lib/ext folder:
Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.
2) set classpath:
There are two ways to set the classpath:
⚫ temporary
⚫ permament
How to set the temporary classpath
open comman prompt and write:
1. C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.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 the mysqlconnector.jar file by appending 12

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.

• public Statement createStatement(): creates a statement object that can be


used to execute SQL queries.
• public Statement Creates a Statement object that will
createStatement(int generate ResultSet objects with the given
resultSetType,int type and concurrency.
resultSetConcurrency):
• public void setAutoCommit(boolean is used to set the commit status.By default
statu it is true.
• public void commit(): saves the changes made since the
previous commit/rollback permanent.
• public void rollback(): Drops all changes made since the
previous commit/rollback.
• public void close(): closes the connection and Releases 20
a
JDBC resources immediately.
Statement interface
⚫ The Statement interface provides methods to execute queries with the
database. The statement interface is a factory of ResultSet i.e. it provides
factory method to get the object of ResultSet.

• public ResultSet executeQuery(String is used to execute SELECT query. It


sql): returns the object of ResultSet.
• public int executeUpdate(String sql): is used to execute specified query, it may
be create, drop, insert, update, delete etc.

• public boolean execute(String sql): is used to execute queries that may


return multiple results.
• public int[] executeBatch(): is used to execute batch of commands.

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

}}

You might also like