Java
Java
Java
by
Mrs. Akhila Pragada
JAVA IS _____
by
Mrs. Akhila Pragada
PROGRAMMING LANGUAGES
Programming
languages
Program
• 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)
Main Program
C Java
• Object
• Class
• Data Abstraction
• Encapsulation
• Inheritance
• Polymorphism
• Dynamic Binding
• Message Passing
CLASS & OBJECT
•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
}
}
}
}
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
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
Documentation
Section
Package Statements
Import Statements Optional
Interface Statements
Class Definitions
Main method class
{
main method Essentia
definition l
}
DOCUMENTATION SECTION
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
Syntax: Example:
datatype variable int
name; a;
Variable Assignment:
Assigning a value to a variable
Syntax: Example:
variable
name=value; a=10;
VARIABLE
• Java variable names are case sensitive. The variable name apple is not the same
as Apple or APPLE.
• 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
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.
Floating point data types are used to represent numbers with a fractional part.
There are two subtypes:
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
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
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
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)
}
SELECTION STATEMENTS
(if)
“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
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:
Example:
“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:
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
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
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
Java is a collection of
1. White spaces
2. Identifiers
3. Comments
4. Literals
5. Operators
6. Separators
7. Keywords
WHITE SPACES
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:
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
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
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
Output: Output:
a= 20 a= 10
b=20
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;
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
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
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
.
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
Memory Allocation:
Example:
int a[ ][ ] = new int[3][4];;
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
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.*)
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[ ][ ][ ];
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
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}}};
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
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
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.
equalsIgnoreCase( );
Compares this String to another String, ignoring case
considerations.
StartsWith( ):
Tests if string starts with the specified prefix
“Figure”.startsWith(“Fig”); // true
Similarly endsWith()
OBJECT ORIENTED PROGRAMMING
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.
lastIndexOf( ):
Searches for the last occurrence of a character or substring.
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.
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)
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
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
• If two or more method have same name and same parameter list but differs in
return type can not be overloaded.
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
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
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);
}
class Counter2{
static int count=0;
Counter2(){
count++;//incrementing the value of static variable
System.out.println(count);
}
Syntax:
static
{
//code
}
TO BLOCK
class Example {
static int a;
static int b;
static {
a = 10;
b = 2 * a;
}
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;
}
• 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?
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
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;
}
A super class
B sub class B <<class>>
A <<interface>>
class B implements A { ….. }
A interface
B <<class>>
B sub class
TYPES OF INHERITANCE
A A X X
B B A B C A B C
B B
C C
C C
TYPES OF INHERITANCE
OK Z
class Z extends A ,B class Z extends A extends B
{ {
OR
} WRONG } WRONG
OBJECT ORIENTED PROGRAMMING
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
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
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
{
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
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
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
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
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?
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 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
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: “); }
} }
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
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
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
Syntax: Example:
javac -d directory javac -d .
javafilename Simple.java
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
•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
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
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.
Syntax:
public boolean equals(Object
obj)
This method returns true if this object is the same as the obj argument; false
otherwise.
OBJECT CLONING
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 s2=(Student)s1.clone();
System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);
}
catch(CloneNotSupportedException c){}
}
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
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
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
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
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
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
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
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
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
•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 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:
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
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
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
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…
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
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
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?
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:
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
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 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()
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
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
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
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
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
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)
javac Helloapplet.java
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 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.
Syntax:
appletviewer Helloapplet.html
OBJECT ORIENTED PROGRAMMING
} <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:
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
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
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
Syntax:
class Java_Outer_class{
//code Example
class Java_Inner_class{
//code
}
}
Example
NON-STATIC NESTED CLASS
(INNER CLASS)
Example
OBJECT ORIENTED PROGRAMMING
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
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
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
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
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
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
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
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.