Java

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 583

OBJECT ORIENTED PROGRAMMING

Lecture #1: Introduction

by
Mrs. Akhila Pragada
JAVA IS _____

simple programming language


one of the most popular programming language
open-source and free
has a huge community support (tens of millions of developers)
close to C & C++
it helps to create modular programs and reusable code
write a program once and then run this program on multiple operating systems
works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
 Java is a high-level, object-oriented programming language
JAVA IS USED

Mobile applications (specially Android apps)


Desktop applications
Web applications
Gaming Applications
Cloud-based Applications
Software Tools
Database connection
And much, much more!
COMPANIES THAT USE JAVA
JAVA HISTORY

Developed by Sun Microsystems Inc in 1991


Initially named as Oak, later changed to Java

First publicly available version – Java 1.0 released in 1995


Oracle corporation acquired Sun Microsystems in 2010
The latest version of Java is Java 14 or JDK 14 released on March, 17th 2020
INSTALLATION
INSTALLATION
INSTALLATION
INSTALLATION
OBJECT ORIENTED PROGRAMMING

Lecture #2: POP vs OOP

by
Mrs. Akhila Pragada
PROGRAMMING LANGUAGES

Programming
languages

Procedure Oriented Object Oriented


languages languages
PROCEDURE ORIENTED
PROGRAMMING (POP)

• Large Programs are divided into sequence of functions (Procedures)

Program

Function Function Function 3


1 2
• Each procedure can be called by another procedure during execution by
calling it using its name
• In POP main focus is on procedures only not on data
• Follows “Top-Down Approach”.
PROCEDURE ORIENTED
PROGRAMMING (POP)

• Global variables can be accessed by all functions

Global Variables Global Variables


1 2

Function 1 Function 2 Function 3

Local Local Local


variables variables variables
• No security to data - Data can be freely moved from one procedure to another procedure
• If we need to change the type of data of global variable then we need to revise all the functions
that are using this global variables. Failing this may result in errors
• POP does not model real world problems very well. Because functions are action oriented
• Examples: C, PASCAL, COBOL, BASIC, FORTRAN
OBJECT ORIENTED
PROGRAMMING (OOP)

• In OOP data is secured -does not allow it to flow freely among functions
• Program is divided into objects and then built functions and data around
these objects.
Student
Object Object Object
1 2 Name
Data Data Rollno
Age
Function Function Branch
s s
Attendanc
Data
e
Object
Percentage
Function 3
s
OBJECT ORIENTED
PROGRAMMING (OOP)

• Data of an object is accessed only by the functions associated by that object


• Objects communicate with each other through functions
• In OOP emphasis is given to data rather than procedures
• OOP follows “Bottom-Up Approach”

Main Program

Function Function Function


1 2 3
Examples: Java, VB.Net, C#
POP VS OOP

Procedure Oriented Programming Object Oriented Programming

• Program is divided into smaller • Program is divided into entities


programs called Procedures called Objects
• Top-Down Approach • Bottom-Up Approach
• Importance is given to procedures • Importance is given to data rather
rather than data
than Procedures/functions
• No security to data
• Data is Secure
• Does not model real-world problems
very well • Model real-world problems
•Suitable for developing medium size • Suitable to developing large size
projects projects
C VS JAVA

C Java

• Procedure Oriented Programming • Object Oriented Programming Language


Language • Complied & Interpreted
• Complied • Does not support preprocessor directives
• Supports Preprocessor Directives • Internally manages the memory
• User takes care of memory management • Does not use pointers
• Uses pointers • Platform independent
• Platform dependent
• Variable can be declared anywhere
• Variable declaration at the beginning of
•No global variable
the block
• Uses global variable
OBJECT ORIENTED PROGRAMMING

Lecture #3: Features of Java


CHARACTERISTICS OF OOP

• Object
• Class
• Data Abstraction
• Encapsulation
• Inheritance
• Polymorphism
• Dynamic Binding
• Message Passing
CLASS & OBJECT

A class is a data type that allows programmers to create objects.


A class provides a definition for an object, describing an object’s
attributes (data) and methods (operations).

An object is an instance of a class. With one class, you can have


as many objects as required.

This is analogous to a variable and a data type, the class is the


data type and the object is the variable.
DATA ABSTRACTION

Data abstraction is the process of hiding certain details


and showing only essential information to the user.
ABSTRACTION
ENCAPSULATION

Encapsulation is a mechanism of wrapping the data


(variables) and code acting on the data (methods)
together as a single unit.
ENCAPSULATION
INHERITANCE

Inheritance can be defined as the process where one


class acquires the properties (methods and fields) of
another class. 
POLYMORPHISM

An operation exhibits different behaviors in different


instances
DYNAMIC BINDING

Dynamic binding also called dynamic dispatch is the process of


linking procedure call to a specific sequence of code (method) at run-
time.

It means that the code to be executed for a specific procedure call is


not known until run-time.

 Dynamic binding is also known as late binding or run-time binding.


MESSAGE PASSING

Message Passing is nothing but sending and receiving


of information by the objects same as people exchange
information.
FEATURES OF JAVA

•Object
• Class
• Data Abstraction
• Encapsulation
• Inheritance
• Polymorphism
• Dynamic Binding
• Message Passing
• Platform independent
• Compiled and interpreted
• Robust and secure
• Distributed
• Multi-threading
• Dynamic and extensible
JAVA BUZZWORDS

Platform independent
“Write once and run anywhere”
Secure
Based on public key encryption and helps to design virus free systems
Architectural and Neutral
Ability of generating Architectural-neutral objects that can run on multiple processors
Portable
Uses a compiler that is written using ANSI C and POSIX sub suit making it portable
Robust
Eliminates the most number of errors in the compile time itself
Multi-Threading
Capable to execute code simultaneously above multiple processors at a time.
OBJECT ORIENTED PROGRAMMING

Lecture #4: First Java program


JAVA VIRTUAL MACHINE (JVM)

Byte Code Execute


Java Compiler Output
.class file (JVM)
File
SIMPLE JAVA PROGRAM

class classname class First


{ {
public static void main (String a[]) public static void main (String a[])
{ {
Block of statements System.out.print(“First java program”);

}
}
}
}

Note: keywords:
• Java is case sensitive class, public, static, void
• class name first letter should be capital
• Every statement should end with semicolon
COMPILING AND EXECUTING

Byte Code
Execute
Java Compiler Output
.class file (JVM)
File

Saving:
First.java

Compiling: p a th
g c l as s
javac First.java
Sett i
Execution:
java First
OBJECT ORIENTED PROGRAMMING

Lecture #5: Compiling & Executing


Javaprogram (Setting classpath)
SIMPLE JAVA PROGRAM

class First
{
public static void main (String a[])
{
System.out.print(“First java program”);

}
}

Note: keywords:
• Java is case sensitive class, public, static, void
• class name first letter should be capital
• Every statement should end with semicolon
COMPILING AND EXECUTING

Byte Code
Execute
Java Compiler Output
.class file (JVM)
File

Saving:
First.java

p ath
Compiling:
g cl a ss
javac First.java
e t t i n
S
Execution:
java First
OBJECT ORIENTED PROGRAMMING

Lecture #6: Structure of Java Program


STRUCTURE OF JAVA PROGRAM

Documentation
Section
Package Statements
Import Statements Optional
Interface Statements
Class Definitions
Main method class
{
main method Essentia
definition l
}
DOCUMENTATION SECTION

• Used for writing comment lines


• Ignored by compiler

3 ways:
⮚ //
This is for single line Ex: //Welcome to Java program

⮚ /* */
This is for multiple lines Ex: /* Welcome to
Java Program */

⮚ /** */
This is used to generate automatic comment
PACKAGE STATEMENT

Java packages are a mechanism to group Java classes that are related to each


other, into the same "group" (package)

Ex: package Employee


IMPORT STATEMENTS

To import java package into a class, we need to use java import keyword


which is used to access package and its classes into the java program

Can import built-in and user-defined packages

Ex: import java.lang.Math.*;


Import java.util.*;
INTERFACE STATEMENTS

Used to achieve multiple inheritance


CLASS DEFINITIONS

Class Definitions Optional


Main method class
{
main method Essentia
definition l
}

Any number of classes can be defined


All the objects of class should be created in main method.
One class should have main method—Main method class
OBJECT ORIENTED PROGRAMMING

Lecture #7: Variables & Datatypes


VARIABLE

A Java variable is a piece of memory that can contain a data value.


Variables are typically used to store information 
Variable Declaration:

Syntax: Example:
datatype variable int
name; a;
 Variable Assignment:
Assigning a value to a variable 
Syntax: Example:
variable
name=value; a=10;
VARIABLE

Variable Naming Conventions:

• Java variable names are case sensitive. The variable name apple is not the same
as Apple or APPLE.

• Java variable names must start with a letter, or the $ or _ character.

• After the first character in a Java variable name, the name can also contain numbers (in
addition to letters, the $, and the _ character).

• Variable names cannot be equal to reserved key words in Java. For instance, the
words int or for are reserved words in Java. Therefore you cannot name your
variables int or fo
DATATYPES IN JAVA

Data type specifies the size and type of values that can be stored in an
variable.
ed
DataType Deriv e
yp
Datat

Primitiv Non-
e Primitive

Numeri Non-Numeric classe Arra


c s y

Integer Floating Char Boolea Interfac


Point n e
INTEGER

Integer types can hold whole numbers such as 123 and −96. 
The size of the values that can be stored depends on the integer type that we choose.

Type Size Range of values that can be stored


byte 1 byte −128
−128toto127
127
shor 2 −32768
−32768toto32767
32767
t bytes Example:
int 4 −2,147,483,648 to 2,147,483,647
bytes inr a;
long 8 9,223,372,036,854,775,808 to byte
bytes 9,223,372,036,854,755,807 b;
1 byte = 8 bits
a=10;
The range of values is calculated as −(2n−1) to (2n−1)−1; where n is the number of bits
required.
FLOATING POINT

Floating point data types are used to represent numbers with a fractional part.
There are two subtypes:

Type Size Range of values that can be stored


float 4 byte 3.4e−038 to 3.4e+038
double 8 1.7e−308 to 1.7e+038
bytes
Example:
float a;
double
b;
a=4.7;
CHARACTER

It stores character constants in the memory


It assumes a size of 2 bytes
Basically it can hold only a single character
Keyword: char
Keep the value in single quote.

Example:
char a;
char b;
a=‘k’;
b=‘2’;
BOOLEAN

Boolean data types are used to store values with two states: true or false.
Its size is 1 bit
Keyword: boolean

Example:
boolean a;
OBJECT DECLARATION
EXAMPLE PROGRAM
BASIC PROGRAM DEVELOPMENT

Edit and
save program
errors

errors
Compile program

Execute program and


evaluate results
Java Environment/
Life Cycle of Java Code
Runtime
Compile-time Environment Class
Environment Java
Loader
Class
Bytecode Libraries
Java Verifier
Source
(.java)

Java Just in
Java
Bytecod Time
Interpreter Java
es Compiler
Virtual
move
Java machine
locally
Compiler or
through
Runtime System
network

Java
Bytecod Operating System
e
(.class )
Hardware
CREATING, COMPILING AND
RUNNING JAVA PROGRAMS
JAVA KEYWORDS
OPERATOR EVALUATION

Parentheses have the highest precedence and it can be used to force an


expression to evaluate in order you want.
(3-1) is 2 and(1+1) **(5-2) is 8. you can also use parentheses to make an
expression easier to read, as in (min*100)/60, even though it does not change
the result.
Exponentiation has the next highest precedence, so 2**1+1 is 3 and not 4 and
3*1**3 is 3 and not 27.
Multiplication and division have the same precedence which is higher than
addition and subtraction which also has the same precedence. So 2*3-1=5 and
2/3-1=-1(integer division, 2/3=0).
Operators with the same precedence are evaluated from left to right. So in the
expression min*100/60, the multiplication operation takes first place, yielding
5900/60 which in turn yields 98.
If the operations had been evaluated from right to left, the result would have
been 59*1 that produce the result as 59 which is wrong
EXAMPLE:

12+20*2-4*2/2.0 # 48.0
1. 12+40-4*2/2.0
2. 12+40-8/2.0
3. 12+40-4.0
4. 52-4.0
5. 48.0
12+(20*2)-4*(2/2.0) # 48.0
12+(20*2)-(4*2)/2.0 # 48.0
expression is evaluated from left -> right. BODMAS(bracket of
division multiplication) rule is followed while evaluating the
expression.
OBJECT ORIENTED PROGRAMMING

Lecture #8: Control Statements in Java


(Part-1)
CONTROL STATEMENTS

Control
Statements

Selection Transfer
Statements Statements
Iterative
Statements
SELECTION STATEMENTS
(if)
“Simple
if”
Syntax: Flow
Chart
if(condition)  Example
{     
block1- stmt1 //checking the age  
block1-stmt2     if(age>18) 
}         System.out.print("Age > 18")
;  
    
SELECTION STATEMENTS
(if)

“if-else
Statement
Syntax:
” Flow
Chart
if(condition) Example
{  
block1-stmt1 if( x < 20 )
block1-stmt2 {
} System.out.print(“Yes");
else }
{ else
block2-stmt1 {
block2-stm2 System.out.print(“NO”);
} }  
    
SELECTION STATEMENTS
(if)

“Nested if-else Statement”


Syntax:
Flow
if(condition)
{
Chart Example
 
if(condition)
{ if( a>b)
block1-stmt1 {
block1-stmt2 if(a >c)
}
else System.out.print(“A is big");
{ else
block2-stmt1 System.out.print(“b is big");
block2-stm2
} }
else
} {
else
{ if(b >c)
block3-stmt1 System.out.print(“B is big");
block3-stm2 else
}
} System.out.print(“b is big");

}  
    
SELECTION STATEMENTS
(if)

“else-if Ladder Statement”


Syntax: Flow
if(condition)
Chart
{
block1-stmt1
block1-stmt2
}
else
{
if(condition)
{
block2-stmt1
block2-stmt2
}
else
{
block3-stmt1
block3-stm2
}
}
SELECTION STATEMENTS
(switch)

“switch Statement”
Syntax: Flow Example

switch(expression)
Chart switch(grade)
{ {
case value : case 'A' :
// Statements System.out.println("Excellent!");
break; // optional
case value : break;
// Statements case 'B' :
break; // optional case 'C' :
System.out.println("Well done");
break;
// You can have any case 'D' :
number of case System.out.println(“Passed");
statements. break;
case 'F' :
default : // Optional System.out.println(“Fail");
// Statements break;
} default :
System.out.println("Invalid
grade"); }
OBJECT ORIENTED PROGRAMMING

Lecture #9: Control Statements in Java


(Part-2)
by
CONTROL STATEMENTS

Control
Statements

Selection Transfer
Statements Statements
Iterative
Statements
ITERATIVE STATEMENTS
(while)
“while”
Repeatedly executes the block of statements as long as the condition is true
Entry-controlled Loop

FlowChar
Syntax:
t
Example:
while(expression)
{ x=0
block1- stmt1 while( x<10)
block1-stmt2 {
} System.out.println(x);
x=x+1;
}
print(“End of while”)
ITERATIVE STATEMENTS
(do-while)
“do-while”
Repeatedly executes the block of statements until the condition becomes False
Exit-controlled Loop

FlowChar
Syntax: t
Example:
do
{ x=0
block1- stmt1 do
block1-stmt2 {
} System.out.println(x);
while(expression) x=x+1;
; }
while( x<10);
print(“End of do-while”)
ITERATIVE STATEMENTS
(for)

“for” Flowchar
t
Syntax:

for(initialization; Boolean_expression; update)


{
// Statements
}

Example:

for(int x = 10; x < 20; x = x + 1)


{
System.out.print("value of x : " + x );
}
TRANSFER STATEMENTS
(break)

“break”
When the break statement is encountered inside a loop, the loop is immediately terminated and
the program control resumes at the next statement following the loop.

Flowchar
Syntax: t Example:

for(int i = 1; i < 5; i ++)


break; {
if( i == 3 )
break;
System.out.println( i );
}

Output:

1
2
TRANSFER STATEMENTS
(continue)

“continue”
In a loop, the continue keyword causes control to immediately jump to the next iteration.

Flowchar
Syntax: Example:
t
for(int i = 1; i < 5; i ++)
continue; {
if( i == 3 )
continue;
System.out.println( i );
}

Output:

1
2
4
PACKAGE DETAILS

Java user input(Scanner)


The Scanner class is used to get user input and it is found in the java.util package.
To use the scanner class, create an object of the class and use any of the available
methods found in the scanner class documentation.
There are some input types in Scanner package
nextBoolean() – reads a Boolean value from the user
nextByte() – reads a byte value from the user
nextDouble() - reads a double value from the user
nextFloat() – reads a float value from the user
nextInt() – reads a int value from the user
nextLine() - reads a string from the user
nextLong() – reads a long value from the user
nextShort() – reads a short value from the user
JAVA LANG PACKAGE

For writing any java program, the most commonly required classes and interfaces
are encapsulated in the separate packages which is nothing but java.lang package.
It is not required to import java package in our program because it is available by
default to every java program.
The following are the some of the important classes present in java.lang package.
1. Object
2. String
3. String buffer
4. All wrapper classes
5. Exception API
6. Thread API…etc.
JAVA.LANG.OBJECT CLASS

For any java object whether it is predefined or customized the most commonly required methods are
encapsulated into a separate class which is nothing but object class.
As object class act as a root (or) parent (or) super for all java classes , by default its methods are available to
every java class.
The following are the list of all methods present in java.lang object class
1. public String toString()
2. public native int hashCode()
3. public boolean equals(Object o);
4. protected native Object clone() throws CloneNotSupportedException;
5. public final Class<?> getClass();
6. protected void finalize () throws Throwble;
7. public final void wait() throws InteruptedException;
8. public final void wait(long ms , int ns) throws InteruptedException;
9. public final native void notify();
10. public final native void notifyAll();
ACCESS MODIFIERS

Access modifiers in java specifies the accessibility or scope of the field,


method, constructor, or a class.
We can change the access levels fields by applying the modifiers in it.
There are 4 access modifiers in java.
Public- for every where.
Private – only within the class. It cannot be accessed from the outside of the
class.
Protected- with in the package and outside the package through child class.
Default – only with in the package.
ACCESS MODIFIERS
TYPE CONVERSION

Converting one data type into another data type is known as type conversion
This is classified into 2 types
1. Automatic/ implicit type conversion
2. Explicit/ manual type conversion
Automatic Type Conversion:
It is possible to convert lower data type into higher data type .
Ex: byte a=5;
int b;
b=a;
This means a is of byte data type and b is int data type. If we write b=a means, a value is stored in b
but the value is in int data type.
Explicit Type Conversion:
It is possible to convert higher data type into lower data type. But we may loss data while conversion.
EXAMPLE

Ex: if float is converted into short data type


Float data type occupies 4 bytes of memory
Short data type occupies 2 bytes of memory
So while converting from higher data type to lower data type we lost some data.
Syntax: var= (target) variable;
Ex: float a;
int x;
x=(int) a;
Which means, a is converted into int data type and the result will be stored in x which
is already an integer data type.
So we are compressing the size of our data so this is nothing but type casting.
LEXICAL ISSUES

Java is a collection of
1. White spaces
2. Identifiers
3. Comments
4. Literals
5. Operators
6. Separators
7. Keywords
WHITE SPACES

Java is a free form language.


We don’t need to follow any special indentation rules
Ex: a program can be written in a single line or multi line or in any strange
way , as long as there is at least one white space character between each token
that is not already separated by an operator or separator.
In java , white space is a space or tab or new line
SEPARATORS
OBJECT ORIENTED PROGRAMMING

Lecture #10: Class & Object


CLASS DEFINITIONS

Class Definitions Optional


Main method class
{
main method Essentia
definition l
}

Any number of classes can be defined


One class should have main method—Main method class
All the objects of class should be created in main method.
CLASS

Defining a class:
A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type support.

Optional Syntax:

[Access_Modifier] class class_name


Variable {
s Fileds declaration;
Methods declerations; Members
Functions
}
CLASS

class_name:
Example:
class Student
class Example

Field declaration:
Syntax: In
var stance
[Access Modifier] type Variable_name; i
crea ables
a
i o nal [initial value] tim ted at re
Opt e of the
crea o bj
Example: tion ect
int age; Instance
float marks; Variable
float studentHeight;
CLASS

Method declaration:
Syntax:
[Access Modifier] returntype identifier (Paramenter_list)
{
al method_body
on
ti }
Op

Example: Example:
int add( int x, float b) int getStudentData( int x, float
{ b)
statements {
} statements
}
CLASS- EXAMPLE

Example:
class Student
{
int a,b;
int add( int x, float b)
{
statements
}
}
OBJECT

An object is an instance of a class.


To create an object “new” operator is used
Object creation:
2 parts-
• Declare the object
• Instantiate the object
Example:
class Student
Object creation:
{
int a,b;
Student obj;
int add( int x, float b)
obj=new Student();
{
statements
Object creation: }
}
Student obj=new Student();
OBJECT

Class creation:
Accessing class members
using .(dot) Operator class Student
{
int a,b;
int add( int x, float b)
Syntax:
{
objectname.variable_name=value;
statements
objectname.methodname(parameter_list);
}
}

Example:
Object creation:
obj.a=10;
obj.add(25,33.5);
Student obj=new Student();
OBJECT

Multiple objects can be created from a single class

Class creation: Object creation:

class Student Student s1=new Student();


{ Student s2=new Student();
int rollno; Student s3=new Student();
int add( int x, float b) s1.rollno=12;
{ s2.rollno=23;
statements s3.rollno=45;
}
}
PROGRAM WITH MULTIPLE
CLASSES

class Example class Addition


{ {
int a,b,c; public static void main(String args[])
void getData(int x, int y)
{
{
Example obj1=new Example();
a=x;
obj1.getData(25,25);
b=y;
obj1.add();
}
void add( ) }
{ }
Output:
c=a+b; Sum
System.out.print(“Sum is :”+c); is :50
}
}
PROGRAM WITH MULTIPLE
CLASSES

class Example Private class Addition


{
{
public static void main(String args[])
int a,b,c;
{
void getData(int x, int y) Example obj1=new Example();
{ obj1.getData(25,25);
a=x; obj1.add();

b=y;
Example obj2=new Example();
} obj2.getData(5,2);
void add( ) obj2.add();
{
}
Output:
c=a+b; Sum
}
System.out.println(“Sum is :”+c); is :50
} Sum is :7
}
OBJECT ORIENTED PROGRAMMING

Lecture #11: Array in Java-Introduction


WHY ARRAY?
Array
i
to ho s used
l
than d more
on e v
Consider : Consider : with alue
s
varia ame
int a; int a; ble n
ame
a=10; a=10;
a=20; System.out.print(“a= “+a);
System.out.print(“a= “+a); b=20;
System.out.print(“b= “+b);

Output: Output:
a= 20 a= 10
b=20

A Variable will hold only one value at a


time
ARRAY

Java array is an object which contains elements of a similar data type.


The elements of an array are stored in a contiguous memory location.

3 Steps:
• Declaration of array
• Instantiate the array
• Initialization of array
ARRAY

Declaration of Array:
Specifying Array name and datatype
2 forms
Syntax(Form-1): Syntax(Form-2):
type type[ ]
array_name[ ]; array_name;
Example(Form-1): Example(Form-2):
int roll_no[ ]; int[ ] roll_no;

Don’t Mention the


size
ARRAY

Instantiate the Array:


Allocating the memory to the array Example:
uses “new” operator int roll_no[ ];

Syntax: Example:
array_name= new roll_no=new int[5 ];
type[ size];
Combining Declaration & Instantiate the Array:

Syntax: Example:
type array_name[ ]= new type[ size]; int roll_no[ ]=new int[5 ];
ARRAY

Memory Allocation:
roll_n
int
roll_no[ ];
o
. Points
roll_n Nothing

roll_no=new
o
.
int[5 ]; roll_no[ 0
]
roll_no[ 1
Array in Java is index-based,
]
the first element of the array is roll_no[ 2
stored at the 0th index, ]
roll_no[ 3
2nd element is stored on 1st
]
index roll_no[ 4
and so on. ]
ARRAY

Initialization of Array: Example:


int roll_no[ ]=new int[5 ];
Assigning values to the Array.
1. Compile-time:
• Assigning individual array elements:

Syntax: Example:
array_name[index]= value; roll_no[0]= 10;
roll_no[1]= 20;
• Combining declaration and initialization:
Syntax: Example:
type array_name[ ]= {list of int roll_no [ ]= {10,20,54,66,12};
values};
In this case required memory will be automatically created, no need of “new”
operator
ARRAY

Initialization of Array:
Reading values from user- Run-time
uses Scanner class (import java.util.*)
• To read a variable value • To read array values • To print array values
int a; int a[]=new int[5]; Using for or foreach
Scanner s; Scanner s; for(i=0;i<5;i++)
a=s. nextInt( ); for(i=0;i<5;i++) {
{ System.out.println(a[i]);
a[i]=s. nextInt( ); }
}
for(int i : a)
{
System.out.println( i);
}
OBJECT ORIENTED PROGRAMMING

Lecture #12: Two Dimensional Array


TYPES OF ARRAY

Java array is an object which contains elements of a similar data type.


The elements of an array are stored in a contiguous memory location.

3 Steps:
• Declaration of array
• Instantiate the array
• Initialization of array

3 types of Arrays:
1. One-Dimensional Array
2. Two-Dimensional Array
3. Multi-Dimensional Array
ONE-DIMENSIONAL ARRAY

Combining Declaration & Instantiate the Array:


Syntax: Example:
type array_name[ ]= new type[ size]; int roll_no[ ]=new int[5 ];
Memory Allocarion:

.
roll_n 0 1 2 3 4
Initialization: o
int a[]=new int[5];
Syntax:
type array_name[ ]= {list of Scanner s= new Scanner(System.in);
values}; for(i=0;i<5;i++)
Example:
{
int roll_no [ ]= {10,20,54,66,12};
a[i]=s. nextInt( );
}
TWO-DIMENSIONAL ARRAY

Used to store more than one value


Used to represent the data in the form of matrix or table
Declaration of Array:
Specifying Array name and data-type
Syntax: Example:
type array_name[ ] int a[ ][ ];
[ ];
Instantiate the Array:
Allocating the memory to the array
uses “new” operator
Syntax: Example:
array_name= new type[ r-size][c- a=new int[3][4];
size];
Syntax: Example:
type array_name[ ][ ]= new type [ r-size][c- int a[ ][ ] = new int[3][4];;
size];
TWO-DIMENSIONAL ARRAY

Memory Allocation:

Example:
int a[ ][ ] = new int[3][4];;

Individual element is accessed: 0 1 2 3


a[r-index][c-index] 0
1
First element: a[0][0]
Second element: a[0][1] 2
Third element: a[0][2]
12th element: a[2][3]
TWO-DIMENSIONAL ARRAY

Initialization of Array:
Assigning values to the Array.
1. Compile-time:
Example:
• Assigning individual array elements: int a[ ][ ]=new int[3 ][4];

Syntax: Example:
array_name[r-index][c-index]= a[0][0]= 10;
value; a[0][1]= 20;
a[1][2]=65;
a[2][3]=35;
TWO-DIMENSIONAL ARRAY

Combining declaration and initialization:

Syntax: Example:
type array_name[r-size][c-size]= {list of int a[3][2]= {10,20,54,66,12,77};
values};
Example:
int a[3][2]= {{10,20},{54,66},
{12,77}};
In this case required memory will be automatically created, no need of “new”
operator
a[0][0] = a[1][0] = a[2][0] = 0 1
10
a[0][1] = 20 54
a[1][1] = 12
a[2][1] = 0 10 20
66 77
1 54 66
w i l l be
s
Value row by 2 12 77
stored w
ro
TWO-DIMENSIONAL ARRAY

Initialization of Array:
Reading values from user- Run-time
uses Scanner class (import java.util.*)

int a[][]=new int[3][2]; • To print array values


Scanner s= new Scanner(System.in);
for(i=0;i<3;i++) for(i=0;i<3;i++)
{
{
for (j=0; j<2;j++)
{ for (j=0; j<2;j++)
a[i][j]=s. nextInt( ); {
} System.out.println(a[i][j]);
}
}
}
OBJECT ORIENTED PROGRAMMING

Lecture #13: Muli-Dimensional Array and


Jagged Arrays
MULTI-DIMENSIONAL ARRAY

The Multi Dimensional Array in Java programming language is nothing but an Array
of Arrays (Having more than one dimension). 
Two Dimensional Array, which is the simplest form of Java Multi Dimensional Array.
we can declare n-dimensional array or Muti dimensional array by placing n number of
brackets [ ], where n is dimension number.
3D-Array Declaration:
Syntax: Example:
type array_name[ ][ ][ ]; int a[ ][ ][ ];

Instantiate the 3D-Array:


Syntax: Example:
array_name= new type[Tables][ r-size][c- a= new int[2][ 3]
size]; [4];
MULTI-DIMENSIONAL ARRAY

Initialization of Array:
Assigning values to the Array.
1. Compile-time:
Example:
• Assigning individual array elements: int a[ ][ ][ ]=new int[2][ 3]
[4];
Syntax: Example:
array_name[table_no][r-index][c-index]= value; a[0][0][0]= 10;
a[0][0][1]= 20;
a[1][1][2]=65;
a[1][2][3]=35;
MULTI-DIMENSIONAL ARRAY

Combining declaration and initialization:

Syntax:
type array_name[tables][r-size][c-size]= {list of values};

Example:
int a[2][3][2]= {{ {5,6},{8,12},{7,90}} , {{10,20},{54,66},
{12,77}}};

In this case required memory will be automatically created, no need of “new”


operator
MULTI-DIMENSIONAL ARRAY

Initialization of Array:
Reading values from user- Run-time
uses Scanner class (import java.util.*)
• To print array values
int a[][][]=new int[2][3][4];
Scanner s= new Scanner(System.in); for(i=0;i<2;i++)
for(i=0;i<2;i++) {
{ for (j=0; j<3;j++)
for (j=0; j<3;j++) {
{
for(k=0;k<4;k++)
for(k=0;k<4;k++)
{
{
a[i][j][k]=s. nextInt( );
System.out.print(a[i][j][k]);;
} }
} }
} }
JAGGED ARRAY

Jagged array is a multidimensional array where member arrays are of different size.
For example, we can create a 2D array where first array is of 3 elements, and is of 4
elements.

Program:
int a[ ][ ];
0 1 2 3
a=new int[3][ ];
0
a[0]=new int[4];
1
a[1]=new int[2];
2
a[2]=new int[3];
ARRAY PACKAGE

Array class is included in java.util package


It contains several static methods that you can use to compare, sort and search in
arrays.
This class is a member of collection framework.
Different methods of this class are listed below.
Arrays.toString()
Arrays.asList()
Array.sort()
Array.binarySearch()
Array.copyOf()
Array.copyOfRange()
Arrays.fill() … etc.
METHODS IN ARRAYS

Arrays.ToString():
It returns the string representation of the array enclosed in the square braces[].
Adjacent elements are separated by the comma character.
Ex: int array[]={1,2,3,4,5,6,7};
System.out.println(Arrays.ToString(array));
Arrays.asList():
It returns a list backed by a given array . In other words, both the list and array refer to the same
location
Ex: List integerList= Array.asList(array);// returns a fixed size list backed by the specified array.
Arrays.sort():
This method sorts the specified array into ascending numerical order.
Arrays.sort(array)
METHODS IN JAVA

Arrays.binarySearch():
It returns an integer value for the index of the specified key in an specified
array. It returns a negative number if the key is not found and for this method
to work properly , the array must be sorted.
Ex: int idx= Arrays.binarySearch(baseArray,21);
Arrays.copyOf():
This method copies the specified array, truncates or pads with zeros so the
copy has the specified length.
Ex: int copyOfArray= Arrays.copyOf(baseArray,11);
OBJECT ORIENTED PROGRAMMING

Lecture #14: Strings


STRINGS

Java string is a sequence of characters. They are objects of


type String.
Once a String object is created it cannot be changed. Strings
are Immutable.
Creating an empty string.
String s = new String();
CREATING STRINGS

String str = "abc";


is equivalent to:
char data[] = {'a', 'b', 'c'};
String str = new String(data);
Construct a string object by passing another string object.
String str2 = new String(str);
STRING METHODS

length()
charAt()
equals()
equalsIgnoreCase()
startsWith()
endsWith()
compareTo()
compareToIgnoreCase()
indexOf()
lastIndexOf()
substring()
concat()
replace()
toLowerCase
STRING METHODS

length():
This method returns the length of the string

System.out.println(“Hello”.length()); //prints 5
String str1 = “CSE Department”
int a=str1.length(); //a=14
STRING METHODS

charAt( ):
Returns the character at the specified index. An index ranges
from 0 to length() - 1. The first character of the sequence is at
index 0, the next at index 1, and so on, as for array indexing.

char ch;
ch = “abc”.charAt(1); // ch = “b”
String str1 = “CSE Department”
char ch1;
ch1 = str1.charAt(4); // ch = “D”
STRING METHODS

equals( ):
Returns true if the invoking string contains the same character
sequence.

String str1 = “CSE Department”;


String str2 = “IT Department”;
if(str1.equals(str2))
System.out.println(“str1 and str2 are equal”);
else
System.out.println(“str1 and str2 are unequal”);
STRING METHODS

equalsIgnoreCase( );
Compares this String to another String, ignoring case
considerations.

String str1 = “CSE DEPARTMENT”;


String str2 = “cse department”;
if(str1.equalsIgnoreCase(str2)
System.out.println(“str1 and str2 are equal”);
else
System.out.println(“str1 and str2 are unequal”);
STRING METHODS

StartsWith( ):
Tests if string starts with the specified prefix

“Figure”.startsWith(“Fig”); // true

String str1 = “CSE DEPARTMENT”;


if(str1.startsWith(“IT”))
System.out.println(“yes it str1 starts with IT”);
else
System.out.println(“No it str1 is not starting with IT”);

Similarly endsWith()
OBJECT ORIENTED PROGRAMMING

Lecture #15: Strings (cont..)


STRING METHODS

compareTo( ):
Compares two strings lexicographically.
The result is a negative integer if this String object lexicographically
precedes the argument string.
The result is a positive integer if this String object lexicographically
follows the argument string.
The result is zero if the strings are equal.
String str1 = “CSE Department”;
String str2 = “IT Department”;
int result;
result= str1.compareTo(str2);
Similarly compareToIgnoreCase()
STRING METHODS

indexOf( ):
Searches for the first occurrence of a character or substring.
Returns -1 if the character does not occur.

String str = “How was your day today?”;


str.indexof(‘a’); // 5
str.indexOf(“was”); //4
STRING METHODS

lastIndexOf( ):
Searches for the last occurrence of a character or substring.

String str = “How was your day today?”;

str.lastIndexOf(‘a’); // 20
STRING METHODS

substring( ):
Returns a new string that is a substring of this string. The
substring begins with the character at the specified index and
extends to the end of this string.

"unhappy".substring(2) returns "happy"

String str = “How was your day today?”;


String str2 = str.substring(8);//your day today
STRING METHODS

concat( ):
Concatenates the specified string to the end of this string.
"to".concat("get").concat("her") returns "together"

String s1=“hello”;
String s2=“welcome”;
String s3=s1.concat(s2);//hellowelcome
STRING METHODS

replace( ):
Returns a new string resulting from replacing all occurrences of oldChar
in this string with newChar.

replace(char oldChar, char newChar)

"mesquite in your cellar“ .replace('e', 'o')


returns "mosquito in your collar"
STRING METHODS

toLowerCase(): Converts all of the characters in a String to


lower case.
toUpperCase(): Converts all of the characters in this String to
upper case.
“HELLO THERE”.toLowerCase();
“hello there”.toUpperCase();
EXPERIMENT

Write a Java program to


demonstrate String handling
methods.
STRING BUFFER

Java string buffer class is used to create mutable(modifiable ) string.


The string buffer class in java is same as string class except it is mutable. i.e., it can be
changed.
StringBuffer() – creates an empty string buffer with the initial capacity of 16.
StringBuffer(String str) – creates a string buffer with the specified string.
StringBuffer(int capacity) – creates an empty string buffer with the specified capacity
as length.
StringBuffer append() – the append() concatenates the given argument with this string.
Ex: StringBuffer sb=new StringBuffer(“hello”);
sb.append(“java”);
System.out.println(sb); // hellojava
STRING BUFFER METHODS

StringBuffer insert() – inserts the given string at the given position.


Ex: StringBuffer sb=new StringBuffer(“hello”);
sb.insert(1,“java”);
System.out.println(sb);//hjavaello
StringBuffer replace() – it replaces the given string from the specified beginIndex and
endIndex.
Ex: StringBuffer sb=new StringBuffer(“hello”);
sb.replace(1,3,“java”);
System.out.println(sb);// hjavalo
StringBuffer delete() – the delete() od StringBuffer class deletes the string from the
specified beginIndex and endsIndex.
Ex: StringBuffer sb=new StringBuffer(“hello”);
sb.delete(1,3);
System.out.println(sb);//hlo
STRING BUFFER METHODS

StringBuffer reverse() – the reverse() of StringBuffer class reverse the current


string.
Ex: StringBuffer sb=new StringBuffer(“hello”);
sb.reverse();
System.out.println(sb);//olleh
OBJECT ORIENTED PROGRAMMING

Lecture #16: Methods


METHODS

A method is a block of code or collection of statements or a set of code grouped


together to perform a certain task or operation.
It provides the reusability of code.
Naming a Method:
Method name must start with a lowercase letter
In the multi-word method name, the first letter of each word must be in uppercase
except the first word.
Example:
check()
There are two types of methods in Java:
sumOfNumbers()
1. Predefined Method
2. User-defined Method
PRE-DEFINED METHOD

Method that is already defined in the Java class libraries is known as


predefined methods.

Also called standard library method or built-in method.

Examples: length(), equals(), compareTo(), sqrt(), etc.

Import related package


USER-DEFINED METHOD

The method written by the user or programmer is known as a user-defined


method
We can modify the method according to our requirement.
Access Specifier:
Access specifier or modifier is the access type of the method. It specifies the visibility of the
method. Java provides four types of access specifier:

Public: The method is accessible by all classes when we use public specifier in our application.

Private: When we use a private access specifier, the method is accessible only in the classes in
which it is defined.

Protected: When we use protected access specifier, the method is accessible within the same
package or subclasses in a different package.

Default: When we do not use any access specifier in the method declaration, Java uses default
access specifier by default. It is visible only from the same package only.
Return Type:
Return type is a data type that the method returns.
If the method does not return anything, we use void keyword.

Method Name:
It is a unique name that is used to define the name of a method.
A method is invoked by its name.

Parameter List:
It is the list of parameters separated by a comma and enclosed in the pair of parentheses. It
contains the data type and variable name. If the method has no parameter, left the parentheses
blank.

Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.
class Example
{
public static void main(String[] args)
{
int a = 15;
int b = 5;
Example e=new Example();
int c = e.minNumber(a, b);
System.out.println("Minimum Value = " + c);
}
public int minNumber(int n1, int n2)
{
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
OBJECT ORIENTED PROGRAMMING

Lecture #17: Constructors


CONSTRUCTORS

• A constructor initializes an object when it is created.


• we use a constructor to give initial values to the instance variables defined by the
class, or to perform any other start-up procedures
• It has the same name as the class in which it resides.
• It is syntactically similar to a method
• At the time of calling constructor, memory for the object is allocated in the
memory.
• Every time an object is created using the new() keyword, at least one constructor
is called.
• It calls a default constructor if there is no constructor available in the class. In
such case, Java compiler provides a default constructor by default(initializes all
member variables to zero)
• Once we define our own constructor, the default constructor is no longer used.
CONSTRUCTORS

Rules for creating Java constructor

• Constructor name must be the same as its class name


• A Constructor must have no explicit return type
• A Java constructor cannot be abstract, static, final, and synchronized

There are two types of constructors in Java: Syntax:


class
ClassName
1. No-arguments constructor {
2. Parameterized constructor ClassName()
{
}
}
NO-ARGUMENTS CONSTRUCTOR

No argument constructors of Java does not accept any parameters.


Instance variables of a method will be initialized with fixed values for all
objects.
Syntax: Example: class Example
class ClassName { {
ClassName() Public class MyClass public static void main(String args[])
{ { {
var_name=value; Int num; MyClass o1 = new MyClass();
} MyClass() MyClass o2 = new MyClass();
} { System.out.println(o1.num + " " +
num = 10; o2.num);
} }
} }
Output:
10 10
PARAMETERIZED CONSTRUCTOR

The parameterized constructor is used to provide different values to distinct


objects. However, you can provide the same values also.
Accepts one or more parameters
Parameters are added to a constructor in the same way that they are added to a
method
Example: class Example
Syntax:
{
class ClassName {
class MyClass public static void main(String args[])
ClassName(parameters )
{ {
{
int x; MyClass o1 = new MyClass(10);
var_name=value;
MyClass(int MyClass o2 = new MyClass(20);
}
i) System.out.println(o1.num + " " +
}
{ o2.num);
x = i; }
} }
} Output: 10 20
CONSTRUCTORS VS METHODS
OBJECT ORIENTED PROGRAMMING

Lecture #18: Constructor Overloading


CONSTRUCTOR OVERLOADING

It is a technique of having more than one constructor with different parameter


lists.

Each constructor performs a different task.

They are differentiated by the compiler by the number of parameters in the list
and their types.
class Student{
int id;
String name;
int age;
Student(int i,String n)
{
id = i;
name = n;
} Output:
Student(int i,String n,int a) 11 jyothi 0
{ 22 Rama 25
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student s1 = new Student(11,"Jyothi");
Student s2 = new Student(22,"Rama",25);
s1.display();
s2.display();
}
}
OBJECT ORIENTED PROGRAMMING

Lecture #19: Method Overloading


polymo
rph
METHOD OVERLOADING means m ism
any
forms.
• Method overloading is one of the ways through which java supports
polymorphism.
• Polymorphism in Java is a concept by which we can perform a single
action in different ways.

• There are two types of polymorphism in Java: compile-time


polymorphism and runtime polymorphism. We can perform
polymorphism in java by method overloading and method overriding.

• Compile Time Polymorphism: At compile-time, java knows which


method to call by checking the method signatures. So this is called
compile-time polymorphism or static or early binding. Compile-time
polymorphism is achieved through method overloading.
METHOD OVERLOADING

• Method Overloading is a technique which allows declaring multiple methods


with same name but different parameters in the same class.

• They are differentiated by the compiler by changing number of arguments or by


changing the data type of arguments.

• If two or more method have same name and same parameter list but differs in
return type can not be overloaded.

• There are two different ways of method overloading.


1. Different datatype of arguments
2. Different number of arguments
METHOD OVERLOADING BY CHANGING
DATA TYPE OF ARGUMENTS.

class Calculate You can


see that
{ s u m () metho
o v d is
void sum (int a, int b) e r l oa de d t w
times. T o
{ he first t
t w ak es
System.out.println("sum is"+(a+b)) ; o integer
} a rguments
second t , the
void sum (float a, float b) akes two
{ float arg
uments.
System.out.println("sum is"+(a+b));
}
Public static void main (String[] args)
{
Calculate cal = new Calculate();
cal.sum (8,5); //sum(int a, int b) is method is called.
cal.sum (4.6f, 3.8f); //sum(float a, float b) is called.
}
}
METHOD OVERLOADING BY
CHANGING NO. OF ARGUMENT

class Demo multiply


()
{ overload method is
void multiply(int l, int b) ed twice
first met . T he
h o d t
{ argumen akes two
ts
System.out.println("Result is"+(l*b)) ; second m and the
etho
} three arg d takes
void multiply(int l, int b,int h) uments.
{
System.out.println("Result is"+(l*b*h));
}
public static void main(String[] args)
{
Demo a = new Demo();
a.multiply(8,5); //multiply(int l, int b) is method is called
a.multiply(4,6,2); //multiply(int l, int b,int h) is called
}
}
METHOD OVERLOADING AND
TYPE PROMOTION

One type is promoted to another implicitly if no matching datatype is found.


METHOD OVERLOADING AND
TYPE PROMOTION

class Example
{
void sum(int a,long b)
{
System.out.println(a+b);
} Output:40
void sum(int a,int b,int c) 60
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
Example obj=new Example();
obj.sum(20,20);//now second int literal will be promoted to long
obj.sum(20,20,20);
}
}
METHOD OVERLOADING AND
TYPE PROMOTION

class Example
{
void sum(int a,int b)
{
System.out.println(a+b);
} Output:20
void sum(long a,long b) 20
{
System.out.println(a+b);
}
public static void main(String args[])
{
Example obj=new Example();
obj.sum(20,20);//now int arg sum() method gets invoked
}
}
METHOD OVERLOADING AND
TYPE PROMOTION

class Example
{
void sum(int a,long b)
{
System.out.println("a method invoked");
}
void sum(long a,int b)
{
System.out.println("b method invoked");
}
public static void main(String args[])
{
Example obj=new Example(); Output: Compile Time Error
obj.sum(20,20);//now ambiguity
}
}
OBJECT ORIENTED PROGRAMMING

Lecture #20: “this” Keyword


THIS KEYWORD

refers to “this” object (object in which it is used)


usage:
with an instance variable or method of “this” class
as a function inside a constructor of “this” class
as “this” object, when passed as parameter
refers to “this” object’s data member
class Weight {
int lb; int oz;
public Weight (int lb, int oz ) {
this.lb = lb; this.oz = oz;
}
}
USAGE OF THIS KEYWORD

This can be used to refer current class instance variable


This can be used to refer current class method(implicitly)
This() can be used to invoke current class constructor.
The this keyword can be used o refer current class instance variable. If there is
ambiguity between the instance variable and parameters, this keyword
resolves the problem of ambiguity.
UNDERSTANDING THE PROBLEM
class Student{  
WITHOUT THIS KEYWORD
int rollno;  
String name;  
Here, p
ara
argume meters (form
float fee;  
n al
Student(int rollno,String name,float fee){   variabl ts) and instan
es a ce
rollno=rollno;   are usin re same. So, w
g e
name=name;   distingu this keyword
ish to
fee=fee;   and ins local variable
tance v
ariable
}   .
void display(){System.out.println(rollno+" "+name+" "+fee);}  
}  
class TestThis1{  
public static void main(String args[]){   Output:
Student s1=new Student(111,"ankit",5000f);   0 null 0.0
Student s2=new Student(112,"sumit",6000f);   0 null 0.0
s1.display();  
s2.display();  }}  
SOLUTION OF THE ABOVE
class Student{   PROBLEM BY THIS KEYWORD
int rollno;  
String name;  
float fee;  
Student(int rollno,String name,float fee){   If local variables(formal
this.rollno=rollno;   arguments) and instance
variables are different, there is
this.name=name;  
no need to use this keyword
this.fee=fee;  
}  
void display(){System.out.println(rollno+" "+name+" "+fee);}  
}  
class TestThis2{  
public static void main(String args[]){  
Student s1=new Student(111,"ankit",5000f);  
Student s2=new Student(112,"sumit",6000f);   Output:
s1.display();   111 ankit 5000
112 sumit 6000
s2.display();  }}  
PROGRAM WHERE THIS
class Student{   KEYWORD IS NOT REQUIRED
int rollno;  
String name;  
float fee;   Output:
Student(int r,String n,float f){   111 ankit
5000
rollno=r;  
112 sumit
name=n;  
6000
fee=f;  
}  
void display(){System.out.println(rollno+" "+name+" "+fee);}  
}  
class TestThis3{  
public static void main(String args[]){  
Student s1=new Student(111,"ankit",5000f);  
Student s2=new Student(112,"sumit",6000f);  
s1.display();  
s2.display();  }}  
THIS: TO INVOKE CURRENT
CLASS METHOD

You may invoke the method of the current class by using the this keyword.
If you don't use the this keyword, compiler automatically adds this keyword
while invoking the method.
EXAMPLE
EXAMPLE
class A
{  
void m()
{
System.out.println("hello m");
}  
void n()
Output:
hello n
{  
hello m
System.out.println("hello n");  
this.m();  
}  
}  
class TestThis4{  
public static void main(String args[]){  
A a=new A();  
a.n();  
}}  
THIS() : TO INVOKE CURRENT
CLASS CONSTRUCTOR

The this() constructor call can be used to invoke the current class constructor.
It is used to reuse the constructor. In other words, it is used for constructor
chaining.
CALLING DEFAULT CONSTRUCTOR
FROM PARAMETERIZED CONSTRUCTOR:
class A
{  
A() Default constructor
{
System.out.println("hello a");
}  
A(int x)
{  
this();  
System.out.println(x);  
}  
}   Output:
class TestThis5 hello a
{  
public static void main(String args[])
10
{  
A a=new A(10);  
}
}  
CALLING PARAMETERIZED CONSTRUCTOR
FROM DEFAULT CONSTRUCTOR:

class A{  
A()
{  
this(5);  
System.out.println("hello a");  
}   Parameterized
A(int x) constructor
{  
System.out.println(x);  
}  
}  
class TestThis6{  
public static void main(String args[]){  
A a=new A();  
}}   Output:
5
hello a
EXAMPLE
class Student
{  
int rollno;   class TestThis7{  
String name,course;   public static void main(String args[]){  
float fee;   Student s1=new Student(111,"ankit","java");  
Student(int rollno,String name,String course) Student s2=new Student(112,"sumit","java",6000f)
{  
this.rollno=rollno;  
;  
this.name=name;   s1.display();  
this.course=course;   s2.display();  
}   }
}  
Student(int rollno,String name,String course,float fee)
{   Output:
this(rollno,name,course);//reusing constructor   111 ankit java null
this.fee=fee;   112 sumit java 6000
}  
void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}  
}  
OBJECT ORIENTED PROGRAMMING

Lecture #21: “static” Keyword


“STATIC” KEYWORD

The static keyword in Java is used for memory


management mainly.
The static keyword belongs to the class than
an instance of the class.
The “static” Keyword can be applied to:
• Variable (also known as a instance variable)
• Block
• Method
• Nested class
TO VARIBALE

Java static variable:


If you declare any variable as static, it is known as a static variable.
The static variable can be used to refer to the common property of all objects
(which is not unique for each object)
for example: college name of students
The static variable gets memory only once in the class area at the time of class
loading
It makes your program memory efficient (i.e., it saves memory).

Syntax:
static
varibale_name=value;
TO VARIBALE

class Student{ If we make college filed static, this field will get the
int rollno; memory only once.
String name;
String college=“GVPCOE";
}

class Student{
Java static property is shared to all
int rollno;
objects.
String name;
static String college=“GVPCOE";
}
TO VARIBALE

class Student{
int rollno;
String name;
static String college ="GVPCOE";//static variable
Student(int r, String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
}
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"AKHILA");
Student s2 = new Student(222,"PRAGADA"); Output:
s1.display(); 111 AKHILA GVPCOE
s2.display(); 222 PRAGADA GVPCOE
}
}
TO VARIBALE

class Counter{
int count=0;//will get memory each time when the instance is created

Counter(){
count++;//incrementing value
System.out.println(count);
}

public static void main(String args[]){ Output:


//Creating objects 1
Counter c1=new Counter(); 1
Counter c2=new Counter(); 1
Counter c3=new Counter();
}
}
will get
memory only
once and retain TO VARIBALE
its value

class Counter2{
static int count=0;

Counter2(){
count++;//incrementing the value of static variable
System.out.println(count);
}

public static void main(String args[]){


//creating objects Output:
Counter2 c1=new Counter2(); 1
Counter2 c2=new Counter2(); 2
Counter2 c3=new Counter2(); 3
}
}
TO BLOCK

A static block is used for initializing static variables.


The static block is executed once when the first object of the class is created.

Syntax:
static
{
//code
}
TO BLOCK

class Example {
static int a;
static int b;

static {
a = 10;
b = 2 * a;
}

public static void main( String args[] )


{
Example e = new Example(); Output:
System.out.printf("a = %d\t b = %d ", e.a, e.b); a = 10 b = 20
}
}
OBJECT ORIENTED PROGRAMMING

Lecture #22: “static” Keyword(cont.)


“STATIC” KEYWORD

The static keyword in Java is used for memory


management mainly.
The static keyword belongs to the class than
an instance of the class.
The “static” Keyword can be applied to:
• Variable (also known as a instance variable)
• Block
• Method
• Nested class
TO METHOD

If you apply static keyword with any method, it is known as static method.

• A static method belongs to the class rather than the object of a class.
• A static method can be invoked without the need for creating an instance of
a class.
• A static method can access static data member and can change the value of
it.
class Student{
int rollno;
String name;
static String college = “GVP";
//static method to change the value of static variable
static void change(){
college = “GVPCOE";
}
TO METHOD

class Calculate{
static int cube(int x){
return x*x*x;
}

public static void main(String args[])


{
int result=Calculate.cube(5);
System.out.println(result);
} Output:
} 125
TO METHOD

Restrictions for the static method

• The static method can not use non static data member or call non-static
method directly.
• this and super cannot be used in static context.Java main method is static?
because the object is not
required to call a static method.
class A{
If it were a non-static method,
int a=40;//non static
JVM creates an object first then
call main() method that will
public static void main(String args[]){
lead the problem of extra
System.out.println(a);
memory allocation.
} Output:
} Compile Time Error
JAVA MAIN METHOD IS STATIC?

Java main() method is always static, so that compiler can call it without the
creation of an object or before the creation of an object of the class.
In any Java program, the main() method is the starting point from where
compiler starts program execution. So, the compiler needs to call the main()
method.
If the main() is allowed to be non-static, then while calling the main() method
JVM has to instantiate its class.
While instantiating it has to call the constructor of that class, There will be
ambiguity if the constructor of that class takes an argument.
Static method of a class can be called by using the class name only without
creating an object of a class.
The main() method in Java must be declared public, static and void. If any of
these are missing, the Java program will compile but a runtime error will be
thrown.
FINAL KEYWORD

The final keyword is a non access modifier used for classes , attributes and
methods, which makes them non changeable.
(impossible to inherit or override)
The final keyword is useful when you want a variable to always store the same
value like PI(3.14)
The final key word is a modifier.
FINAL KEYWORD

The final keyword in java is used to restrict the user. The java final keyword
can be used in many contexts.
1. Variable
2. Method
3. Class
It can be applied with the variables , a final variable that have no value it is
called blank final variable or uninitialized variable .
It can be initialized in the constructor only.
The blank final variable can be static also which will be initialized in the static
block only.
FINAL VARIABLE

If you make any variable as final, you cannot change the value of final
variable (it will be constant)
Ex: there is a final variable speed limit, we are going to change the value of
this variable.
But, it cannot be changed because final variable once assigned a value can
never be changed.
EXAMPLE

class Bike
{
final int speedlimit=90;
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
Bike obj= new Bike();
obj.run();
}
}
Output:
Compile time error
FINAL METHOD

class Bike
{
final void run()
{
System.out.println("running");
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely with 100 kmph");
}
public static void main(String args[])
{
Honda honda = new Honda();
honda.run();
}
}
}
Output: Compile time error
IS FINAL METHOD INHERITED?

Class Bike
{
final void run()
{
System.out.println(“running…”);
}
Class Honda2 extends Bike
{
public static void main(String args[])
{
New Honda2().run();
}
}
Output: running…
WHAT IS BLANK OR UNINITIALIZED
FINAL VARIABLE?

A final variable that is not initialized at the time of declaration is known as blank final
variable.
If you want to create a variable that is initialized at the time of creating object and
once initialized may not be changed, it is useful.
For example, PAN CARD number of an employee.
It can be initialized only in constructor.
Ex: class Student
{
int id;
String name;
final String PAN_CARD_NUMBER;
}
CAN WE INITIALIZE BLANK FINAL VARIABLE?

Yes, but only in constructors


class Bike10{
final int speedlimit;//blank final variable
Bike10(){
speedlimit=70;
System.out.println(speedlimit);
}
public static void main(String args[]){
new Bike10();
}
}
Output: 70
GARBAGE COLLECTION

Java garbage collection is the process by which Java programs perform


automatic memory management.
Java programs compile to bytecode that can be run on a Java Virtual Machine,
or JVM for short.
When Java programs run on the JVM, objects are created on the heap, which
is a portion of memory dedicated to the program.
Eventually, some objects will no longer be needed.
The garbage collector finds these unused objects and deletes them to free up
memory.
GARBAGE COLLECTION

In java, garbage means unreferenced objects.


Garbage Collection is process of reclaiming the runtime unused memory
automatically. In other words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++.
But, in java it is performed automatically. So, java provides better memory
management.
Advantage of Garbage Collection
It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
It is automatically done by the garbage collector(a part of JVM) so we don't
need to make extra efforts.
By nulling a 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 first object is referred by e1 is available for garbage collection
By anonymous object:
new Employee();
HOW IT WORKS?

Java garbage collection is an automatic process.


The programmer does not need to explicitly mark objects to be deleted.
The garbage collection implementation lives in the JVM.
Each JVM can implement garbage collection however it pleases; the only
requirement is that it meets the JVM specification.
Although there are many JVMs, Oracle’s HotSpot is by far the most common.
It offers a robust and mature set of garbage collection options.
While HotSpot has multiple garbage collectors that are optimized for various
use cases, all its garbage collectors follow the same basic process.
CONTD…

In the first step, unreferenced objects are identified and marked as ready for
garbage collection.
In the second step, marked objects are deleted.
Optionally, memory can be compacted after the garbage collector deletes
objects, so remaining objects are in a contiguous block at the start of the heap.
The compaction process makes it easier to allocate memory to new objects
sequentially after the block of memory allocated to existing objects.
All of HotSpot’s garbage collectors implement a generational garbage
collection strategy that categorizes objects by age.
The rationale behind generational garbage collection is that most objects are
short-lived and will be ready for garbage collection soon after creation.
FINALIZE() METHOD

The java.lang.Object.finalize() is called by the garbage collector on an object


when garbage collection determines that there are no more references to the
object. A subclass overrides the finalize method to dispose of system resources
or to perform other cleanup.
Declaration
Following is the declaration for java.lang.Object.finalize() method
protected void finalize()
Parameters
NA
Return Value
This method does not return a value.
Exception
Throwable − the Exception raised by this method
EXAMPLE

The following example shows the usage of lang.Object.finalize() method.


import java.util.*;
public class ObjectDemo extends GregorianCalendar {
public static void main(String[] args) {
try {
ObjectDemo cal = new ObjectDemo();
System.out.println("" + cal.getTime());
System.out.println("Finalizing...");
cal.finalize();
System.out.println("Finalized."); } Output:
catch (Throwable ex) { Sat Sep 22 00:27:21 EEST 2012
ex.printStackTrace(); } Finalizing...
Finalized.
}
}
OBJECT ORIENTED PROGRAMMING

Lecture #23: Inheritance-Introduction


INHERITANCE

Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another.
Reusability is achieved by INHERITANCE
Java classes Can be Reused by extending a class. Extending an existing class is
nothing but reusing properties of the existing classes.
The class whose properties are extended is known as super or base or parent
class.
The class which extends the properties of super class is known as sub or derived
or child class
A class can either extends another class or can implement an interface
DEFINING A SUBCLASS

Syntax :
class <subclass name> extends <superclass name>
{
variable declarations;
method declarations;
}

• extends keyword signifies that properties of the super class are


extended to sub class
• Sub class will not inherit private members of super class
INHERITANCE

class B extends A { ….. } A <<class>>

A super class
B sub class B <<class>>

A <<interface>>
class B implements A { ….. }
A interface
B <<class>>
B sub class
TYPES OF INHERITANCE

Single Inheritance Hierarchical Inheritance

A A X X

B B A B C A B C

NOT SUPPORTED BY JAVA


MultiLevel Inheritance Multiple Inheritance
SUPPORTED BY
A A A B JAVA
A B

B B

C C
C C
TYPES OF INHERITANCE

• Mulitiple Inheritance can be implemented by implementing


multiple interfaces not by extending multiple classes
Example :
class Z extends A implements C , D A C D
{ …………}

OK Z
class Z extends A ,B class Z extends A extends B
{ {

OR
} WRONG } WRONG
OBJECT ORIENTED PROGRAMMING

Lecture #24: Single Inheritance


INHERITANCE

Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another.
Reusability is achieved by INHERITANCE
Java classes Can be Reused by extending a class. Extending an existing class is
nothing but reusing properties of the existing classes.
The class whose properties are extended is known as super or base or parent
class.
The class which extends the properties of super class is known as sub or derived
or child class
A class can either extends another class or can implement an interface
TYPES OF INHERITANCE

Single Inheritance

A A

B B
SINGLE INHERITANCE

class A class Example


{ {
int i,j; public static void main(String args[])
void showij() {
{ A a = new A();
System.out.println(“i and j : “+i+j); B b = new B();
} a.i=10;
} a.j=20;
class B extends A System.out.println(“contents of a:”);
{ a.showij();
b.i=1;
Output:
int k;
b.j=2; 1
void showk()
{ b.k=3; 1
System.out.println(“k : “+k); 1 of b:”);
System.out.println(“contents
} b.showij();
void sum() b.showk();
{ System.out.println(“sum of i,j,k of b:”);
System.out.println(“i+j+k: “+(i+j+k)); b.sum();
} }
} }
OBJECT ORIENTED PROGRAMMING

Lecture #25: Multilevel Inheritance


INHERITANCE

Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another.
Reusability is achieved by INHERITANCE
Java classes Can be Reused by extending a class. Extending an existing class is
nothing but reusing properties of the existing classes.
The class whose properties are extended is known as super or base or parent
class.
The class which extends the properties of super class is known as sub or derived
or child class
A class can either extends another class or can implement an interface
TYPES OF INHERITANCE

MultiLevel Inheritance

A A

B B

C C
MULTI LVEL INHERITANCE
class C extends B
class A {
{ int k;
int i; void showk()
void showij() {
{ System.out.println(“k : “+k);
System.out.println(“i :”+i); }
} void sum()
} {
class B extends A System.out.println(“i+j+k: “+(i+j+k));
{ } Output:
int j; } 1
void showj() class Example
{ 1
{
System.out.println(“j : “+j); 1
public static void main(String args[]) {
} C c=new C();
} c.i=10;
c.j=20;
c.k=30;
c.sum()
}}
OBJECT ORIENTED PROGRAMMING

Lecture #26: Hierarchical Inheritance


INHERITANCE

Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another.
Reusability is achieved by INHERITANCE
Java classes Can be Reused by extending a class. Extending an existing class is
nothing but reusing properties of the existing classes.
The class whose properties are extended is known as super or base or parent
class.
The class which extends the properties of super class is known as sub or derived
or child class
A class can either extends another class or can implement an interface
TYPES OF INHERITANCE

Hierarchical Inheritance

X X

A B C A B C
HIERARCHICAL INHERITANCE

class A class C extends A{


{ int k;
int i; void showk()
void showij() {
{ System.out.println(“k : “+k);
System.out.println(“i :”+i); }
} void sum()
} {
class B extends A System.out.println(“i+k: “+(i+k));
{ } Output:
int j; } 1
void showj() class Example
{ 1
{
System.out.println(“j : “+j); 1
public static void main(String args[]) {
} C c=new C();
void sum() c.i=10;
{ c.k=30;
System.out.println(“i+j: “+(i+j)); c.sum()
} }}
}
OBJECT ORIENTED PROGRAMMING

Lecture #27: “super” keyword


SUPER KEYWORD

The super keyword in Java is used in subclasses to access superclass members


(attributes, constructors and methods).
Can be used to call super class constrctor
1. super()
2. super(<parameter-list>)
Can refer to super class instance variables/Methods
3. super . <super class instance variable/Method>
USE OF SUPER KEYWORD FOR
CONSTRUCTORS

Whenever a sub class object is created ,super class constructor is


called first.
If super class constructor does not have any constructor of its own OR
has an unparametrized constructor then it is automatically called by
Java Run Time by using call super()
If a super class has a parameterized constructor then it is the
responsibility of the sub class constructor to call the super class
constructor by call
super(<parameters required by super class>)
Call to super class constructor must be the first statement in sub class
constructor
1. WHEN SUPER CLASS HAS A
UNPARAMETRIZED CONSTRUCTOR
class A
{
A()
class inhtest
{ {
System.out.println("This is constructor public static void main(String args[]
of class A"); {
} B b1 = new B();
} // End of class A
class B extends A
}
{ }
B() Optional
{
super();
System.out.println("This is constructor of OUTPUT
class B”);} This is constructor of class A
} // End of class B
This is constructor of class B
class A
{ File Name is inherit1.java
A()
{
System.out.println("This is class A");
} Output:
} This is class A
class B extends A This is class B
{
B()
{
System.out.println("This is class B");
}
}
class inherit1
{
public static void main(String args[])
{
B b1 = new B();
}
} 1. When super class has a Unparametrized
constructor
1. When super class has a Unparametrized
class A constructor
{
private A()
{
System.out.println("This is class A");
}
}
class B extends A
{
B()
{
System.out.println("This is class B");
}
} Output:
class inherit2 Error: A() has private access in A
{
public static void main(String args[])
{
B b1 = new B();
}
}
class A
{
private A()
{
System.out.println("This is class A");
}
A()
{
System.out.println("This is class A");
}
} Output:
class B extends A A() is already defined in A
{ A() has private access in A
B()
{ 2 errors
System.out.println("This is class B");
}
}
class inherit2
{
public static void main(String args[])
{
B b1 = new B();
}} 1. When super class has a Unparametrized
2. When super class has a parametrized constructor

class A
{
int a;
A( int a1) B b1 = new B(10,8.6);
{
a =a1;
System.out.println("This is constructor of class A");
}
}
class B extends A
{
int b;
D:\java\bin>javac inhtest.java
double c;
B(int b1,double c1) inhtest.java:15: cannot find
{ symbol
b=b1; symbol : constructor A()
c=c1;
location: class A
System.out.println("This is constructor of class B");
} {
} ^
1 errors
2. When super class has a parametrized constructor
class A
{
int a;
A( int a1)
{
a =a1;
System.out.println("This is constructor
of class A");
}}
class B extends A
{ B b1 = new B(8,10,8.6);
int b;
double c;
B(int a2,int b1,double c1)
{
OUTPUT
super(a2); This is constructor of class A
b=b1; This is constructor of class B
c=c1;
System.out.println("This is constructor
of class B");
}}
OBJECT ORIENTED PROGRAMMING

Lecture #28: “super” keyword


SUPER KEYWORD

The super keyword in Java is used in subclasses to access superclass members


(attributes, constructors and methods).
Can be used to call super class constrctor
1. super()
2. super(<parameter-list>)
Can refer to super class instance variables/Methods
3. super . <super class instance variable/Method>
3. Refer to super class instance variables/Methods

class A class B extends A


{ {
int a; int b;
A( int a) double c;
{ B(int a,int b,double c)
this.a =a; {
System.out.println("This is constructor of super(a);
class A"); this.b=b;
} this.c=c;
void print() System.out.println("This is constructor of
{ class B");
System.out.println("a="+a); }
} void show()
void display() {
{ print();
System.out.println("hello This is Display in System.out.println("b="+b);
A"); System.out.println("c="+c);
} }
} // End of class A } // End of class B
3. Refer to super class instance variables/Methods

class inhtest1
{
public static void main(String args[])
{
B b1 = new B(10,8,4.5);
b1.show();
}
}

OutPut
D:\java\bin>java inhtest1
This is constructor of class A
This is constructor of class B
a=10
b=8
c=4.5
3. Refer to super class instance variables/Methods
class A class B extends A
{ {
int a; int b;
A( int a) private double c;
{ B(int a,int b,double c)
this.a =a; {
System.out.println("This is constructor of super(a);
class A"); this.b=b;
} this.c=c;
void show() System.out.println("This is constructor of
{ class B");
System.out.println("a="+a); }
} void show()
void display() {
{ super.show();
System.out.println("hello This is Display in System.out.println("b="+b);
A"); System.out.println("c="+c);
} display();
} }
}
3. Refer to super class instance variables/Methods

class inhtest1
{
public static void main(String args[])
{
B b1 = new B(10,8,4.5);
b1.show();
}
}
/* OutPut
D:\java\bin>java inhtest1
This is constructor of class A
This is constructor of class B
a=10
b=8
c=4.5
hello This is Display in A
*/
class A class B extends A
class inhtest2
{ {
int b; {
int a; public static void main(String
A( int a) double c;
{ B(int a,int b,double c)
this.a =a; { args[])
} super(a); {
void show() this.b=b; B b1 = new B(10,20,8.4);
{ this.c=c; b1.show();
System.out.println("a="+a); } }
} void show()
}
void display() {
{ //super.show();
System.out.println("hello This is System.out.println("a="+a);
System.out.println("b="+b);
Display in A");System.out.println("c="+c);
} }
} }
D:\java\bin>java inhtest2
a=10
b=20
c=8.4
3. Refer to super class instance variables/Methods
class B extends A
class A {
{ // super class variable a hides here
int a; int a; class inhtest2
A( int a) int b; {
{ double c;
public static void main(String args[])
this.a =a; B(int a,int b,double c)
} {
{
} super(100); B b1 = new B(10,20,8.4);
this.a = a; b1.show();
this.b=b; }
this.c=c; }
}
void show()
{
System.out.println("Super class a="+super.a);
System.out.println("a="+a);
System.out.println("b="+b); Out Put
System.out.println("c="+c); D:\java\bin>java inhtest2
} Super class a=100
} a=10
b=20
c=8.4
3. Refer to super class instance variables/Methods
OBJECT ORIENTED PROGRAMMING

Lecture #29: Method Overriding


METHOD OVERRIDING

If subclass (child class) has the same method as declared in the parent class, it
is known as method overriding in Java.

Uses:
• Method overriding is used to provide the specific implementation of a
method which is already provided by its superclass.
• Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


• The method must have the same name as in the parent class
• The method must have the same parameter as in the parent class.
METHOD OVERRIDING

class Vehicle class Vehicle


{ {
void run() void run()
{ {
System.out.println("Vehicle is running"); System.out.println("Vehicle is running");
} }
} }
class Bike extends Vehicle
class Bike extends Vehicle
{
{
public static void main(String args[])
public static void main(String args[])
{
{
Bike obj = new Bike();
Bike obj = new Bike();
obj.run();
obj.run();
}
}
}
void run()
{
Output: Output: System.out.println("Bike is running safely");
Vehicle is running Bike is running }
safely }
METHOD OVERRIDING

class Vehicle class Vehicle


{ {
void run() void run()
{ {
System.out.println("Vehicle is running"); System.out.println("Vehicle is running");
} }
} }
class Bike extends Vehicle
class Bike extends Vehicle
{
{
public static void main(String args[])
public static void main(String args[])
{
{
Bike obj = new Bike();
Bike obj = new Bike();
obj.run();
obj.run();
}
}
void run()
}
{
Output: super.run();
Output: Vehicle is running System.out.println("Bike is running safely");
Vehicle is running Bike is running }
}
safely
METHOD OVERRIDING
REALTIME EXAMPLE

le
Examp
METHOD OVERRIDING

Note:
A method declared as static method cannot be overridden
Main method cannot be overridden
A method declared final cannot be overridden.
Constructors cannot be overridden.
METHOD OVERLOADING
VS
METHOD OVERRIDING
OBJECT ORIENTED PROGRAMMING

Lecture #30: Dynamic Method Dispatch


DYNAMIC METHOD DISPATCH

Dynamic method dispatch is a mechanism by which a call to an


overridden method is resolved at runtime.
This is how java implements runtime polymorphism.
When an overridden method is called by a reference, java determines
which version of that method to execute based on the type of object it
refer to.
In simple words the type of object which it referred determines which
version of overridden method will be called.
UPCASTING IN JAVA

When Parent class reference variable refers to Child class object, it is


known as Upcasting.
In Java this can be done and is helpful in scenarios where multiple
child classes extends one parent class.
In those cases we can create a parent class reference and assign child
class objects to it.
Example:
Notice the last output. This is because of the statement, gm = ck;. Now
gm.type() will call the Cricket class version of type() method. Because here
gm refers to the cricket object.
EXAMPLE
EXAMPLE

class Game{
public void type(){
System.out.println("Indoor & outdoor"); }
}
Class Cricket extends Game
{
public void type(){
System.out.println("outdoor game");
}
public static void main(String[] args){
Game gm = new Game(); Output:
Cricket ck = new Cricket(); Indoor & outdoor
gm.type(); Outdoor game
ck.type(); Outdoor game
gm = ck;//gm refers to Cricket object
gm.type(); //calls Cricket's version of type}
}
DIFFERENCE BETWEEN STATIC BINDING AND
DYNAMIC BINDING IN JAVA?

Static binding in Java occurs during compile time while dynamic


binding occurs during runtime. Static binding uses type(Class)
information for binding while dynamic binding uses instance of
class(Object) to resolve calling of method at run-time. Overloaded
methods are bonded using static binding while overridden methods are
bonded using dynamic binding at runtime.
In simpler terms, Static binding means when the type of object which is
invoking the method is determined at compile time by the compiler.
While Dynamic binding means when the type of object which is
invoking the method is determined at run time by the compiler.
OBJECT ORIENTED PROGRAMMING

Lecture #31: “final” keyword


“FINAL” KEYWORD

The final keyword in java is used to


restrict the user

final can be:


variable
method
class
JAVA FINAL VARIABLE

If you make any variable as final, you cannot change the value of final
variable(It will be constant).
class Bike
{
class FinalVariable final int speedlimit=90;//final variable
{ void run()
final int var = 50; {
var = 60 // error speedlimit=400; // error
} }
public static void main(String args[])
{
Bike obj=new Bike();
m pi l e - time
co obj.run();
errors }
}//end of class
JAVA FINAL METHOD

class Bike
{
final void run()
If you make any method {
as final, you cannot System.out.println("running");
override it. }
}
class Honda extends Bike
{
void run()
{System.out.println("running safely with
pi l e -time
co m 100kmph");}
errors public static void main(String args[])
{
Honda honda= new Honda();
honda.run();
}
}
JAVA FINAL CLASS

final class Bike


If you make any class as final, {
you cannot extend it. ....
}

class Honda1 extends Bike


{
void run()
{
System.out.println("running safely with
pi l e-t im e 100kmph");
c om }
errors
public static void main(String args[])
{
Honda1 honda= new Honda1();
honda.run();
}
}
“FINAL” KEYWORD

uninitialized final variable:


A final variable that is not initialized at the time of declaration is known as
blank final variable. class Bike{
It can be initialized only in constructor. final int speedlimit;//blank final
variable
Ex: PANCARD NUMBER
Bike()
{
speedlimit=70;
System.out.println(speedlimit);
}

public static void main(String args[])


{
Bike b1=new Bike();
}
}
“FINAL” KEYWORD

static blank final variable


A static final variable that is not initialized at the time of declaration is known
as static blank final variable.
It can be initialized only in static block.
class A
{
static final int data;//static blank final variable
static
{
data=50;
}
public static void main(String args[])
{
System.out.println(A.data);
}
}
“FINAL” KEYWORD

final parameter
class Bike
If you declare any parameter {
as final, you cannot change int cube(final int n)
the value of it. {
n=n+2;//can't be changed as n is final
n*n*n;
}
public static void main(String args[])
{
-time
compile Bike b=new Bike();
errors b.cube(5);
}
}
“FINAL” KEYWORD
OBJECT ORIENTED PROGRAMMING

Lecture #32: Abstract class


ABSTRACTION

Abstraction is a process of hiding the implementation details and showing


only functionality to the user.

There are two ways to achieve abstraction in java


• Abstract class
• Interface
ABSTRACT CLASS

A class which contains the abstract keyword in its declaration is known as


abstract class.
ABSTRACT CLASS

An abstract class can have both abstract and regular methods


The abstract keyword is a non-access modifier, used for classes and methods:

Abstract class: is a restricted class that cannot be used to create objects (to
access it, it must be inherited from another class).
Syntax:
abstract class_name{ }
no method
Abstract method: can only be used in an abstract class, and it does not have a
body
body. The body is provided by the subclass (inherited from).

Syntax:
abstract type
method_name(paramenter_list);
abstract class Figure class Rectangle extends Figure
{ {
int dim1,dim2; Rectangle(int a, int b)
Figure(int d1, int d2) {
{ super(a,b);
dim1=d1; }
dim2=d2;
} void area() //overriding abstract method
void display() {
{ System.out.println(dim1*dim2);
System.out.println(“Area is: “); }
} }

abstract void area(); //abstract method class Example32{


} public static void main(String
args[])
n a b stract {
b c l a ss of a
er
Any su ss must eith e Rectangle r=new rectangle(10,20);
cla t al l o f th Figure f;
en er
implem thods of sup f=r;
b st r a ct me
l a re d itself f.display();
a b e dec
s o r f.area();
clas aabstra
ct
}
}
OBJECT ORIENTED PROGRAMMING

Lecture #33: Interface


ABSTRACTION

Abstraction is a process of hiding the implementation details and showing


only functionality to the user.

There are two ways to achieve abstraction in java


• Abstract class
• Interface
INTERFACE

An interface is a fully abstract class. It includes a group of abstract methods


(methods without a body).
We use the “interface” keyword to create an interface in Java
Uses:
• It is used to achieve abstraction.
• By interface, we can support the functionality of multiple inheritance.
Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}
INTERFACE

Implementing an Interface
• Like abstract classes, we cannot create objects of interfaces.
• To use an interface, other classes must implement it. We use the “implements” keyword
to implement an interface.

Note:
• It is similar to class. It is a collection of abstract methods.
• Method bodies exist only for default methods and static methods.
• An interface may also contain constants, default methods, static methods, and nested types.
• all the methods of the interface need to be defined in the class.
• cannot instantiate an interface.
• does not contain any constructors.
interface Polygon
{
void getArea(int length, int
breadth);
}
class Rectangle implements Polygon
{
public void getArea(int length, int breadth)
{
System.out.println("The area of the rectangle is " + (length *
breadth));
}
}
class Example{
public static void main(String[]
args) {
e m e n ts an Rectangle r1 = new Rectangle();
t h at i m pl ment r1.getArea(5, 6);
c l a s s i m p l e
A ust
t e rf a c e m
e cl a r ed in }
in h ods d }
e m e t e .
al l t h erfa c
the int
INTERFACE

The relationship between classes and interfaces


INTERFACE

Multiple inheritance in Java by interface


if any class
implement
Polygon, it s
INTERFACE provide im sh ould
plementati
for all the ons
abstract
methods of
both Line
Implementing Multiple Interfaces Extending an Interface
and Polygon
.

interface A {
interface Line {
// members of A
// members of Line interface
}
}
interface B {
// extending interface
// members of B
interface Polygon extends Line {
}
// members of Polygon interface
// members of Line interface
class C implements A, B {
}
// abstract members of A
// abstract members of B
}
OBJECT ORIENTED PROGRAMMING

Lecture #35: Packages


PACKAGES

A Package can be defined as a grouping of related types (classes, interfaces,


enumerations and annotations)
Packages are used for:
• Preventing naming conflicts.
• Making searching/locating and usage of classes, interfaces, enumerations
easier
• Providing controlled access
• Packages can be considered as data encapsulation (or data-hiding).
Package na
me s
and directo
ry
structure a
re
closely rela
ted.
PACKAGES
BUILT-IN PACKAGES

These packages consist of a large number of classes which are a part of Java API.
• java.lang: Contains language support classes(e.g classed which defines
primitive data types, math operations). This package is automatically imported.
• java.io: Contains classed for supporting input / output operations.
• java.util: Contains utility classes which implement data structures like Linked
List, Dictionary and support ; for Date / Time operations.
• java.applet: Contains classes for creating Applets.
• java.awt: Contain classes for implementing the components for graphical user
interfaces (like button , ;menus etc).
• java.net: Contain classes for supporting networking operations.
It is a good practice to use
names of packages with
USER-DEFINED PACKAGESlower case letters to avoid
any conflicts with the
names of classes and
interfaces.
These are the packages that are defined by the user.
Creating a Package:
• choose a name for the package
• include a “package” statement along with that name
• The package statement should be the first line in the source file.
• There can be only one package statement in each source file

Example:
Syntax: package mypack;
package package_name; public class Simple{
public static void main(String args[]){
System.out.println("Welcome to
package");
}
USER-DEFINED PACKAGES

compile java package

Syntax: Example:
javac -d directory javac -d .
javafilename Simple.java

run java package program The -d switch specifies


You need to use fully qualified name the destination where
to put the generated
class file.
Example:
java
mypack.Simple
ACCESS PACKAGE FROM
ANOTHER PACKAGE

three ways to access


1. import package.*;
2. import package.classname;
3. fully qualified name.
ACCESS PACKAGE FROM
ANOTHER PACKAGE

import package.*;
• “import” keyword is used to make the classes and interface of another
package accessible to the current package.
• All the classes and interfaces of this package will be accessible but not
subpackages.
save as:
package pack;
A.java
public class A{
public void msg()
{System.out.println("Hello");}
}
package mypack; save as:
B.java
import pack.*;

class B{
public static void main(String args[])
{
A obj = new A();
obj.msg(); Output:
} javac -d . A.java
} javac -d . B.java
java mypack.B
Hello
ACCESS PACKAGE FROM
ANOTHER PACKAGE

import package.classname;
• “import” keyword is used to make the classes and interface of another
package accessible to the current package.
• only declared class of this package will be accessible.
save as:
package pack;
A.java
public class A{
public void msg()
{System.out.println("Hello");}
}
package mypack; save as:
B.java
import pack.A;

class B{
public static void main(String args[])
{
A obj = new A();
obj.msg(); Output:
} javac -d . A.java
} javac -d . B.java
java mypack.B
Hello
ACCESS PACKAGE FROM
ANOTHER PACKAGE

fully qualified name.


• Now there is no need to import.
• But you need to use fully qualified name every time when you are
accessing the class or interface.
• only declared class of this package will be accessible.
save as:
package pack;
A.java
public class A{
public void msg()
{System.out.println("Hello");}
}
package mypack;
save as:
B.java
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully qualified
name
obj.msg();
} Output:
} javac -d . A.java
javac -d . B.java
java mypack.B
Hello
ACCESS SPECIFIERS

• Specifies the accessibility or scope of a field, method, constructor, or class.


• We can change the access level of fields, constructors, methods, and class
by applying the access modifier on it.
• By controlling access, you can prevent misuse.

There are four types of Java access modifiers:


1. Default
2. public
3. private
4. protected
ACCESS SPECIFIERS
WRAPPER CLASSES IN JAVA

The wrapper class in Java provides the mechanism to convert primitive into


object and object into primitive.
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into
objects and objects into primitives automatically.
The automatic conversion of primitive into an object is known as autoboxing
and vice-versa unboxing.
Java is an object-oriented programming language, so we need to deal with
objects many times like in Collections, Serialization, Synchronization, etc. Let
us see the different scenarios, where we need to use the wrapper classes.
USES OF WRAPPER CLASSES

•Change the value in Method: Java supports only call by value. So, if we pass
a primitive value, it will not change the original value. But, if we convert the
primitive value in an object, it will change the original value.
•Serialization: We need to convert the objects into streams to perform the
serialization. If we have a primitive value, we can convert it in objects through
the wrapper classes.
•Synchronization: Java synchronization works with objects in Multithreading.
•java.util package: The java.util package provides the utility classes to deal
with objects.
•Collection Framework: Java collection framework works with objects only.
All classes of the collection framework (ArrayList, LinkedList, Vector,
HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with
objects only.
AUTOBOXING

The automatic conversion of primitive data type into its corresponding wrapper class is known
as autoboxing, for example, byte to Byte, char to Character, int to Integer, long to Long, float to
Float, boolean to Boolean, double to Double, and short to Short.
Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the
primitive into objects.
class WrapperExample{
public static void main(String args[]){
int a=20;
Integer i=Integer.valueOf(a);
//converting int into Integer explicitly
Integer j=a;
//autoboxing, now compiler will write Integer.valueOf(a) internally

System.out.println(a+" "+i+" "+j);


}} Output: 20 20 20
UNBOXING

The automatic conversion of wrapper type into its corresponding primitive type
is known as unboxing. It is the reverse process of autoboxing. Since Java 5, we
do not need to use the intValue() method of wrapper classes to convert the
wrapper type into primitives.
class WrapperExample{
public static void main(String args[]){
Integer a= new Integer(3);
int i=a.intValue();
//converting Integer to int explicitly
int j=a;
//unboxing, now compiler will write a.intValue() internally
System.out.println(a+" "+i+" "+j);
}} output: 3 3 3
CUSTOM WRAPPER CLASSES

Java Wrapper classes wrap the primitive data types, that is why it is known as
wrapper classes. We can also create a class which wraps a primitive data type.
So, we can create a custom wrapper class in Java.
MATH CLASS

Java Math class provides several methods to work on math calculations like
min(), max(), avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.
Unlike some of the StrictMath class numeric methods, all implementations of
the equivalent function of Math class can't define to return the bit-for-bit same
results. This relaxation permits implementation with better-performance where
strict reproducibility is not required.
If the size is int or long and the results overflow the range of value, the
methods addExact(), subtractExact(), multiplyExact(), and toIntExact() throw
an ArithmeticException.
For other arithmetic operations like increment, decrement, divide, absolute
value, and negation overflow occur only with a specific minimum or
maximum value. It should be checked against the maximum and minimum
value as appropriate.
OBJECT ORIENTED PROGRAMMING

Lecture #34: Object class


OBJECT CLASS

The Object class is the parent class of all the classes in java by default
Object class is present in java.lang package
If a Class does not extend any other class then it is direct child class of Object
and if extends other class then it is an indirectly derived
The Object class provides some common behaviors to all the objects such as
object can be compared, object can be cloned, object can be notified etc.

String toString() Object clone() void wait()


boolean equals(Object void finalize() void notify()
obj) class void
int hashCode() getclasss() notifyAll()
EQUALS

It is used to compare the two objects dynamically.

Syntax:
public boolean equals(Object
obj)

This method returns true if this object is the same as the obj argument; false
otherwise.
OBJECT CLONING

The object cloning is a way to create exact copy of an object.


The clone() method of Object class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class whose
object clone we want to create

Syntax:
protected Object clone() throws CloneNotSupportedException

Advantages:
• easy way of copying objects
• don't need to write lengthy and repetitive codes.
class Student implements Cloneable{
int rollno;
String name;

Student(int rollno,String name){


this.rollno=rollno;
this.name=name;
} Output:
public Object clone()throws 101 amit
CloneNotSupportedException{ 101 amit
return super.clone();
}
public static void main(String args[]){
try{
Student s1=new Student(101,"amit");

Student s2=(Student)s1.clone();

System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);

}
catch(CloneNotSupportedException c){}
}
REFLECTION

Reflection is an API which is used to examine or modify the behavior of


methods, classes, interfaces at runtime.
There is a class in Java named “Class” that keeps all the information about
objects and classes at runtime.
The object of “Class” can be used to perform reflection.

Steps:
• create an object of Class.
• using the object we can call various methods to get information about
methods, fields, and constructors present in a class.
REFLECTION

Reflection can be used to get information about –

Class The getClass() method is used to get the name of the class to which an
object belongs.
Constructors The getConstructors() method is used to get the public
constructors of the class to which an object belongs.
Methods The getMethods() method is used to get the public methods of the
class to which an objects belongs.
import java.lang.reflect.Method; System.out.println("The name of
import java.lang.reflect.Field; constructor is " + constructor.getName());
import java.lang.reflect.Constructor; System.out.println("The public methods
class Test of class are : ");
{ Method[] methods = cls.getMethods();
private String s; System.out.println(method.getName());
public Test() { s = “Java }
Programming"; } }
public void method1() {
System.out.println("The string is " + s);
}
}
Outpt:
class Demo The name of class is Test
{ The name of constructor is Test
public static void main(String args[]) throws The public methods of class
Exception are :
{ method1
Test obj = new Test();
Class cls = obj.getClass();
System.out.println("The name of class is " +
cls.getName());
Constructor constructor = cls.getConstructor();
RUNTIME JAVA CLASSES

Java Runtime class is used to interact with java runtime environment. Java


Runtime class provides methods to execute a process, invoke GC, get total and
free memory etc. There is only one instance of java.lang.Runtime class is
available for one java application.
The Runtime.getRuntime() method returns the singleton instance of Runtime
class.
COLLECTIONS IN JAVA

The Collection in Java is a framework that provides an architecture to store


and manipulate the group of objects.
Java Collections can achieve all the operations that you perform on a data
such as searching, sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework
provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
What is Collection in Java
A Collection represents a single unit of objects, i.e., a group.
FRAMEWORK IN JAVA

What is a framework in Java


• It provides readymade architecture.
• It represents a set of classes and interfaces.
• It is optional.
What is Collection framework
The Collection framework represents a unified architecture for storing and
manipulating a group of objects. It has:
1.Interfaces and its implementations, i.e., classes
2.Algorithm
HIERARCHY OF COLLECTION FRAMEWORK
COLLECTION INTERFACE

The Collection interface is the interface which is implemented by all the


classes in the collection framework.
It declares the methods that every collection will have.
In other words, we can say that the Collection interface builds the foundation
on which the collection framework depends.
Some of the methods of Collection interface are Boolean add ( Object obj),
Boolean addAll ( Collection c), void clear(), etc. which are implemented by all
the subclasses of Collection interface.
LIST INTERFACE

List interface is the child interface of Collection interface. It inhibits a list type data
structure in which we can store the ordered collection of objects. It can have
duplicate values.
List interface is implemented by the classes ArrayList, LinkedList, Vector, and
Stack.
To instantiate the List interface, we must use :
1.List <data-type> list1= new ArrayList();  
2.List <data-type> list2 = new LinkedList();  
3.List <data-type> list3 = new Vector();  
4.List <data-type> list4 = new Stack();  
There are various methods in List interface that can be used to insert, delete, and
access the elements from the list.
ARRAYLIST

The ArrayList class implements the List interface. It uses a dynamic array to store the duplicate element of
different data types. The ArrayList class maintains the insertion order and is non-synchronized. The
elements stored in the ArrayList class can be randomly accessed. Consider the following example.
import java.util.*;  
class TestJavaCollection1{  
public static void main(String args[]){  
ArrayList<String> list=new ArrayList<String>();//Creating arraylist  
list.add(“akhila");//Adding object in arraylist  
list.add(“rajesh");  
list.add(“asha");  
list.add(“mouli");  
//Traversing list through Iterator  
Iterator itr=list.iterator();  
while(itr.hasNext()){  
System.out.println(itr.next());  }  }  }  
Output: akhila rajesh asha mouli
ARRAY LIST

Java ArrayList class uses a dynamic array for storing the elements.


It is like an array, but there is no size limit.
We can add or remove elements anytime.
So, it is much more flexible than the traditional array.
It is found in the java.util package.
It is like the Vector in C++.
The ArrayList in Java can have the duplicate elements also.
It implements the List interface so we can use all the methods of List interface
here.
The ArrayList maintains the insertion order internally.
It inherits the AbstractList class and implements List interface.
ARRAY LIST

The important points about Java ArrayList class are:


•Java ArrayList class can contain duplicate elements.
•Java ArrayList class maintains insertion order.
•Java ArrayList class is non synchronized.
•Java ArrayList allows random access because array works at the index basis.
•In ArrayList, manipulation is little bit slower than the LinkedList in Java
because a lot of shifting needs to occur if any element is removed from the
array list.
HIERARCHY OF ARRAYLIST CLASS

As shown in the above diagram, Java ArrayList class extends


AbstractList class which implements List interface. The List
interface extends the Collection and Iterable interfaces in
hierarchical order.
ArrayList class declaration
Let's see the declaration for java.util.ArrayList class.
public class ArrayList<E> extends AbstractList<E> implement
s List<E>, RandomAccess, Cloneable, Serializable  
LINKEDLIST

LinkedList implements the Collection interface. It uses a doubly linked list internally to store
the elements. It can store the duplicate elements. It maintains the insertion order and is not
synchronized. In LinkedList, the manipulation is fast because no shifting is required.
Consider the following example.
import java.util.*;  
public class TestJavaCollection2{  
public static void main(String args[]){  
LinkedList<String> al=new LinkedList<String>();  
al.add(“Akhila");  
al.add(“Rajesh");  
al.add(“Asha");  
al.add(“Mouli");  
Iterator<String> itr=al.iterator();  
while(itr.hasNext()){  
System.out.println(itr.next());  }  }  }  
Output: Akhila Rajesh Asha Mouli
VECTOR

Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However,
It is synchronized and contains many methods that are not the part of Collection
framework.
Consider the following example.
import java.util.*;  
public class TestJavaCollection3{  
public static void main(String args[]){  
Vector<String> v=new Vector<String>();  
v.add("Ayush");  
v.add("Amit");  
v.add("Ashish");  
v.add("Garima");  
Iterator<String> itr=v.iterator();  
while(itr.hasNext()){  
System.out.println(itr.next());  }  }  }  
STACK

The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e., Stack. The
stack contains all of the methods of Vector class and also provides its methods like boolean push(),
boolean peek(), boolean push(object o), which defines its properties.
Consider the following example.
import java.util.*;  
public class TestJavaCollection4{  
public static void main(String args[]){  
Stack<String> stack = new Stack<String>();  
stack.push("Ayush");  
stack.push("Garvit");  
stack.push("Amit");  
stack.push("Ashish");  
stack.push("Garima");  
stack.pop();  
Iterator<String> itr=stack.iterator();  
while(itr.hasNext()){  
System.out.println(itr.next());  }  }  }  
SET INTERFACE

Set Interface in Java is present in java.util package. It extends the Collection


interface. It represents the unordered set of elements which doesn't allow us to
store the duplicate items. We can store at most one null value in Set. Set is
implemented by HashSet, LinkedHashSet, and TreeSet.
Set can be instantiated as:
1.Set<data-type> s1 = new HashSet<data-type>();  
2.Set<data-type> s2 = new LinkedHashSet<data-type>();  
3.Set<data-type> s3 = new TreeSet<data-type>();  
HASH SET

HashSet class implements Set Interface. It represents the collection that uses a hash table for storage.
Hashing is used to store the elements in the HashSet. It contains unique items.
Consider the following example.
import java.util.*;  
public class TestJavaCollection7{  
public static void main(String args[]){  
//Creating HashSet and adding elements  
HashSet<String> set=new HashSet<String>();  
set.add("Ravi");  
set.add("Vijay");  
set.add("Ravi");  
set.add("Ajay");  
//Traversing elements  
Iterator<String> itr=set.iterator();  
while(itr.hasNext()){  
System.out.println(itr.next());  }  }  }  
HASH SET

Java HashSet class is used to create a collection that uses a hash table for
storage. It inherits the AbstractSet class and implements Set interface.
The important points about Java HashSet class are:
•HashSet stores the elements by using a mechanism called hashing.
•HashSet contains unique elements only.
•HashSet allows null value.
•HashSet class is non synchronized.
•HashSet doesn't maintain the insertion order. Here, elements are inserted on the
basis of their hashcode.
•HashSet is the best approach for search operations.
•The initial default capacity of HashSet is 16, and the load factor is 0.75.
Difference between List and Set
A list can contain duplicate elements whereas Set contains unique elements only.
HIERARCHY OF HASHSET CLASS

The HashSet class extends AbstractSet class which implements


Set interface. The Set interface inherits Collection and Iterable
interfaces in hierarchical order.
HashSet class declaration
Let's see the declaration for java.util.HashSet class.
public class HashSet<E> extends AbstractSet<E> implements
 Set<E>, Cloneable, Serializable  
METHODS IN JAVA
LINKED HASH SET

LinkedHashSet class represents the LinkedList implementation of Set Interface. It


extends the HashSet class and implements Set interface. Like HashSet, It also contains
unique elements. It maintains the insertion order and permits null elements.
Consider the following example.
import java.util.*;  
public class TestJavaCollection8{  
public static void main(String args[]){  
LinkedHashSet<String> set=new LinkedHashSet<String>();  
set.add("Ravi");  
set.add("Vijay");  
set.add("Ravi");  
set.add("Ajay");  
Iterator<String> itr=set.iterator();  
while(itr.hasNext()){  
System.out.println(itr.next());  }  }  }  
TREE SET

Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet, TreeSet
also contains unique elements. However, the access and retrieval time of TreeSet is quite fast. The
elements in TreeSet stored in ascending order.
import java.util.*;  
public class TestJavaCollection9{  
public static void main(String args[]){  
//Creating and adding elements  
TreeSet<String> set=new TreeSet<String>();  
set.add("Ravi");  
set.add("Vijay");  
set.add("Ravi");  
set.add("Ajay");  
//traversing elements  
Iterator<String> itr=set.iterator();  
while(itr.hasNext()){  
System.out.println(itr.next()); }  }  }  
HASH MAP

Java HashMap class implements the Map interface which allows us to store


key and value pair, where keys should be unique.
If you try to insert the duplicate key, it will replace the element of the
corresponding key.
It is easy to perform operations using the key index like updation, deletion,
etc. HashMap class is found in the java.util package.
HashMap in Java is like the legacy Hashtable class, but it is not synchronized.
It allows us to store the null elements as well, but there should be only one
null key.
Since Java 5, it is denoted as HashMap<K,V>, where K stands for key and V
for value. It inherits the AbstractMap class and implements the Map interface.
HASH MAP

•Java HashMap contains values based on the key.


•Java HashMap contains only unique keys.
•Java HashMap may have one null key and multiple null
values.
•Java HashMap is non synchronized.
•Java HashMap maintains no order.
•The initial default capacity of Java HashMap class is 16 with
a load factor of 0.75.
Hierarchy of HashMap class
As shown in the above figure, HashMap class extends
AbstractMap class and implements Map interface.
HASH MAP DECLARATION

Let's see the declaration for java.util.HashMap class.


public class HashMap<K,V> extends AbstractMap<K,V> implements Map<
K,V>, Cloneable, Serializable  
HashMap class Parameters
Let's see the Parameters for java.util.HashMap class.
•K: It is the type of keys maintained by this map.
•V: It is the type of mapped values.
EXAMPLE

import java.util.*;  
public class HashMapExample1{  
 public static void main(String args[]){  
HashMap<Integer,String> map=new HashMap<Integer,String>();
//Creating HashMap    
 map.put(1,"Mango");  //Put elements in Map  
 map.put(2,"Apple");    
map.put(3,"Banana");   
 map.put(4,"Grapes");   
 System.out.println("Iterating Hashmap...");  
 for(Map.Entry m : map.entrySet()){    
 System.out.println(m.getKey()+" "+m.getValue());    }  }  }  
Output: Iterating Hashmap…
1. Mango 2. Apple 3. Banana 4. Grapes
In this example, we are storing Integer as the key and String as the value, so we are
using HashMap<Integer,String> as the type. The put() method inserts the elements in the map.
To get the key and value elements, we should call the getKey() and getValue() methods.
The Map.Entry interface contains the getKey() and getValue() methods. But, we should call the entrySet()
method of Map interface to get the instance of Map.Entry.
STRING TOKENIZER

The java.util.StringTokenizer class allows you to break a string into tokens.


It is simple way to break string.
It doesn't provide the facility to differentiate numbers, quoted strings,
identifiers etc. like StreamTokenizer class. We will discuss about the
StreamTokenizer class in I/O chapter.
Constructors of StringTokenizer class
There are 3 constructors defined in the StringTokenizer class.
EXAMPLE

Let's see the simple example of StringTokenizer class that tokenizes a string
"my name is khan" on the basis of whitespace.
import java.util.StringTokenizer;  
public class Simple{  
 public static void main(String args[]){  
   StringTokenizer st = new StringTokenizer("my name is khan"," ");  
     while (st.hasMoreTokens()) {  
        System.out.println(st.nextToken());  }  }  }  
Output: my
name
is
khan
NEXTTOKEN(STRING DELIM) METHOD
OF STRINGTOKENIZER CLASS

StringTokenizer class is deprecated now. It is recommended to use


split() method of String class or regex (Regular Expression).
import java.util.*;  
public class Test {  
   public static void main(String[] args) {  
       StringTokenizer st = new StringTokenizer("my,name,is,khan");  
      // printing next token  
      System.out.println("Next token is : " + st.nextToken(","));    }      }  
Output: Next token is : my
CALENDER CLASS

Java Calendar class is an abstract class that provides methods for converting
date between a specific instant in time and a set of calendar fields such as
MONTH, YEAR, HOUR, etc. It inherits Object class and implements the
Comparable interface.
Java Calendar class declaration
Let's see the declaration of java.util.Calendar class.
public abstract class Calendar extends Object   
implements Serializable, Cloneable, Comparable<Calendar>  
EXAMPLE

import java.util.Calendar;  
public class CalendarExample1 {  
   public static void main(String[] args) {  
   Calendar calendar = Calendar.getInstance();  
   System.out.println("The current date is : " + calendar.getTime());  
   calendar.add(Calendar.DATE, -15);  
   System.out.println("15 days ago: " + calendar.getTime());  
   calendar.add(Calendar.MONTH, 4);  
   System.out.println("4 months later: " + calendar.getTime());  
   calendar.add(Calendar.YEAR, 2);  
   System.out.println("2 years later: " + calendar.getTime());   }  } 
Output:
The current date is : Thu Jan 19 18:47:02 IST 2017
15 days ago: Wed Jan 04 18:47:02 IST 2017
4 months later: Thu May 04 18:47:02 IST 2017
2 years later: Sat May 04 18:47:02 IST 2019
RANDOM CLASS

Java Random class is used to generate a stream of pseudorandom numbers.


The algorithms implemented by Random class use a protected utility method
than can supply up to 32 pseudorandomly generated bits on each invocation.
Random class is used to generate pseudo-random numbers in java. An
instance of this class is thread-safe. The instance of this class is
however cryptographically insecure. This class provides various
method calls to generate different random data types such as float,
double, int.
Constructors:
•Random(): Creates a new random number generator
•Random(long seed): Creates a new random number generator using
a single long seed
JAVA IO PACKAGE

Java I/O (Input and Output) is used to process the input and produce the


output.
Java uses the concept of a stream to make I/O operation fast. The java.io
package contains all the classes required for input and output operations.
We can perform file handling in Java by Java I/O API.
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's
called a stream because it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are
attached with the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
INPUTSTREAM
FILE INPUT STREAM CLASS

Java FileInputStream class obtains input bytes from a file.


It is used for reading byte-oriented data (streams of raw bytes) such as image
data, audio, video etc.
You can also read character-stream data. But, for reading streams of
characters, it is recommended to use FileReader class.
Let's see the declaration for java.io.FileInputStream class:
public class FileInputStream extends InputStream ass.
FILE OUTPUT STREAM CLASS

Java FileOutputStream is an output stream used for writing data to a file.


If you have to write primitive values into a file, use FileOutputStream class.
You can write byte-oriented as well as character-oriented data through
FileOutputStream class. But, for character-oriented data, it is preferred to use 
FileWriter than FileOutputStream.
Let's see the declaration for Java.io.FileOutputStream class:
public class FileOutputStream extends OutputStream  
BUFFEREDOUTPUTSTREAM

Java BufferedOutputStream class is used for buffering an output stream. It


internally uses buffer to store data. It adds more efficiency than to write data
directly into a stream. So, it makes the performance fast.
For adding the buffer in an OutputStream, use the BufferedOutputStream class.
Let's see the syntax for adding the buffer in an OutputStream:
OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\
IO Package\\testout.txt"));  
Let's see the declaration for Java.io.BufferedOutputStream class:
public class BufferedOutputStream extends FilterOutputStream  
BUFFEREDINPUTSTREAM

Java BufferedInputStream class is used to read information from stream. It


internally uses buffer mechanism to make the performance fast.
The important points about BufferedInputStream are:
•When the bytes from the stream are skipped or read, the internal buffer
automatically refilled from the contained input stream, many bytes at a time.
•When a BufferedInputStream is created, an internal buffer array is created.
Let's see the declaration for Java.io.BufferedInputStream class:
public class BufferedInputStream extends FilterInputStream  
BYTE ARRAY OUTPUT STREAM

Java ByteArrayOutputStream class is used to write common data into


multiple files. In this stream, the data is written into a byte array which can be
written to multiple streams later.
The ByteArrayOutputStream holds a copy of data and forwards it to multiple
streams.
The buffer of ByteArrayOutputStream automatically grows according to data.
Let's see the declaration for Java.io.ByteArrayOutputStream class:
public class ByteArrayOutputStream extends OutputStream  
BYTE ARRAY INPUT STREAM

The ByteArrayInputStream is composed of two words: ByteArray and


InputStream. As the name suggests, it can be used to read byte array as input
stream.
Java ByteArrayInputStream class contains an internal buffer which is used
to read byte array as stream. In this stream, the data is read from a byte array.
The buffer of ByteArrayInputStream automatically grows according to data.
Let's see the declaration for Java.io.ByteArrayInputStream class:
public class ByteArrayInputStream extends InputStream  
JAVA FILE WRITER CLASS
FILE READER CLASS IN JAVA
JAVA BUFFERED WRITER
BUFFERED READER CLASS
CHAR ARRAY READER CLASS
CHAR ARRAY WRITER CLASS
UNIT-4
EXCEPTION HANDLING
EXCEPTIONS

The Exception Handling in Java is one of the powerful mechanism to handle


the runtime errors so that normal flow of the application can be maintained.
What is Exception?
Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program.
It is an object which is thrown at runtime.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of
the application. An exception normally disrupts the normal flow of the
application that is why we use exception handling.
EXCEPTIONS

•Exceptions are events that occur during the execution of programs that disrupt the normal flow of
instructions (e.g. divide by zero, array access out of bound, etc.).
•In Java, an exception is an object that wraps an error event that occurred within a method and contains:
•Information about the error including its type
•The state of the program when the error occurred
•Optionally, other custom information
•Exception objects can be thrown and caught.
Exceptions are used to indicate many different types of error conditions.
•JVM Errors:
•OutOfMemoryError
•StackOverflowError
•LinkageError
System errors:
•FileNotFoundException
•IOException
•SocketTimeoutException
•Programming errors:
•NullPointerException
•ArrayIndexOutOfBoundsException
•ArithmeticException
EXAMPLE

Suppose there are 10 statements in your program and there occurs an exception at
statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not
be executed. If we perform exception handling, the rest of the statement will be
executed. That is why we use exception handling in Java.
1.statement 1;  
2.statement 2;  
3.statement 3;  
4.statement 4;  
5.statement 5;//exception occurs  
6.statement 6;  
7.statement 7;  
8.statement 8;  
9.statement 9;  
10.statement 10;  
EXCEPTIONS

All exceptions and errors extend from a common java.lang.Throwable parent class. Only Throwable objects can be
thrown and caught.
Other classes that have special meaning in Java are
java.lang.Error (JVM Error), java.lang.Exception (System Error), and java.lang.RuntimeException (Programming
Error).
public class java.lang.Throwable extends Object
implements java.io.Serializable {
public Throwable();
public Throwable(String msg);
public Throwable(String msg, Throwable cause);
public Throwable(Throwable cause);
public String getMessage();
public String getLocalizedMessage();
public Throwable getCause();
public Throwable initCause(Throwable cause);
public String toString();
public void printStackTrace();
public void printStackTrace(java.io.PrintStream);
public void printStackTrace(java.io.PrintWriter);
public Throwable fillInStackTrace();
public StackTraceElement[] getStackTrace();
public void setStackTrace(StackTraceElement[] stackTrace);}=
TYPES

Checked Exception
The classes which directly inherit Throwable class except RuntimeException
and Error are known as checked exceptions e.g. IOException, SQLException
etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked
at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
AssertionError etc.
JAVA CATCH BLOCK

Java catch block is used to handle the Exception by declaring the type of
exception within the parameter.
The declared exception must be the parent class exception ( i.e., Exception) or
the generated exception type. However, the good approach is to declare the
generated type of exception.
The catch block must be used after the try block only. You can use multiple
catch block with a single try block.
PROBLEM WITHOUT EXCEPTION HANDLING

Let's try to understand the problem if we don't use a try-catch block.


public class TryCatchExample1 {  
 public static void main(String[] args) {  
  int data=50/0; //may throw exception             
        System.out.println("rest of the code");  }  }  
output: Exception in thread "main" java.lang.ArithmeticException: / by zero
As displayed in the above example, the rest of the code is not executed (in
such case, the rest of the code statement is not printed).
There can be 100 lines of code after exception. So all the code after exception
will not be executed.
SOLUTION BY EXCEPTION HANDLING

Let's see the solution of the above problem by a java try-catch block.
Example 2
public class TryCatchExample2 {  
    public static void main(String[] args) {  
        try  {
 int data=50/0; //may throw exception           }  
            //handling the exception  
        catch(ArithmeticException e)  {
              System.out.println(e);   }
  System.out.println("rest of the code");  }  }  
Output: java.lang.ArithmeticException: / by zero rest of the code
Now, as displayed in the above example, the rest of the code is executed, i.e., the rest of the
code statement is printed.
INTERNAL WORKING OF TRY AND
CATCH BLOCK
INTERNAL WORKING OF JAVA TRY-
CATCH BLOCK

The JVM firstly checks whether the exception is handled or not. If exception
is not handled, JVM provides a default exception handler that performs the
following tasks:

Prints out exception description.


Prints the stack trace (Hierarchy of methods where the exception occurred).
Causes the program to terminate.
But if exception is handled by the application programmer, normal flow of the
application is maintained i.e. rest of the code is executed.
JAVA MULTI-CATCH BLOCK

A try block can be followed by one or more catch blocks. Each catch block
must contain a different exception handler. So, if you have to perform
different tasks at the occurrence of different exceptions, use java multi-catch
block.
•At a time only one exception occurs and at a time only one catch block is
executed.
•All catch blocks must be ordered from most specific to most general, i.e.
catch for ArithmeticException must come before catch for Exception.
JAVA NESTED TRY BLOCK

The try block within a try block is known as nested try block in java.
Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.
....  
try  {  
    statement 1;  
    statement 2;  
    try  { 
         statement 1;  
        statement 2;      } 
     catch(Exception e)  
  {  }  }  
catch(Exception e)  
{ }  ....  
JAVA FINALLY BLOCK

Java finally block is a block that is used to execute important code such as


closing connection, stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block follows try or catch block.
Note: If you don't handle exception, before terminating the program, JVM
executes finally block(if any).
Finally block in java can be used to put "cleanup" code such as closing a file,
closing connection etc.
Let's see the different cases where java finally block can be used.
Rule: For each try block there can be zero or more catch blocks, but only
one finally block.
Note: The finally block will not be executed if program exits(either by calling
System.exit() or by causing a fatal error that causes the process to abort).
JAVA THROW KEYWORD

The Java throw keyword is used to explicitly throw an exception.


We can throw either checked or uncheked exception in java by throw
keyword. The throw keyword is mainly used to throw custom exception. We
will see custom exceptions later.
The syntax of java throw keyword is given below.
throw exception;  
Let's see the example of throw IOException.
throw new IOException("sorry device error);  
In this example, we have created the validate method that takes integer value
as a parameter. If the age is less than 18, we are throwing the
ArithmeticException otherwise print a message welcome to vote.
JAVA EXCEPTION PROPAGATION

An exception is first thrown from the top of the stack and if it is not caught, it
drops down the call stack to the previous method,If not caught there, the
exception again drops down to the previous method, and so on until they are
caught or until they reach the very bottom of the call stack.This is called
exception propagation.
Rule: By default Unchecked Exceptions are forwarded in calling chain
(propagated).
JAVA THROWS KEYWORD

The Java throws keyword is used to declare an exception. It gives an information to the


programmer that there may occur an exception so it is better for the programmer to provide
the exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.
return_type method_name() throws exception_class_name{  
//method code  }  
Which exception should be declared
Ans) checked exception only, because:
•unchecked Exception: under your control so correct your code.
•error: beyond your control e.g. you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.
Advantage of Java throws keyword
Now Checked Exception can be propagated (forwarded in call stack).
It provides information to the caller of the method about the exception.
JAVA THROWS EXAMPLE

Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.
Rule: If you are calling a method that declares an exception, you must either
caught or declare the exception.
1.There are two cases:Case1:You caught the exception i.e. handle the exception using try/catch.
2.Case2:You declare the exception i.e. specifying throws with the method.
Case1: You handle the exception
•In case you handle the exception, the code will be executed fine whether exception occurs
during the program or not.
Case2: You declare the exception
•A)In case you declare the exception, if exception does not occur, the code will be executed fine.
•B)In case you declare the exception if exception occures, an exception will be thrown at runtime
because throws does not handle the exception.
BUILT IN EXCEPTIONS

Many exceptions and errors are automatically generated by the java virtual
machine.
Errors generally abnormal situations in the JVM such as:
Running out of memory
Infinite recursion
Inability to link to another class
Run time exceptions, are generally a result of programming errors such as:
Dereferencing a null reference
Trying to read outside the bounds of an array
Dividing an integer value by zero.
CHECKED EXCEPTION

Checked exceptions are called compile-time exceptions because these exceptions are checked at


compile-time by the compiler. The compiler ensure whether the programmer handles the exception or
not.
import java.io.*;  
class CheckedExceptionExample {  
    public static void main(String args[]) throws IOException{  
        FileInputStream file_data = null;  
        file_data = new FileInputStream(“Akhila.txt");  
        int m;  
        while(( m = file_data.read() ) != -1) {  
            System.out.print((char)m);          }  
        file_data.close();  }  }  
In the above code, we are trying to read the Akhila.txt file and display its data or content on the screen.
The program throws following exceptions
The FileInputStream(File filename) constructor throws the FileNotFoundException that is checked
exception.
The read() method of the FileInputStream class throws the IOException.
The close() method also throws the IOException.
HOW TO RESOLVE THE ERROR?

There are basically two ways through which we can solve these errors.
1) The exceptions occur in the main method. We can get rid from these
compilation errors by declaring the exception in the main method using the
throws We only declare the IOException, not FileNotFoundException,
because of the child-parent relationship. The IOException class is the parent
class of FileNotFoundException, so this exception will automatically cover by
IOException. We will declare the exception in the following way:
class Exception{  
    public static void main(String args[])  throws IOException {  
        ...  
        ...  }  
If we compile and run the code, the errors will disappear, and we will see the
data of the file.
CONT…

We can also handle these exception using try-catch However, the way which


we have used above is not correct.
We have to a give meaningful message for each exception type.
By doing that it would be easy to understand the error.
We will use the try-catch block in the following way:
UNCHECKED EXCEPTION

The unchecked exceptions are just opposite to the checked exceptions. The compiler will


not check these exceptions at compile time.
In simple words, if a program throws an unchecked exception, and even if we didn't
handle or declare it, the program would not give a compilation error.
Usually, it occurs when the user provides bad data during the interaction with the program.
class UncheckedExceptionExample1 {    
   public static void main(String args[])     {  
    int postive = 35;  
    int zero = 0;  
    int result = positive/zero;  
    //Give Unchecked Exception here.   
System.out.println(result);  }  }  
In the above program, we have divided 35 by 0. The code would be compiled successfully,
but it will throw an ArithmeticException error at runtime. On dividing a number by 0
throws the divide by zero exception that is a uncheck exception.
CONT…

Note: The RuntimeException class is able to resolve all the unchecked


exceptions because of the child-parent relationship.
class UncheckedException1 {    
   public static void main(String args[])     {  
    int num[] ={10,20,30,40,50,60};  
    System.out.println(num[7]);     }  }
In the above code, we are trying to get the element located at position 7, but
the length of the array is 6. The code compiles successfully, but throws the
ArrayIndexOutOfBoundsException at runtime.  
USER DEFINED EXCEPTION

In Java, we already have some built-in exception classes like 


ArrayIndexOutOfBoundsException, NullPointerException, and ArithmeticException.
These exceptions are restricted to trigger on some predefined conditions. In Java, we can
write our own exception class by extends the Exception class.
We can throw our own exception on a particular condition using the throw keyword.
For creating a user-defined exception, we should have basic knowledge of the try-catch
 block and throw keyword.
Bugs or errors that we don't want and restrict the normal execution of the programs are
referred to as exceptions.
ArithmeticException,ArrayIndexOutOfBoundExceptions,ClassNotFoundExceptions et
c.are come in the category of Built-in Exception.
Sometimes, the built-in exceptions are not sufficient to explain or describe certain situations.
For describing these situations, we have to create our own exceptions by creating an
exception class as a subclass of the Exception class.
These types of exceptions come in the category of User-Defined Exception.
CHAINED EXCEPTIONS

Chained Exceptions allows to relate one exception with another exception, i.e one
exception describes cause of another exception.
For example, consider a situation in which a method throws an ArithmeticException
because of an attempt to divide by zero but the actual cause of exception was an
I/O error which caused the divisor to be zero. The method will throw only
ArithmeticException to the caller. So the caller would not come to know about the
actual cause of exception. Chained Exception is used in such type of situations.
Constructors Of Throwable class Which support chained exceptions in java:
1. Throwable(Throwable cause) :- Where cause is the exception that causes the
current exception.
2.Throwable(String msg, Throwable cause) :- Where msg is the exception message
and cause is the exception that causes the current exception.
Methods Of Throwable class Which support chained exceptions in java :
3.getCause() method :- This method returns actual cause of an exception.
4.initCause(Throwable cause) method :- This method sets the cause for the calling
exception.
MULTI THREADING IN JAVA
MULTI THREADING IN JAVA

Multithreading in Java is a process of executing multiple threads simultaneously.


A thread is a lightweight sub-process, the smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared
memory area.
They don't allocate separate memory area so saves memory, and context-switching
between the threads takes less time than process.
Java Multithreading is mostly used in games, animation, etc.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform
multiple operations at the same time.
2) You can perform many operations together, so it saves time.
Threads are independent, so it doesn't affect other threads if an exception occurs in
a single thread.
MULTI TASKING

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to


utilize the CPU. Multitasking can be achieved in two ways:
•Process-based Multitasking (Multiprocessing)
•Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
•Each process has an address in memory. In other words, each process allocates a separate
memory area.
•A process is heavyweight.
•Cost of communication between the process is high.
•Switching from one process to another requires some time for saving and loading registers,
memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
•Threads share the same address space.
•A thread is lightweight.
•Cost of communication between the thread is low.
•Note: At least one process is required for each thread.
THREAD

A thread is a lightweight subprocess, the smallest unit of processing. It is a


separate path of execution.
Threads are independent. If there occurs exception in one thread, it doesn't
affect other threads. It uses a shared memory area.
As shown in the above figure, a thread is executed inside the process. There is
context-switching between the threads. There can be multiple processes inside
the OS, and one process can have multiple threads.
Note: At a time one thread is executed only.
Java provides Thread class to achieve thread programming. Thread class
provides constructors and methods to create and perform operations on a
thread. Thread class extends Object class and implements Runnable interface.
LIFE CYCLE OF A THREAD

A thread can be in one of the five states. According to sun, there is only 4
states in thread life cycle in java new, runnable, non-runnable and
terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread
states are as follows:
1.New
2.Runnable
3.Running
4.Non-Runnable (Blocked)
5.Terminated
HOW TO CREATE A THREAD

There are two ways to create a thread:


1.By extending Thread class
2.By implementing Runnable interface.
Thread class:
Thread class provide constructors and methods to create and perform
operations on a thread.Thread class extends Object class and implements
Runnable interface.
Commonly used constructors of thread class:
•Thread()
•Thread(String name)
•Thread(Runnable r)
•Thread(Runnable r, String name)
RUNNABLE INTERFACE

The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method
named run().
public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs
following tasks:
•A new thread starts(with new callstack).
•The thread moves from New state to the Runnable state.
•When the thread gets a chance to execute, its target run() method will run.
•If you are not extending the Thread class,your class object would not be treated as a
thread object.So you need to explicitely create Thread class object.We are passing
the object of your class that implements Runnable so that your class run() method
may execute.
THREAD SCHEDULER IN JAVA

Thread scheduler in java is the part of the JVM that decides which thread
should run.
There is no guarantee that which runnable thread will be chosen to run by the
thread scheduler.
Only one thread at a time can run in a single process.
The thread scheduler mainly uses preemptive or time slicing scheduling to
schedule the threads.
Difference between preemptive scheduling and time slicing
Under preemptive scheduling, the highest priority task executes until it enters
the waiting or dead states or a higher priority task comes into existence. Under
time slicing, a task executes for a predefined slice of time and then reenters the
pool of ready tasks. The scheduler then determines which task should execute
next, based on priority and other factors.
SLEEP METHOD IN JAVA

The sleep() method of Thread class is used to sleep a thread for the specified
amount of time.
Syntax of sleep() method in java
The Thread class provides two methods for sleeping a thread:
•public static void sleep(long miliseconds)throws InterruptedException
•public static void sleep(long miliseconds, int nanos)throws
InterruptedException
As you know well that at a time only one thread is executed. If you sleep a
thread for the specified time,the thread shedular picks up another thread and
so on.
CAN WE START A THREAD TWICE

No. After starting a thread, it can never be started again. If you does so,
an IllegalThreadStateException is thrown. In such case, thread will run once
but for second time, it will throw exception.
Let's understand it by the example given below:
public class ThreadTwice extends Thread{  
 public void run(){  
  System.out.println("running...");   }  
 public static void main(String args[]){  
  ThreadTwice t1=new ThreadTwice();  
  t1.start();  
t1.start();  }  }  
Output: running
Exception in thread “main” java.lang.IllegalThreadStateException.
WHAT IF WE CALL RUN() METHOD
DIRECTLY INSTEAD START() METHOD?

•Each thread starts in a separate 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.
class CallRun extends Thread{  
 public void run(){  
   System.out.println("running...");   }  
 public static void main(String args[]){  
  CallRun t1=new CallRun();  
t1.run();//fine, but does not start a separate call stack  }  }  
Output: running…
As you can see in the above program that there is no context-switching
because here t1 and t2 will be treated as normal object not thread object.
JOIN METHOD

The join() method waits for a thread to die. In other words, it causes 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

The currentThread() method returns a reference to the currently executing


thread object.
NAMING A THREAD

The Thread class provides methods to change and get the name of a thread. By
default, each thread has a name i.e. thread-0, thread-1 and so on. By we can
change the name of the thread by using setName() method. The syntax of
setName() and getName() methods are given below:
1.public String getName(): is used to return the name of a thread.
2.public void setName(String name): is used to change the name of a thread.
PRIORITY OF A THREAD

Each thread have a priority. Priorities are represented by a number between 1


and 10. In most cases, thread schedular schedules the threads according to
their priority (known as preemptive scheduling). But it is not guaranteed
because it depends on JVM specification that which scheduling it chooses.
3 constants defined in Thread class:
1.public static int MIN_PRIORITY
2.public static int NORM_PRIORITY
3.public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of
MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
DAEMON THREAD

Daemon thread in java is a service provider thread that provides services to the user thread.
Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates
this thread automatically.
There are many java daemon threads running automatically e.g. gc, finalizer etc.
You can see all the detail by typing the jconsole in the command prompt. The jconsole tool
provides information about the loaded classes, memory usage, running threads etc.
Points to remember for Daemon Thread in Java
•It provides services to user threads for background supporting tasks. It has no role in life than
to serve user threads.
•Its life depends on user threads.
•It is a low priority thread.
•Why JVM terminates the daemon thread if there is no user thread?
•The sole purpose of the daemon thread is that it provides services to user thread for
background supporting task. If there is no user thread, why should JVM keep running this
thread. That is why JVM terminates the daemon thread if there is no user thread.
•Note: If you want to make a user thread as Daemon, it must not be started otherwise
it will throw IllegalThreadStateException.
JAVA THREAD POOL

Java Thread pool represents a group of worker threads that are waiting for
the job and reuse many times.
In case of thread pool, a group of fixed size threads are created. A thread from
the thread pool is pulled out and assigned a job by the service provider. After
completion of the job, thread is contained in the thread pool again.
Advantage of Java Thread Pool
Better performance It saves time because there is no need to create new
thread.
Real time usage
It is used in Servlet and JSP where container creates a thread pool to process
the request.
EXECUTORSERVICE

The Java ExecutorService is the interface which allows us to execute tasks on


threads asynchronously. The Java ExecutorService interface is present in the
java.util.concurrent package. The ExecutorService helps in maintaining a pool
of threads and assigns them tasks. It also provides the facility to queue up
tasks until there is a free thread available if the number of tasks is more than
the threads available.
THREAD GROUP IN JAVA

Java provides a convenient way to group multiple threads in a single object. In


such way, we can suspend, resume or interrupt group of threads by a single
method call.
Note: Now suspend(), resume() and stop() methods are deprecated.
Java thread group is implemented by java.lang.ThreadGroup class.
A ThreadGroup represents a set of threads. A thread group can also include the
other thread group. The thread group creates a tree in which every thread
group except the initial thread group has a parent.
A thread is allowed to access information about its own thread group, but it
cannot access the information about its thread group's parent thread group or
any other thread groups.
JAVA SHUTDOWN HOOK

The shutdown hook can be used to perform cleanup resource or save the state when JVM shuts down
normally or abruptly. Performing clean resource means closing log file, sending some alerts or
something else. So if you want to execute some code before JVM shuts down, use shutdown hook.
When does the JVM shut down?
•The JVM shuts down when:user presses ctrl+c on the command prompt
•System.exit(int) method is invoked
•user logoff
•user shutdown etc.
The addShutdownHook(Thread hook) method
The addShutdownHook() method of Runtime class is used to register the thread with the Virtual
Machine.
Syntax:
public void addShutdownHook(Thread hook){}  
The object of Runtime class can be obtained by calling the static factory method getRuntime(). For
example:
Runtime r = Runtime.getRuntime();
Factory method
The method that returns the instance of a class is known as factory method.
Note: The shutdown sequence can be stopped by invoking the halt(int) method of Runtime
class.
ISALIVE()

The isAlive() method of thread class tests if the thread is alive. A thread is


considered alive when the start() method of thread class has been called and
the thread is not yet dead. This method returns true if the thread is still running
and not finished.
Syntax:
public final boolean isAlive()
Returns :
This method will return true if the thread is alive otherwise returns false.)  
GARBAGE COLLECTION

In java, garbage means unreferenced objects.


Garbage Collection is process of reclaiming the runtime unused memory
automatically. In other words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in
java it is performed automatically. So, java provides better memory management.
Advantage of Garbage Collection
•It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
•It is automatically done by the garbage collector(a part of JVM) so we don't
need to make extra efforts.
How can an object be unreferenced?
There are many ways:
•By nulling the reference
•By assigning a reference to another
•By anonymous object etc.
SYNCHRONIZATION IN JAVA

Synchronization in java is the capability to control the access of multiple threads to any shared resource.
Java Synchronization is better option where we want to allow only one thread to access the shared
resource.
Why use Synchronization
The synchronization is mainly used to
1.To prevent thread interference.
2.To prevent consistency problem.
Types of Synchronization
There are two types of synchronization
3.Process Synchronization
4.Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
5.Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
6.Cooperation (Inter-thread communication in java)
MUTUAL EXCLUSIVE

Mutual Exclusive helps keep threads from interfering with one another while
sharing data. This can be done by three ways in java:
1.by synchronized method
2.by synchronized block
3.by static synchronization
Concept of Lock in Java
Synchronization is built around an internal entity known as the lock or
monitor. Every object has an lock associated with it. By convention, a thread
that needs consistent access to an object's fields has to acquire the object's lock
before accessing them, and then release the lock when it's done with them.
From Java 5 the package java.util.concurrent.locks contains several lock
implementations.
SYNCHRONIZED BLOCK IN JAVA

Synchronized block can be used to perform synchronization on any specific


resource of the method.
Suppose you have 50 lines of code in your method, but you want to
synchronize only 5 lines, you can use synchronized block.
If you put all the codes of the method in the synchronized block, it will work
same as the synchronized method.
Points to remember for Synchronized block
•Synchronized block is used to lock an object for any shared resource.
•Scope of synchronized block is smaller than the method.
Syntax to use synchronized block
1.synchronized (object reference expression) {   
2.  //code block   
3.}  
STATIC SYNCHRONIZATION

If you make any static method as synchronized, the lock will be on the class not on object.
Problem without static synchronization
Suppose there are two objects of a shared class(e.g. Table) named object1 and object2.In case
of synchronized method and synchronized block there cannot be interference between t1 and
t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single lock.But
there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and
t3 acquires another lock.I want no interference between t1 and t3 or t2 and t4.Static
synchronization solves this problem.
Synchronized block on a class lock:
The block synchronizes on the lock of the object denoted by the reference .class name .class.
A static synchronized method printTable(int n) in class Table is equivalent to the following
declaration:
1.static void printTable(int n) {  
2.    synchronized (Table.class) {       // Synchronized block on class A  
3.        // ...  
 }  }  
.
DEADLOCK

Deadlock in java is a part of multithreading. Deadlock can occur in a situation


when a thread is waiting for an object lock, that is acquired by another thread
and second thread is waiting for an object lock that is acquired by first thread.
Since, both threads are waiting for each other to release the lock, the condition
is called deadlock.
INTERTHREAD COMMUNICATION
IN JAVA

Inter-thread communication or Co-operation is all about allowing


synchronized threads to communicate with each other.
Cooperation (Inter-thread communication) is 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.It is implemented by
following methods of Object class:
•wait()
•notify()
•notifyAll()
WAIT METHOD

Causes current thread to release the lock and wait until either another thread
invokes the notify() method or the notifyAll() method for this object, or a
specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from
the synchronized method only otherwise it will throw exception.
NOTIFY AND NOTIFYALL

Notify():
Wakes up a single thread that is waiting on this object's monitor. If any threads
are waiting on this object, one of them is chosen to be awakened. The choice
is arbitrary and occurs at the discretion of the implementation. Syntax:
public final void notify()
NotifyAll():
Wakes up all threads that are waiting on this object's monitor. Syntax:
public final void notifyAll()
OBJECT ORIENTED PROGRAMMING

Lecture #36: Graphics Programming


SWINGS

Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to
create window-based applications. It is built on the top of AWT (Abstract
Windowing Toolkit) API and entirely written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight
components.
The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
The Java Foundation Classes (JFC) are a set of GUI components which
simplify the development of desktop applications.
COMPONENTS AND CONTAINERS

In Java, a component is the basic user interface object and is found in


all Java applications. Components include lists, buttons, panels, and
windows.
To use components, you need to place them in a container.
A container is a component that holds and manages other components.
Containers display components using a layout manager.
Swing components inherit from the javax.Swing.JComponent
class, which is the root of the Swing component hierarchy.
JComponent, in turn, inherits from the Container class in the
Abstract Windowing Toolkit (AWT). So Swing is based on
classes inherited from AWT.
MVC ARCHITECTURE

Swing uses the model-view-controller architecture (MVC) as the fundamental


design behind each of its components. Essentially, MVC breaks GUI
components into three elements. Each of these elements plays a crucial
role in how the component behaves.
Model:
The model encompasses the state data for each component. There are
different models for different types of components.
For example, the model of a scrollbar component might contain information
about the current position of its adjustable “thumb,” its minimum and
maximum values, and the thumb’s width (relative to the range of values).
A menu, on the other hand, may simply contain a list of the menu items the
user can select from.
Note that this information remains the same no matter how the component
is painted on the screen; model data always exists independent of the
component’s visual representation.
MVC ARCHITECTURE

View:
The view refers to how you see the component on the screen. For a
good example of how views can differ, look at an application window on
two different GUI platforms. Almost all window frames will have a titlebar
spanning the top of the window. However, the titlebar may have a close
box on the left side (like the older MacOS platform), or it may have the
close box on the right side (as in the Windows 95 platform). These are
examples of different types of views for the same window object.
Control:
The controller is the portion of the user interface that dictates how the
component interacts with events. Events come in many forms — a
mouse click, gaining or losing focus, a keyboard event that triggers a
specific menu command, or even a directive to repaint part of the
screen. The controller decides how each component will react to the
event—if it reacts at all.
ARCHITECTURE
DESCRIPTION

Figure 1.5 shows how the model, view, and controller work together to create
a scrollbar component.
The scrollbar uses the information in the model to determine how far into the
scrollbar to render the thumb and how wide the thumb should be. Note that the
model specifies this information relative to the minimum and the maximum.
It does not give the position or width of the thumb in screen pixels—the view
calculates that.
The view determines exactly where and how to draw the scrollbar, given the
proportions offered by the model.
The view knows whether it is a horizontal or vertical scrollbar, and it knows
exactly how to shadow the end buttons and the thumb.
Finally, the controller is responsible for handling mouse events on the
component.
The controller knows, for example, that dragging the thumb is a legitimate action
for a scroll bar, and pushing on the end buttons is acceptable as well. The result
is a fully functional MVC scrollbar.
FLOW LAYOUT
GRID LAYOUT
BOX LAYOUT
CARD LAYOUT
JAVA APPLET

Applet is a special type of program that is embedded in the webpage to


generate the dynamic content. It runs inside the browser and works at client
side.
Advantage of Applet Applets can perform
• It works at client side so less response time. arithmetic operations,
• Secured display graphics, play
sounds, accepts user
• It can be executed by browsers running under manyinputs,
plateforms,
creates including
Linux, Windows, Mac Os etc. animations
APPLETS

How applets differ from applications:


• Applets do not use main() method
• Applets cannot run independently. They run inside a webpage using HTML
code
• Applets cannot read from or write to the files in the local computer
• Applet are restricted from using libraries from other languages such as C
or C++.

These restrictions ensure


security and cannot do any
damage to the local system
APPLETS

Steps involved in developing and testing an applet are:


1. Building an applet code (.java code)
2. Creating an executable applet (.class file)
3. Designing a webpage using HTML tags
4. Preparing <APPLET> tag
5. Incorporating <APPET> tag into web page(creating HTML file)
6. Testing the applet code.
1. BUILDING AN APPLET
Applet Life cycle:
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It
provides 4 life cycle methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked
only once.
2. public void start(): is invoked after the init() method or browser
is maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when
Applet is stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked
only once.

java.awt.Component class
The Component class provides 1 life cycle method of applet.
5. public void paint(Graphics g): is used to paint the Applet. It
provides Graphics class object that can be used for drawing oval,
rectangle, arc etc.
import java.applet.*;
import java.awt.*;
public class appletclassname extends
Applet
{
...............
...............
Hierarchy of Applet------
public void paint( Graphics g)
>
{
............... // Applet operations code
...............
}
...............
...............
}
import java.applet.*;
import java.awt.*;
Helloapplet.java
public class Helloapplet extends Applet
{
public void paint( Graphics g)
{
g.drawString(“Hello Java”,10,100);

}
2. CREATING AN EXECUTABLE
APPLET (.CLASS FILE)

.class file is obtained by compiling the source codeof the applet.

javac Helloapplet.java

this generates Helloapplet.class file.


3. DESIGNING A WEBPAGE USING
HTML TAGS

In order to run a java applet, it is first necessary to have a webpage that references
the applet.
Web page is made with HTML tags.

<HTML>
<HEAD>
...
</HEAD>
<BODY>
....
</BODY>
</HTML>

<APPLET> tag is used.


4.PREPARING <APPLET> TAG

<APPLET> tag supplies the name of the applet to be loaded and tells trowser
how much space required by the applet.
This specifies three things
1. name of the applet Example:
2. Width of the applet(in pixels) <APPLET
code=Helloapplet.class
3. Height of the applet(in pixels)
width=400
height=200 >
</APPLET>
5. CREATING HTML FILE

<HTML>
<HEAD>
<TITLE> Welcome to Java Applets</TITLE>
</HEAD>
<BODY>

<APPLET Helloapplet.html
code=Helloapplet.class
width=400
height=200 >
</APPLET>

</BODY>

</HTML>
6.TESTING THE APPLET CODE.

Our current directory will have following things:


Helloapplet.java
Helloapplet.class
Helloapplet.html

To run an applet, we require one of the folowing:


1. java enabled web browser(entire webpage can be seen)
2. java applet viewer(only applet output)

Syntax:
appletviewer Helloapplet.html
OBJECT ORIENTED PROGRAMMING

Lecture #37: Graphics Programming


(Devoloping and Testing an Applet)
JAVA APPLET

Applet is a special type of program that is embedded in the webpage to


generate the dynamic content. It runs inside the browser and works at client
side.
Advantage of Applet Applets can perform
• It works at client side so less response time. arithmetic operations,
• Secured display graphics, play
sounds, accepts user
• It can be executed by browsers running under manyinputs,
plateforms,
creates including
Linux, Windows, Mac Os etc. animations
APPLETS

Steps involved in developing and testing an applet are:


1. Building an applet code (.java code)
2. Creating an executable applet (.class file)
3. Designing a webpage using HTML tags
4. Preparing <APPLET> tag
5. Incorporating <APPET> tag into web page(creating HTML file)
6. Testing the applet code.
import java.applet.*;
import java.awt.*;
public class Helloapplet extends AppletHelloapplet.java
{
public void paint( Graphics g) Helloapplet.html
{
g.drawString(“Hello Java”,10,100);

} <HTML>
} <HEAD>
<TITLE> Welcome to Java Applets</TITLE>
</HEAD>
<BODY>
Helloapplet.class
<APPLET
code=Helloapplet.class
width=400
height=200 >
javac Helloapplet.java </APPLET>

</BODY>

</HTML>
To run an applet, we require one of the folowing:

1. java enabled web browser(entire webpage can be seen)

2. java applet viewer(only applet output)

Syntax:
appletviewer Helloapplet.html

Applet Window------
>
WORKING WITH 2D SHAPES

Graphics class includes methods for drawing many different types of shapes.

Coordinate System of x
(0,0 (50,0
java
) )
(0,20
)

(0,60 (50,60
) )
DRAWING METHODS

Graphics class
OBJECT ORIENTED PROGRAMMING

Lecture #38: Nested class/Inner class


INNER CLASS OR NESTED CLASS

In java, just like methods and varibles, it can have a class too.
Java inner class or nested class is a class which is declared inside the class or
interface.

Syntax:
class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
INNER CLASS OR NESTED CLASS

Types of Nested classes


Two types
1. Static nested class
2. Non-static nested class (inner class)
• Member inner class
• Anonymous inner class
• Local inner class
STATIC NESTED CLASS

A static class i.e. created inside a class is called static nested class in java

Syntax:
class Java_Outer_class{
//code
static class Java_Inner_class{
//code
}
}
No need to
static inner class instance can be created outside the class using following
create outer
Syntax class object
Syntax:
Outer.Inner o1=new Oute.Inner();
STATIC NESTED CLASS

Rules:
• It can be accessed by outer class name.
• Static nested class cannot access non-static (instance) data member or
method.
• It can access static data members of outer class including private.
• static inner class can be public, private, protected and default
• Outer class should be public or default.
INNER CLASS OR NESTED CLASS

Types of Nested classes


Two types
1. Static nested class
2. Non-static nested class (inner class)
• Member inner class
• Anonymous inner class
• Local inner class
NON-STATIC NESTED CLASS
(INNER CLASS)

• Member inner class


A non-static class that is created inside a class but outside a method is called
member inner class.

Syntax:
class Java_Outer_class{
//code Example
class Java_Inner_class{
//code
}
}

Outer class Object is required.


NON-STATIC NESTED CLASS
(INNER CLASS)

• Anonymous inner class


A class that have no name is known as anonymous inner class in java.
It should be used if you have to override method of class or interface.

Example
NON-STATIC NESTED CLASS
(INNER CLASS)

• Local inner class


A class i.e. created inside a method is called local inner class in java.
If you want to invoke the methods of local inner class, you must instantiate
this class inside the method.

Example
OBJECT ORIENTED PROGRAMMING

Lecture #39: Event Handling


(Introduction)
EVENT HANDLING

Event?
Change in the state of an object is known as event i.e. event describes the change
in state of source.
Events are generated as result of user interaction with the graphical user interface
components.
For example: press a button, enter a character in textbox, click or drag a mouse,
etc.
Event Handling?
Event Handling is the mechanism that controls the event and decides what should
happen if an event occurs.
This mechanism have the code which is known as event handler that is executed
when an event occurs. (Delegation Event Model)
DELEGATION EVENT MODEL)
Benifit:
User interface
key participants design is
• Source seperated from
event handler
The source is an object on which event occurs.
• Listener
It is also known as event handler. Listener is responsible for generating
response to an event.

Source Listener
Register

Click Here State Change


Java Code Seperate Java
Event Oocurs
Code

Delegating event Response


processing
EVENT HANDLING

Source Listener

Button
Checkbox
List Events
Interfaces
Generates Menuitem
Events sent to
Choice
Scrollbar
Textcomponent Listerners have to register to
sources
Syntax:
window
addTypeListener()
import
java.awt.event.*
EVENT HANDLING paclage

Event Classes Source Interfaces

ActionEvent Button, Menuitem,List ActionListener


AdjustmentEvent AdjustmentListner
Component ComponentListener
ComponentEvent
Component ContainerListner
ContainerEvent
Component
FocusEvent FocusListener
Component
ItemEvent ItemListener
Checkbox,choice
KeyListener
KeyEvent Textcomponent
MouseListener,MouseMotionListener
MouseEvent Mouse movements
MouseWheelListener
MouseWheelEvent MouseWheelmovement
TextListener
TextEvent Textcomponent
WindowListener
WindowEvent Window
EVENT HANDLING

Template:
1. import packages import
java.awt.*;
java.awt.event.*
;
java.applet.*;
2. Class should extend the Applet class and implement the interfaces
3. Write applet code
4. init() method: Register the Listener interface Syntax:
5. Write Event methods defintion addTypeListener()
OBJECT ORIENTED PROGRAMMING

Lecture #40: Mouse Events


EVENT HANDLING

Event?
Change in the state of an object is known as event i.e. event describes the change
in state of source.
Events are generated as result of user interaction with the graphical user interface
components.
For example: press a button, enter a character in textbox, click or drag a mouse,
etc.
Event Handling?
Event Handling is the mechanism that controls the event and decides what should
happen if an event occurs.
This mechanism have the code which is known as event handler that is executed
when an event occurs. (Delegation Event Model)
EVENT HANDLING

Source Listener

Button
Checkbox
List Events
Interfaces
Generates Menuitem
Events sent to
Choice
Scrollbar
Textcomponent Listerners have to register to
sources
Syntax:
window
addTypeListener()
EVENT HANDLING

Event Classes Source Interfaces

ActionEvent Button, Menuitem,List ActionListener


AdjustmentEvent AdjustmentListner
Component ComponentListener
ComponentEvent
Component ContainerListner
ContainerEvent
Component
FocusEvent FocusListener
Component
ItemEvent ItemListener
Checkbox,choice
KeyListener
KeyEvent Textcomponent
MouseListener,MouseMotionListener
MouseEvent Mouse movements
MouseWheelListener
MouseWheelEvent MouseWheelmovement
TextListener
TextEvent Textcomponent
WindowListener
WindowEvent Window
MOUSE EVENTS

Clas Interfaces Methods


s
mousePressed(),
MouseListener mouseClicked(),
mouseEntered(),
mouseExited(),
MouseEvent mouseReleased()

mouseMoved(),
MouseMotionListener
mouseDragged

getX(), getY()
MOUSE EVENTS

Template:
import Example
1. import packages
java.awt.*;
java.awt.event.*
;
java.applet.*;
2. Class should extend the Applet and implement the interfaces
(MouseListener, MouseMotionListener)
3. Write applet code
4. init() method: Register the Listener interface Syntax: addMouseeListener()
5. Write Event methods defintion
addMouseMotionListener()
OBJECT ORIENTED PROGRAMMING

Lecture #41: AWT Hierarchy


OBJECT ORIENTED PROGRAMMING

Lecture #42: Layout managers


AWT VERSUS SWING
Java Generic Methods or generic classes enable Programmers to specify, with
a single method declarations, a set of related methods or, with a single class
declaration, a set of related types.
GENERIC METHODS

We can write a single method declaration that can be called with arguments of
different types.

Rules:
• All genreic method declarations have a type parameter section deleimted
by angle brackets(< and >) that precedes the methods return type
• Each type paramenter section contains one or more type parameters
seperated by commas
• The type parameter can be used to declare the return type
• Type parameters can represent only reference types not primitive types(like
int, double and char)
GENERIC CLASSES

Java Generic Methods or generic classes enable Programmers to specify, with


a single method declarations, a set of related methods or, with a single class
declaration, a set of related types.

Rules:
• Genreic class declaration looks like a non-generic class declaration, except
that the class name is followed by a type parameter section.
• As with Generic methods, the type parament section of a generic class can
have one or more type paramenters seperated by commas
OBJECT ORIENTED PROGRAMMING

Lecture #54: Generic and Inheritance


GENERIC AND INHERITANCE

A class aquring the proprties of another class-Inheritance.


Java Generic Methods or generic classes enable Programmers to specify, with
a single method declarations, a set of related methods or, with a single class
declaration, a set of related types.

3 different ways of Generic and Inheritance


1. Only Super class is Genreic
2. Only Subclass is Generic
3. Super and Sub class both are Generic
ONLY SUPER CLASS IS GENREIC

class SuperA<T> class SubA extends SuperA<T>


{ {
T a; SubA(Integer n1)
SuperA(T n) Output:
{
{ 10
super(n1);
a=n; }
} }
T getA()
{ class Ex
return a; {
} public static void main(String args[])
} {
SubA<Integer> s=new SubA<Integer>(10);
System.out.println(s.getA());
}
}
ONLY SUBCLASS IS GENERIC
class SuperA
{
class SubA<T> extends SuperA{
int a;
T t;
SuperA(int n)
SubA(Integer n1, T x)
{
{
a=n;
super(n1);
} class Ex
t=x;
int getA() {
}
{ public static void main(String args[])
T gett()
return a; {
{
} SubA<String> s=new SubA<String>(10,”Jyothi”);
return t;
} System.out.println(s.getA());
}}
System.out.println(s.gett());
}
}
Output:
10
Jyothi
SUPER AND SUB CLASS BOTH ARE
GENERIC
class SuperA<T> class SubA<T> extends SuperA<T>
{ {
T a; SubA(T n1)
SuperA(T n) { Output:
{ super(n1); 10
a=n; }
} } Jyothi
T getA()
{ class Ex
return a; {
} public static void main(String args[])
} {
SubA<Integer> s=new SubA<Integer>(10);
System.out.println(s.getA());
SubA<String> s1=new SubA<String>(“Jyothi”);
System.out.println(s1.getA());
}
}
GENERIC AND INHERITANCE

3 different ways of Generic and Inheritance


1. Only Super class is Genreic
2. Only Subclass is Generic
3. Super and Sub class both are Generic

subclass is free to
use its own type
parameters if
needed
SUBCLASS IS FREE TO USE ITS OWN
TYPE PARAMETERS IF NEEDED
class SuperA<T> class SubA<T> extends SuperA<T>
{ {
T a; SubA(T n1)
SuperA(T n) { Output:
{ super(n1); 10
a=n; }
} } Jyothi
T getA()
{ class Ex
return a; {
} public static void main(String args[])
} {
SubA<Integer> s=new SubA<Integer>(10);
System.out.println(s.getA());
SubA<String> s1=new SubA<String>(“Jyothi”);
System.out.println(s1.getA());
}
}
SUBCLASS IS FREE TO USE IYS OWN
TYPE PARAMETERS IF NEEDED
class SuperA<T>
{ Output:
T a; class SubA<T,V> extends SuperA<T>
10
SuperA(T n) { V t;
{ SubA(T n1, T x)
Jyothi
a=n; {
} super(n1);
T getA() t=x;
{ } class Ex
return a; V gett() {
} { public static void main(String args[])
} return t; {
} SubA<Integer, String> s=new SubA<Integer,String>
} (10,“Jyothi”);
System.out.println(s.getA());
System.out.println(s.gett());
}
}
OVERRIDING METHODS OF
GENRIC CLASS
class SuperA<T> class SubA<T> extends SuperA<T>
{ { Output:
T a; SubA(T n1) 10
SuperA(T n) { 20
{ super(n1);
a=n; } Jyothi
} T getA() class Ex
T getA() { {
{ return a; public static void main(String args[])
return a; } {
} SuperA<Integer> s1=new SuperA<Integer> (10);
} } SubB<Integer> s2=new SubB<Integer> (20);
SubB<String> s3=new SubB<String> (“Jyothi”);
System.out.println(s1.getA());
System.out.println(s2.getA());
System.out.println(s3.getA());
}
}
SOCKET PROGRAMMING

Java Socket programming is used for communication between the applications running
on different JRE.
Java Socket programming can be connection-oriented or connection-less.
Socket and ServerSocket classes are used for connection-oriented socket programming
and DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.
Connection-oriented service involves the creation and termination of the connection
for sending the data between two or more devices.
In contrast, connectionless service does not require establishing any connection and
termination process for transferring the data over a network.
The client in socket programming must know two information:
1.IP Address of Server, and
2.Port number.
The Socket class is used to communicate client and server. Through this class, we can
read and write message. The ServerSocket class is used at server-side. The accept()
method of ServerSocket class blocks the console until the client is connected.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy