JAVA Full Notes

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

Class and Object

Dr. Kasturi Dhal


Department of CSE
Silicon Institute of Technology

[email protected]
What is a class in Java
• Class defines a new data type. Once a class is defined it can be used
to create objects of that type.
• A class is a template for an object and object is an instance of a class.
It is a logical entity.
• Definition: A class is a set of objects that share a common structure
and a common behaviour.
• The properties and actions of the objects are written in the class.
• While defining a class we declare its form and nature by specifying
the data it contains and code that operates on that data.
• A class in Java can contain:
• Fields
• Methods
Syntax
• A class is defined using class keyword
Syntax: class classname{
type instance-variable1;
class class_name type instance-variable2;
{ ...
field; type instance-variableN;
method; type methodname1(parameter-list){
} //body of method
}
type methodname2(parameter-list){
//body of method
}
...
type methodnameN(parameter-list){
//body of method
}
NOTE }

A class declaration only creates a template, it does not create and actual object.
Instance Variable
• The data or variables defined within a class but outside the method
are called instance variables.
• Instance variable doesn't get memory at compile time. It gets
memory at run time when object (instance) is created.
• Each instance (object) of the class contains its own copy of these
variables.
• The data of one object is separate and unique from the data for other.
• Both variables and methods within a class are called members of the
class. Example Class Box{
double width;
double height;
double depth;
}
• To create an object of Box class use the following code:
Creating object of a class:

Box mybox = new Box();

• Every Box object will contain its own copies of the instance variables
width, height and depth of each instance variable defined by the
class.
• To access the instance variables and methods within an object we
need the dot(.) operator.
Example
mybox.height
Method
• A method is like function used to expose behavior of an object.
Syntax
returnType methodName (parameter list) {
statements ; // Code for definition of the method.
}

Note

In java we do not have independent function/methods, it must be a member of a class


or interface.

When a method uses an instance variable that is defined by its class, it does so directly,
without preceding them with an object name or the dot operator.
Object
• An object is a real-world entity.
• An object is a run time entity.
• The object is an entity which has identity, state and behavior.
• The object is an instance or variable of a class.
An object has three characteristics:

• State: represents the data (value) of an object.


• Behavior: represents the behavior (functionality) of an
object such as deposit, withdraw, etc.
• Identity: An object identity is typically implemented via a
unique ID. The value of the ID is not visible to the external
user. However, it is used internally by the JVM to identify
each object uniquely.
Constructors
• It is special type of methods used to initialize an object.
• Constructor name must be the same as its class name.
• It does not return any value, not even void.
• It is called automatically when an instance of the class is created.
• Every time an object is created using the new() keyword, at least one
constructor is called.
• Once we define a constructor, during the object creation, it is
automatically called and finishes its execution before the new operator
completes its work.
• A Java constructor cannot be abstract, static, final, and synchronized.
Types of Constructors
• There are three types of constructors in java.
• Default Constructors(no argument constructor)
• Parameterized Constructor
Default Constructor
• A constructor is called "Default Constructor" when it doesn't have any parameter. The
syntax of default constructor : class-name(){ }
• Default constructor is used to provide the default values to the object like 0, null etc.
depending on the type.
• It is useful to initialize all objects with the same data.
• When data is not passed at the time of creating an object, default constructor is called.
• It is not necessary to write a constructor for a class. It is because java compiler creates a
default constructor if your class doesn't have any.
Example of Default Constructor
Parameterized Constructor
• A constructor which has a specific number of parameters is called
parameterized constructor.
• It is useful to initialize each object with different data.
• When data is passed at the time of creating an object,
parameterized constructor is called.
Parameterized Constructor
Difference between constructor and method in
java
Method Overloading
• If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
• Overloading allows different methods to have the same name, but
different signatures.
• The signature can differ by the number of parameters or type of
parameters.
• Overloading is related to compile-time (or static) polymorphism.
• Method overloading increases the readability of the program
• NOTE: Function cannot be overloaded by their return type
• There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type of arguments
class TestSum1 {

int sum(int x, int y) { class DriverSum{


return (x + y); public static void main(String args[])
{
}
TestSum1 s = new Sum1();
int sum(int x, int y, int z) { System.out.println(s.sum(10, 20));
return (x + y + z); System.out.println(s.sum(10, 20, 30));
} System.out.println(s.sum(10.5, 20.5));
double sum(double x, double y) { }
}
return (x + y);
}

DriverSum.java
Method Overloading with Type Promotion
class Test{
void add(int a){
a++; output
System.out.println(a);
}
void add(float a){ 100
a++; 6.3
System.out.println(a);
}
}
class ABC{
public static void main(String []args){
Test obj=new Test();
obj.add('c’);
obj.add(5.3f);
} ABC.java
}
class Test{
void add(int a,char b){ output

System.out.println(a+b);
} 22.0
void add(int a,double b){
System.out.println(a+b);
}
}
class DriverMain{
public static void main(String []args){
Test obj=new Test();
obj.add(11,11);
DriverMain.java
}
}
Overloading of Constructors

• Like any other method constructors can be overloaded.


Static Keyword
• The static keyword in java is used for memory management mainly.
• When a member is defined as static then then that member will be
used independently of any object.
• it can be accessed before any objects of its class are created, and
without reference to any object.
• The static keyword can be applied on
• Data Member
• Member function
• Block
• Class
Static Data member
• When a data member is declared as static, then a single copy of
variable is created and shared among all objects at class level.
• Syntax: static datatype varname;
• All instances of the class share the same static variable.
• static variables store values for the variable in common memory
location
• Use:
• share the value of the variable among all the object
• count the number of object created for a class
Cont.

• The static variable can be used to refer to the common property of all
objects (which is unique for each object)
• i.e. the company name of Employee, college name of Student class, etc.
• The static variable gets memory only once in the class area, at the
time of class loading.
• Advantages:
1. It makes your program memory efficient (i.e., it saves memory).
2. It is used to share data between the object.
class Student{
int rollno;
String name;
static String college ="Silicon"; output
Student(int r,String n){
rollno = r; 111 Karan Silicon
name = n; 222 Aryan Silicon
}
void display (){
System.out.println (rollno+" "+name+" "+college);
}
}
class TestStudent{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student (222,"Aryan");
s1.display();
s2.display();
}
}
• Static variable will get memory only once. If any object changes the
value of static variable, it will retain its value.

class Counter{
static int count=0;//will get memory only once and retain its value
Counter(){
count++;
System.out.println(count);
} output
public static void main(String args[]){ 1
Counter c1=new Counter(); 2
Counter c2=new Counter(); 3
Counter c3=new Counter();
}
}
What will be the output?
class Test {
static int x = 10;
Option
public static void main(String[] args) {
Test t1 = new Test(); A) 10 10
Test t2 = new Test(); B) 20 20
t1.x = 20; C) 10 20
System.out.print(t1.x + " "); D) 20 10
System.out.println(t2.x);
}
}
Static Methods
• we can make method as static.
• Static method belongs to class rather than object of a class
• static methods can be invoked without creating any instance of the
class
• it can be called by class name ( i.e. Test.fun() )
• NOTE All the methods in Math class are static, so they are
independent of specific instance.
Rules
• Methods declare static have several restriction
1. Static method can directly access static data member and can change value
of it.
2. Static method can not call non static method directly. It can call static
method only.
• A non static method can call both static and non static method
class Student{
int rollno; String name;
static String college ="Silicon";
Student(int r,String n){
rollno = r; name = n; output
}
static void change(){ 111 Karan Silicon
college = "SIT"; 222 Aryan Silicon
} 111 Karan SIT
void display (){ 222 Aryan SIT
System.out.println(rollno+" "+name+" "+college);
}
}
class TestStudent{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display(); s2.display();
Student.change();
s1.display(); s2.display();
}
}
static block
• It is used to initialize static variables. The static block executed exactly
once when the class is loaded in the main memory.
• The code inside static block is executed only once, the first time you
make an object of the class or first time you access static member of
the class.
• JVM executed before main method at the time of class loading
• Syntax:
static{
list of statements...
}
class Example
{
static int num;
static String mystr;
static output
{
num = 97; Value of num: 97
mystr = "Static keyword in Java"; Value of mystr: Static
keyword in Java
}
public static void main(String args[])
{
System.out.println("Value of num: "+num);
System.out.println("Value of mystr: "+mystr);
}
}
• A class can have any number of static blocks
• static blocks are called inorder they appear in the source code.
What will be the output ?

class Test {
static{
int y = 100;
System.out.println("static block y= " + y);
}
public static void main(String[] args) {
int x = 300;
System.out.println(x);
}
static{
int x = 200;
System.out.println("static block x= " + x);
}
}
class Example2
{
static int num;
static String mystr;
static
{
System.out.println("Static Block 1"); output
num = 68;
mystr = "Block1"; Static Block 1
} Static Block 2
static Value of num: 98
{ Value of mystr: Block2
System.out.println("Static Block 2");
num = 98;
mystr = "Block2";
}
public static void main(String args[])
{
System.out.println("Value of num: "+num);
System.out.println("Value of mystr: "+mystr);
}
}
this keyword
• ‘this’ is a reference variable that refers to the currently invoking
object.
class A5 output
{
void m() A5@15db9742
{ A5@15db9742
System.out.println(this);//prints same reference ID
}
public static void main(String args[])
{
A5 obj=new A5();
System.out.println(obj);//prints the reference ID
obj.m();
}
}
• Important uses of this keyword.
1. this keyword can be used to refer current class instance
variables.
• this keyword is used to access the instance variable inside a
function, when local variable name is same as instance
variable name.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this: to pass as argument in the constructor call
6. this keyword can be used to return current class instance
this keyword can be used to refer current class instance variables.
class Student{
int rollno; String name; float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno; output
this.name=name;
this.fee=fee; 111 ankit 5000
} 112 sumit 6000
void display(){
System.out.println(rollno+" "+name+" "+fee);
}
}
class TestThis1{
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. Let's see the example.
class A{
void m(){
System.out.println("hello m");
}
void n(){
System.out.println("hello n");
this.m(); //m();//same as this.m()
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}
}
this(): to invoke current class constructor
• this() can be used to invoke current class constructor
• It is used to reuse constructor
• It is used for constructor chaining
• this() constructor call should be used to reuse the constructor from
the constructor.
• NOTE: Call to this() must be the first statement in constructor.
Otherwise java shows compile time error.
this can be used to invoke current class constructor.
class Example{
int x,y;
Example(){
x =0; y =0;
this(5,10);
}
Example(int a, int b){
x =a; y = b;
}
void display()
{
Sop(x + “ “ + y);
}
}
class TestExample{
public static void main(String args[]){ Calling Parameterized constructor from default
Example ob=new Example(); constructor.
ob.display();
}
}
class Student{
int rollno; String name,course; float fee;
Student(int rollno,String name,String course){
this.rollno=rollno; this.name=name; this.course=course;
}
Student(int rollno,String name,String course,float fee) {
this(rollno,name,course);//reusing constructor
this.fee=fee; output
}
void display() 111 ankit java null
{ 112 sumit java 6000
System.out.println(rollno+" "+name+" "+course+" "+fee);
}
}
class TestStudent{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display(); s2.display();
}
}
this can be passed as an argument in the method call.
class Example{
int x,y;
Example(){ class TestExample{
this(5,10); public static void main(String args[]){
} Example ob=new Example();
Example(int a, int b){ display(ob);
x =a; y = b; ob.modify();
} }
display(Example ob) { }
Sop(ob.x + “ “ + ob.y);
}
void modify(){
x = x +10;
display(this);
}

}
The this keyword can also be passed as an argument in the method. It is mainly used in
the event handling.

class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
this: to pass as argument in the constructor call
• We can pass the this keyword in the constructor also. It is useful if we
have to use one object in multiple classes. Let's see the example:
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this); b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
this keyword can be used to return current class
instance
• We can return this keyword as a statement from the method. In such
case, return type of the method must be the class type). Let's see the
example: Syntax:
class A{ return_type method_name(){
A getA(){ return this;
return this; }
}
void msg(){
System.out.println("Hello java"); output
}
} Hello Java
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Access Specifier
• The access specifier in java specifies accessibility (scope) of a data member,
method, constructor or class.
• It is a keyword that specifies how to access the member of a class or class
itself.
• There are 4 types of access specifier in java
1. public: public member of a class are accessible everywhere including outside the
class. Classes, methods, and fields declared as public can be accessed from any
class in the Java program, whether these classes are in the same package or in
another package. Any other program can read and use them Achieves highest
level of accessibility.
2. private: private member of a class are not accessible anywhere outside the class.
They are only accessible only within the class by the method of that class
3. default: If no access specifier is specified by the programmer, then java compiler
uses default access specifier. Default member are accessible outside the class but
within the same directory.
4. protected: protected members of a class are accessible outside the class, but
generally within the same directory. (will discuss in inheritance chapter)
class Person {
private String name = “Raju”;
private int age = 30;
void talk() {
System.out.println(name + “ “ + age);
}
}
Class TestPerson{
public static void main(String [] args) {
Person ob = new Person();
ob.talk();
ob.name = “xyz”;
}
}
class Hello {
private int a=20;
private void show()
{
System.out.println("Hello java");
}
}
class Demo {
public static void main(String args[]) {
Hello obj=new Hello();
System.out.println(obj.a); //Compile Error, you can't access private data here
obj.show();//Compile Time Error, you can't access private methods here
}
}
Inheritance
Inheritance
• Inheritance is a process in which object of one class can acquire the properties of
object of another class.
• The idea behind inheritance in Java is that you can create new classes that are
built upon existing classes.
• When you inherit from an existing class, you can reuse methods and data
members of the parent class. You can also add new methods and fields in your
current class also.
• Objective: Inheritance supports the concept of “code re-usability”
• i.e when we want to create a new class and there is already a class that
includes some of the code that we want, we can derive our new class from
the existing class. By doing this, we are reusing the fields and methods of the
existing class.
Advantages of using Inheritance
1. Code reusability
2. Cost cutting
3. reduce redundancy
Terms used in Inheritance

• Sub Class/Child Class: Subclass is a class which inherits the other


class. It is also called a derived class, extended class, or child class.
• Super Class/Parent Class: Super class is the class from where a
subclass inherits the features. It is also called a base class or a parent
class.
Cont..
Syntax

class SubclassName extends SuperclassName


{
//methods and fields
}
The extends keyword indicates that you are making a new
class that derives from an existing class.
The meaning of "extends" is to increase the functionality.
class Employee{ //Base class
float salary=40000;
}
class Programmer extends Employee{ //Derived class
int bonus=10000;
}
class DriverInhertance{ //Driver class...
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
class Vehicle {
String brand = "Hyundai"; // Vehicle attribute
}
class Car extends Vehicle {
String modelName = "i10"; // Car attribute
public void display() { // Vehicle method
System.out.println(brand);
System.out.println(modelName);
}

}
class DriverCar{
public static void main(String[] args) {
Car myCar = new Car(); // Create a myCar object
myCar.display(); // Call the display() method (from the Vehicle class) on the myCar
object
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
Types of inheritance in java

Note: Java does not support


multiple
inheritance
Single Inheritance
• In single inheritance, sub classes inherit the features of one
superclass.
• In the given image, the class A serves as a base class for the derived
class B.

• There exists single base class and single derived class.


Example
class Animal{
void eat(){
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){
System.out.println("barking...");
}
}
class Driver{
public static void main(String args[]){
Dog d=new Dog();
d.bark(); d.eat();
}
}s
class Person {
String name,dob;
void setPerson(String n, String d){
name = n; dob = d;
}
}
class Emp extends Person{
int salary, eno;
void setEmp(int s, int e, String name, String dob){
setPerson(name,dob); salary = s; eno = e;
}
void display(){
System.out.println(name + " "+ dob + " "+ eno + " "+
salary);
}
}
class TestEmp{
public static void main(String args[]){
Emp e1 = new Emp();
e1. setEmp(50000,100,"Kasturi Dhal","22 March 1983");
e1.display();
}
}
Although a subclass includes all of the members of its superclass, it cannot access
those members of the superclass that have been declared as private.
class A{
int i;
private int j; // private to A
void setij(int x, int y) {
i = x; j = y;
}
}
class B extends A {
int total;
void sum() {
total = i + j; // ERROR, j is not accessible here
}
}
class Access {
public static void main(String args[]) {
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
System.out.println("Total is " + subOb.total);
}
}
Keyword super
• The super keyword in Java is a reference variable which is used to refer
immediate parent class object.
• Whenever you create the instance of subclass, an instance of parent class is
created implicitly which is referred by super reference variable.
• Usage of keyword super
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
• It is used to access a member of the superclass that has been hidden by a
member of a subclass:
• The keyword super is used to access the member (instance variable of
method) of parent class. It is used if parent class and child class have same
member.
Call the super class constructor.
• Syntax: super(list of arguments);
• Note: super() must be the first instruction in subclass constructor.
• It is used to access a member of the super class that has been hidden
by a member of a subclass.
• super.member ; // It access the super class member
. super.method();
• When a subclass calls super( ), it is calling the constructor of its
immediate superclass. Thus, super( ) always refers to the super class
immediately above the calling class.
class Vehicle{
int maxSpeed = 120;
}
class Car extends Vehicle{
int maxSpeed = 180;
void display() {
SOP("Max Speed: " + super.maxSpeed);
}
}
class Test
{
public static void main(String[] args) {
Car small = new Car();
small.display();
}
}
Inheritance and constructors in java
• In Java, constructor of base class with no argument gets automatically called in
derived class constructor. For example.
class Base {
Base() {
public class Test {
SOP("Base Class Constructor "); public static void main(String[ ] args)
} {
} Derived d = new Derived();
}
class Derived extends Base { }
Derived() {
SOP("Derived Class Constructor ");
} output

} Base Class Constructor


Derived Class Constructor
• Constructor are called in order of their derivation.
class A{
A(){
SOP("A Class Constructor "); public class TestC {
} public static void main(String[ ] args)
} {
C ob = new C( );
class B extends A{ }
B( ) { }
SOP("B Class Constructor ");
output
}
} A class Constructor
B Class Constructor
class C extends B{ C Class Constructor
C( ) {
SOP("C Class Constructor ");
}
}
Important points
• Call to super() must be first statement in Derived(Student) Class
constructor.
• If a constructor does not explicitly invoke a super class constructor,
the Java compiler automatically inserts a call to the no-argument
constructor of the super class. If the super class does not have a no-
argument constructor but a parameterized constructor, you will get
a compile-time error. Object does have such a constructor, so if
Object is the only super class, there is no problem.
• If a subclass constructor invokes a constructor of its super class,
either explicitly or implicitly, you might think that a whole chain of
constructors called, all the way back to the constructor of Object.
This, in fact, is the case. It is called constructor chaining.
Super() for parameterized constructor
class A{
int x; class TestB {
A ( int x) { public static void main(String [ ] args){
this.x = x; B ob = new B(10,20);
} ob.show();
} }
class B extends A{ }
int y;
B( int a, int b) {
super(a);
y = b;
}
void show(){
System.out.println(y + " " + x);
}
}
Types of Inheritance
Multilevel Inheritance
• In Multilevel Inheritance, a derived class will be inheriting a base class and as well
as the derived class also act as the base class to other class.
• In image, the class A serves as a base class for the derived class B, which in turn
serves as a base class for the derived class C.
Example
class Animal{
void eat(){
System.out.println("eating..."); class TestBabyDog{
} public static void main(String args[]){
} BabyDog d=new BabyDog();
class Dog extends Animal{ d.weep();
void bark(){ d.bark();
System.out.println("barking..."); d.eat();
} }
} }
class BabyDog extends Dog{
void weep(){
System.out.println("weeping...");
}
}
class A{
int x;
A ( int x1) {
x = x1;
}
}
class B extends A{ public class TestC1 {
int y; public static void main(String[] args) {
B( int a, int b) { C ob = new C(100,200,300 );
super(a); ob.display();
y = b; }
} }
}
class C extends B{
int z;
C(int a, int b, int c) {
super(a,b);
z = c;
}
void display(){
System.out.println(x + " "+ y+" "+ z);
} }
Hierarchical Inheritance
• In Hierarchical Inheritance, one class serves as a super class (base class) for more
than one sub class.
• In the given image, the class A serves as a base class for the derived class B,C and
D.
class Animal{
void eat(){
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){
SOP("barking...");
}
}
class Cat extends Animal{
void meow(){
SOP("meowing...");
}
}
class Driver{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
}
}
class A{
int x;
void setA ( int x1) {
public class TestC2 {
x = x1;
public static void main(String[] args) {
}
C ob = new C();
}
B ob1 = new B();
class B extends A{
ob1.setA(10);
int y;
ob1.setB(20);
void setB( int b) {
ob1.show();
y = b;
ob.setA(200);
}
ob.setC(100);
void show(){
ob.show();
System.out.println("y = "+ y + "x ="+ x);
}
}
}
}
class C extends A{
int z;
void setC(int c) {
z = c;
}
void show(){
System.out.println("z = "+ z + " x = " + x);
}
}
class Figure {
int side;
Figure(int x) {
side = x;
}
} class TestFigure{
class Square extends Figure{ public static void main(String [] args){
int s1; Rectangle r = new Rectangle(4,4,5);
Square(int n, int x){
super(n); s1 = x; r.display();
} r.area();
void area(){ Square t = new Square(4,5);
System.out.println (s1 * s1);
}
t.display();
void display(){ t.area();
System.out.println("Square :" + side +" "+ s1); }
} }
}
class Rectangle extends Figure{
int l,b;
Rectangle(int n, int x , int y){
super(n); l = x; b = y;
}
void area(){
System.out.println(l * b);
}
void display(){
System.out.println("Rectangle :"+side + " " +l + " " + b );
}
}
Polymorphism

• Polymorphism in Java is a concept by which we can perform a single


action in different ways.
• Polymorphism is derived from two Greek words:
• poly and morphs. The word "poly“ means many and "morphs“ means forms.
So polymorphism means many forms.
• There are two types of polymorphism in Java:
• Compile-time polymorphism. ( Perform by method overloading)
• Runtime polymorphism.( Perform by method overriding)
Method Overriding
• When a method in a subclass has the same name and type signature as a
method in its superclass, then the method in the subclass is said to override the
method in the superclass.
• If subclass (child class) has a method having same signature(name, plus the
number and the type of its parameters) as declared in the parent class, it is
known as method overriding in Java.
• An instance method in a subclass with the same signature (name, plus the
number and the type of its parameters) and return type as an instance method in
the superclass overrides the superclass’s method.
• When an overridden method invoked by the object of a subclass, it will always
refer to the version of the method defined by the subclass.
class A {
int i, j;
A(int a, int b) { class Override {
i = a; j = b; public static void main(String args[]) {
} B subOb = new B(1, 2, 3);
void show() { subOb.show(); // this calls show() in B
SOP("i and j: " + i + " " + j); }
} }
}
class B extends A { output
int k; i and j: 1 2
B(int a, int b, int c) { k: 3
super(a, b); k = c;
}
void show() { If you wish to access the superclass version
super.show(); SOP("k: " + k); of an overridden method, you can do so by
} using super.
}
Method overriding occurs only when the names and the type signatures of the two methods
are identical. If they are not, then the two methods are simply overloaded.
class A {
int i, j;
A(int a, int b) {
i = a; j = b; class Override {
} public static void main(String args[]) {
void show() { B subOb = new B(1, 2, 3);
SOP("i and j: " + i + " " + j);
}
subOb.show(“This is K”); // this
calls show() in B
} subob.show(); // this calls show in A
class B extends A {
int k;
}
B(int a, int b, int c) { }
super(a, b); k = c;
}
void show( String msg) {
SOP(msg+ k);
}
}
Rules for Method Overriding
• Method must have same name as in the parent class and
• The argument list should be exactly the same as that of the overridden method.
• The access level must be same or less restrictive .i.e: If the superclass method is
declared public then the overriding method in the subclass cannot be either
private or protected. While overriding, visibility of a method can be increased but
can not be reduced.
• methods can be overridden only if they are inherited by the subclass.
• Final method cannot be overridden
• A method declared static cannot be overridden
• If a method cannot be inherited, then it cannot be overridden (Private methods
cannot be overridden).
• Constructors cannot be overridden.
class Bank
{
int getRateOfInterest() { class Test2
return 0; {
} public static void main(String args[])
}
{
class SBI extends Bank
SBI s=new SBI();
{
int getRateOfInterest() { ICICI i=new ICICI();
return 8; AXIS a=new AXIS();
} SOP("SBI Rate of Interest: "+ s.getRateOfInterest());
} SOP("ICICI Rate of Interest: "+i.getRateOfInterest());
class ICICI extends Bank SOP("AXIS Rate of Interest: "+a.getRateOfInterest());
{ }
int getRateOfInterest() { }
return 7;
}
}
class AXIS extends Bank output
{
int getRateOfInterest() { SBI Rate of Interest: 8
return 9; ICICI Rate of Interest: 7
} AXIS Rate of Interest: 9
}
class Figure {
double dim1, dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
double area(){
SOP("Area for Figure is undefined.");
return 0;
}
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
double area() {
SOP("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
double area() {
SOP("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class FindAreas {
public static void main(String args[]) {
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
figref = r;
SOP("Area is " + figref.area());
figref = t;
SOP("Area is " + figref.area());
figref = f;
SOP("Area is " + figref.area());
}
}
Difference between Method Overloading and overriding

Method overloading Method overriding

Method overloading is used to increase the Method overriding is used to provide the
readability of the program. specific implementation of the method that is
already provided by its super class.
Method overloading is a compile time Method overriding is a run time polymorphism.
polymorphism.
Method overloading is performed within class. Method overriding occurs in two classes that
have IS-A (inheritance) relationship.
In method overloading ,return type can or Return type must be same or covariant in
cannot be same, but we must have to change method overriding.
the parameter

Here, methods must have same name but While in this, methods must have same name
different signature. and same signature.
Static Binding Vs Dynamic Binding
• Static/Early Binding: The binding which can be resolved at compile
time by compiler is known as static or early binding. Binding of all the
static, private and final methods is done at compile-time .
• Why binding of static, final and private methods is always a static
binding?
• Static binding is better performance wise (no extra overhead is required).
Compiler knows that all such methods cannot be overridden and will always
be accessed by object of local class. Hence compiler doesn’t have any
difficulty to determine object of class (local class for sure). That’s the reason
binding for such methods is static.
Dynamic/Late Binding
• In Dynamic binding compiler doesn’t decide the method to be called. Overriding
is a perfect example of dynamic binding. Binding is done at run time.
classABC{
void print() { class Test{
SOP("print in superclass."); public static void main(String args[]){
} ABC ob = new XYZ( );
} ob.print();
class XYZ extends ABC{ }
void print() { }
SOP("print in superclass.");
}
}
Dynamic Method Dispatch
• Dynamic Method Dispatch is a process in which a call to an overridden method is
resolved at runtime rather than compile-time.
• Through Dynamic method dispatch Java implements run-time polymorphism.
• A superclass reference variable can refer to a subclass object. Java uses this fact
to resolve calls to overridden methods at runtime.
• When an overridden method is called through the reference variable of a
superclass, Java determines which version of that method to execute based
upon the type of the object being referred to at the time the call occurs.
• The type of the object being referred to (not the type of the reference variable)
that determines which version of an overridden method will be executed.
• if a superclass contains a method that is overridden by a subclass, then when
different types of objects are referred to through a superclass reference variable,
different versions of the method are executed.
class Animal { //Driver Class...
public void move() { public class TestDog {
SOP("Animals can move");
public static void main(String args[]) {
}
// Animal reference and object
} Animal a = new Animal();
class Dog extends Animal { // Animal reference but Dog object
public void move() { Animal b = new Dog();
SOP("Dogs can walk and run"); a.move();//call method of Animal class
b.move();// call method in Dog class
}
}
} }
Output:

Animals can move


Dogs can walk and run Note: Base class object can refer to derived class
object but reverse is not true
class Animal { //Driver Class...
void move() { public class TestDog {
SOP("Animals can move");
public static void main(String args[]) {
}
// Animal reference and object
} Animal a = new Animal();
class Dog extends Animal { // Animal reference but Dog object
void move() { Animal b = new Dog();
SOP("Dogs can walk and run"); a.move();//call method of Animal class
b.move();// call method in Dog class
}
a.bark(); // Error
public void bark() { }
SOP("Dogs can bark"); }
}
}
Output:

error: cannot find symbol a.bark();


class A {
class Dispatch {
void callme() {
public static void main(String args[]) {
SOP("Inside A's callme method");
A a = new A();
}
B b = new B();
}
C c = new C();
class B extends A {
A r;
void callme() {
r = a;
SOP("Inside B's callme method");
r.callme(); // calls A's version of callme
}
r = b;
}
r.callme(); // calls B's version of callme
class C extends A {
r = c;
void callme() {
r.callme(); // calls C's version of callme
SOP("Inside C's callme method");
}
}
}
}

output
Inside A's callme method
Inside B's callme method
Inside C's callme method
Upcasting
• Substituting a subclass instance for its superclass is called upcasting.
• The compiler checks for valid upcasting and issues error "incompatible
types" otherwise.
• Upcasting is always safe because a subclass instance possesses all the
properties of its superclass and can do whatever its superclass can do.
class parent{
void display(){
System.out.println("Parent class Method");
}
}
class child extends parent{ Output
void display(){ Child class Method
System.out.println("Child class Method"); Parent class Method
}
}
class Upcasting{
public static void main(String args[]){
parent ob = new child();
ob.display();
parent ob1 = new parent();
ob1.display();
}
}
Final keyword
• The java final keyword can be used in many context.
• Following are different contexts where final is used.
• final variable ( used create a constant variable )
• final method ( Prevent method overriding )
• final class ( Prevent inheritance )
Final Variables
• If you make any variable as final, you cannot change the value of final variable (It
will be constant).
• final variables must be used only for the values that we want to remain constant
throughout the execution of program.
• Example:
• final int THRESHOLD = 5;
• static final double PI = 3.14159;
• It is good practice to represent final variables in all uppercase, using underscore
to separate words.
• We must initialize a final variable, otherwise compiler will throw compile-time error. A
final variable can only be initialized once, either via an initializer or an assignment
statement.
• There are three ways to initialize a final variable :
1. You can initialize a final variable when it is declared.
2. If it is not initialized while declaration( blank final variable).There are two ways to
initialize a blank final variable.
• A blank final variable can be initialized inside instance-initializer block or
initialized inside constructor. If you have more than one constructor in your
class then it must be initialized in all of them, otherwise compile time error will
be thrown.
• A blank final static variable can be initialized inside static block.
• A final variable can be assigned value later, but only once
class FinalDemo{
final int THRESHOLD = 5; // a final variable direct initialize
final int CAPACITY; // a blank final variable
final int MINIMUM; // another blank final variable
static final double PI = 3.141592653589793; // a final static
variable PI
static final double EULERCONSTANT; // a blank final static
variable
// instance initializer block for initializing CAPACITY
{
CAPACITY = 25;
}
// static initializer block for initializing EULERCONSTANT
static{
EULERCONSTANT = 2.3; class Test{
} public static void main(String []args){
// constructor for initializing final variable FinalDemo obj=new FinalDemo();
FinalDemo() { SOP("CAPACITY= "+obj.CAPACITY);
MINIMUM = -1; SOP("EULERCONSTANT= "+obj.EULERCONSTANT);
} SOP("MINIMUM= "+obj.MINIMUM);
} }
}
• A variable can be final and static.
• example:
• final static collegeName=”Silicon”
• The blank final variable can be static, which can be initialized in the static block.
• When a final variable is created inside a method/constructor/block, it is called
local final variable, and it must initialize once where it is created.
class FD{
public static void main(String args[]) {
// local final variable
final int i;
i = 20;
System.out.println(i);
}
}
Final Method
• When a method is declared with final keyword, it is called a final
method.
• A final method cannot be overridden.
• We must declare methods with final keyword for which we required
to follow the same implementation throughout all the derived
classes.
• Since final methods cannot be overridden, a call to one can be
resolved at compile time. This is called early binding. In this way final
provides a performance enhancement.
class Bike {
final void r1() {
System.out.println("running");
}
}
class Honda extends Bike {
output
void r1() { // error since final methods can not be overridden
System.out.println("running safely with 100kmph");
ERROR
}
public static void main(String args[])
{
Honda honda= new Honda();
honda.r1();
}
}
Final class
• When a class is declared as final then it cannot be subclassed i.e. no any other
class can extend it.
• This is particularly useful for creating an immutable class like the predefined
String class.
• Declaring a class as final implicitly declares all of its methods as final too.
• It is illegal to declare a class as both abstract and final since an abstract class is
incomplete by itself and relies upon its subclasses to provide complete
implementations. final class A
{
// methods and fields
}
// The following class is illegal.
class B extends A
{
// ERROR! Can't subclass A
}
Object class
• Object is a special class in java which is the parent/ super class of all
the classes in java by default. In other words, it is the topmost class
of java.
• This means that a reference variable of type Object can refer to an
object of any other class.
• The Object class provides some common behaviors to all the objects
Object class defines the following methods, which means that they are available in every
object:
Example of toString()
class A {
A() {
System.out.println("Constructed A");
}
public String toString() {
return "This is A";
}
}
class B extends A {
B() {
super();
System.out.println("Constructed B");
}
public String toString() {
return "This is B";
}
}
class C extends B {
C() {
super();
System.out.println("Constructed C");
}
public String toString() {
return "This is C";
}
}

public class Test {


public static void main(String[] args) {
A a1 = new A();
System.out.println(a1);
B b1 = new B();
System.out.println(b1);
C c1 = new C();
System.out.println(c1);
}
}
Data Abstraction
• Abstraction is a process of hiding the implementation details and
showing only functionality to the user.
• It shows only important things to the user and hides the internal
details.
• Abstraction lets you focus on what the object does instead of how it
does it.
• There are two ways to achieve abstraction in java
1. Abstract class
2. Interface
Abstract Method
• An abstract method is a method with only signature (i.e., the method
name, the list of arguments and the return type) without
implementation (i.e., without method’s body (without braces, and
followed by a semicolon))
. abstract void moveTo(double deltaX, double deltaY);//no body and abstract
• Keyword abstract is used to declare an abstract method. Example:
• Any class that contains one or more abstract methods must be
declared abstract. public abstract class GraphicObject {
// declare fields
// declare nonabstract methods
abstract void draw();
}
Abstract Method
• An abstract method cannot be declared final, as final method cannot
be overridden. An abstract method, on the other hand, must be
overridden in a subclass before it can be used.
• An abstract method cannot be private (which generates a
compilation error). This is because private method are not visible to
the subclass and thus cannot be overridden.
Abstract class
• A class which is declared as abstract is known as an abstract class.
• abstract keyword in front of the class keyword at the beginning of the class
declaration.
• Example: abstract class A{ }
• It can have abstract and non-abstract methods.
• It needs to be extended and its method implemented. It cannot be
instantiated.
• There can be no objects of an abstract class. That is, an abstract class
cannot be directly instantiated with the new operator. Such objects would
be useless, because an abstract class is not fully defined.
• When an abstract class is subclassed, the subclass usually provides
implementations for all of the abstract methods in its parent class.
However, if it does not, then the subclass must also be declared abstract.
Important point
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
• It can have final methods which will force the subclass not to change
the body of the method.
• An abstract class provides a template for further development.
abstract class A {
abstract void callme();
void callmetoo()
{
outputs
SOP("This is a concrete method.");
} B's implementation of callme.
}
This is a concrete method.
class B extends A {
void callme() {
SOP("B's implementation of callme.");
}
}
class AbstractDemo {
public static void main(String args[])
{
B b = new B();
b.callme();
b.callmetoo();
}
• In Java abstract classes cannot be used to instantiate objects, they can
be used to create object references, because Java’s approach to run-time
polymorphism is implemented through the use of superclass references.
Thus, it must be possible to create a reference to an abstract class so that
it can be used to point to a subclass object.
abstract class Figure {
double dim1, dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
abstract double area();
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) { super(a, b); }
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}
Output
Inside Area for Rectangle.
Area is 45.0
Inside Area for Triangle.
Area is 40.0
• An abstract class can contain constructors in Java. And a constructor
of abstract class is called when an instance of an inherited class is
created.
abstract class Base {
Base() { class Test {
System.out.println("Base Constructor Called"); public static void main(String args[]) {
} Derived d = new Derived();
abstract void fun(); }
} }
class Derived extends Base {
Derived() {
System.out.println("Derived Constructor Called");
} output
void fun() {
Base Constructor Called
System.out.println("Derived fun() called");
Derived Constructor Called
}
}
• We can have an abstract class without any abstract method. This
allows us to create classes that cannot be instantiated, but can only
be inherited.
abstract class Base {
void fun() {
System.out.println("Base fun called");
}
output
}
class Derived extends Base { Base fun called
}
class Test {
public static void main ( String args[] ) {
Derived d = new Derived();
d.fun();
}
}
• Abstract classes can also have final methods (methods that cannot be
overridden). For example, the following program compiles and runs fine.

abstract class Base {


final void fun() {
System.out.println("Derived fun called");
output
}
} Derived fun called
class Derived extends Base {
}
class Test {
public static void main(String args[]) {
Base b = new Derived();
b.fun();
}
}
Interface
• A Java interface is a 100% abstract superclass which define a set of methods its
subclasses must support.
• Interfaces specify what a class must do and not how. Interface in java are like a
contract or protocol which the class have to implement.
• An interface contains only public abstract methods (methods with signature and
no implementation) and possibly constants (public static final variables).
• The implementing objects have to override all the methods of the interface and
provide implementation for all those methods.
• It is used to achieve abstraction and multiple inheritances in Java.
• It cannot be instantiated just like abstract class.
• It is used to achieve abstraction and multiple inheritances in Java.
• Java does not support multiple inheritance among classes, but interfaces allows
java to support this feature.
• keyword interface to define an interface.
Data members of an interface

• Data member defined in an interface are by default public static and


final.
• As they are final they need to be assigned a value.
• Being static they can be accessed directly with the help of an
interface name.
Methods in an interface
• All methods are implicitly public and abstract.
Why Interface
• To achieve total abstraction
• To achieve multiple inheritance
• A subclass, however, can implement more than one interfaces. This is
permitted in Java as an interface merely defines the abstract methods
without the actual implementations and less likely leads to inheriting
conflicting properties from multiple interfaces.
• To achieve loose coupling

• Interfaces are used to implement abstraction. So the question is why do we use


interfaces when we have abstract classes?
• The reason is, abstract classes may contain non-final variables, whereas
variables in interface are final, public and static.
Syntax
access-specifier interface interface_name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}

1. When it is declared as public, the interface can be used by any other code. In this case, the interface must be
the only public interface declared in the file, and the file must have the same name as the interface.
2. Each class that includes an interface must implement all of the methods.
3. Variables can be declared inside of interface declarations. They are implicitly final and static, meaning they
cannot be changed by the implementing class. They must also be initialized. All methods and variables are
implicitly public.
Implementing Interface
• Keywords : implements
• To implement an interface, include the implements clause in a class definition,
and then override the methods defined by the interface.
class classname extends superclass implements interface1 ,interface2, ...
{
// class-body
}

• If a class implements more than one interface, the interfaces are separated with a
comma.
• If a class implements two interfaces that declare the same method, then the
same method will be used by clients of either interface.
• The methods that implement an interface must be declared public. Also, the type
signature of the implementing method must match exactly the type signature
specified in the interface definition.
Example-1
interface Callback {
void callback(int param);
}
class Client implements Callback
{ NOTE: When you implement an
// Implement Callback's interface interface method, it must be declared
public void callback(int p) { as public.
System.out.println("callback called with " + p);
}
}
class Test {
psvm(String args [] ){
client c = new Client();
c.callback(20);
}
}
interface Shape {
double getArea();
}
class Rectangle implements Shape {
private int length;
private int width;
Rectangle(int length, int width) {
this.length = length;
this.width = width;
}
public String toString() {
return "Rectangle[length=" + length + ",width=" + width + "]";
}
public double getArea() {
return length * width;
}
}
class Triangle implements Shape {
private int base;
private int height;
Triangle(int base, int height) {
this.base = base;
this.height = height;
}
public String toString() {
return "Triangle[base=" + base + ",height=" + height + "]";
} Rectangle[length=1,width=2]
public double getArea() { Area is 2.0
return 0.5 * base * height; Triangle[base=3,height=4]
} Area is 6.0
}
class TestShape {
public static void main(String[] args) {
Shape s;
s = new Rectangle(1, 2); // upcast
System.out.println(s);
System.out.println("Area is " + s.getArea());
s = new Triangle(3, 4); // upcast
System.out.println(s);
System.out.println("Area is " + s.getArea());
//Shape s3 = new Shape("green"); // Compilation Error!!
}
}
• It is permissible for classes that implement interfaces to define
additional members of their own.
• It is possible to create a reference variable of type interface. Any
instance of any class that implements the declared interface can be
referred to by such a variable.
• When you call a method through one of these references, the correct
version will be called based on the actual instance of the interface being
referred to.
• The method to be executed is looked up dynamically at run time.
• Dynamic lookup of a method at run time incurs a significant overhead
when compared with the normal method invocation in Java
interface Callback {
void callback(int param); output
}
callback called with 42
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
Note: In the above program although ‘c’ is
void example(){
System.out.println("Inside Example"); used to access the callback() method, it
} cannot access any other members of the
} Client class. An interface reference variable
class TestIface { only has knowledge of the methods
public static void main(String args[]) { declared by its interface declaration.
Callback c = new Client();
c.callback(42);
//c.example();
}
}
class AnotherClient implements Callback
{
// Implement Callback's interface output
public void callback(int p) {
callback called with 42
System.out.println("Another version of callback");
Another version of callback
System.out.println("p squared is " + (p*p)); p squared is 1764
}
}
class TestIface2 {
public static void main(String args[]) {
Callback c = new Client();
AnotherClient ob = new AnotherClient(); Note: As you can see, the version of
c.callback(42); callback( ) that is called is determined by
c = ob; // c now refers to AnotherClient object the type of object that c refers to at run
c.callback(42); time.
}
}
Partial Implementation
• If a class includes an interface but does not fully implement the
methods defined by that interface, then that class must be declared as
abstract.
abstract class Incomplete implements Callback {
int a, b; Note: The class Incomplete does not
void show() { implement callback( ) and must be declared
System.out.println(a + " " + b); as abstract. Any class that inherits the class
} Incomplete must implement callback( ) or be
// ... declared abstract itself.
}
Nested Interface
• An interface can be declared a member of a class or another
interface. Such an interface is called a member interface or a nested
interface.
• A nested interface can be declared as public, private, or protected.
This differs from a top-level interface, which must either be declared
as public or use the default access level.
• When a nested interface is used outside of its enclosing scope, it
must be qualified by the name of the class or interface of which it is
a member.
class A {
interface NestedIF {
boolean isNotNegative(int x);
}
}
// B implements the nested interface.
class B implements A.NestedIF {
output
public boolean isNotNegative(int x) {
return x < 0 ? false : true; 10 is not negative
}
}
class NestedIFDemo {
public static void main(String args[]) {
// use a nested interface reference
A.NestedIF nif = new B();
if(nif.isNotNegative(10))
System.out.println("10 is not negative");
if(nif.isNotNegative(-12))
System.out.println("this won't be displayed");
}
}
• We can use interfaces to import shared constants into multiple classes by simply
declaring an interface that contains variables that are initialized to the desired
values. When you include that interface in a class, all of those variable names
will be in scope as constants.
Extending Interface
• One interface can inherit another by using the keyword extends. The
syntax is the same as for inheriting classes.
• When a class implements an interface that inherits another
interface, it must provide implementations for all methods defined
within the interface inheritance chain.
interface A {
void meth1();
void meth2();
}
interface B extends A {
void meth3();
}
class MyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");
}
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1(); ob.meth2(); ob.meth3();
}
}
Default interface Method
• Before Java 8, interfaces could have only abstract methods .
• The implementation of these methods has to be provided in a
separate class. So, if a new method is to be added in an interface then
its implementation code has to be provided in the class implementing
the same interface.
• To overcome this issue, Java 8 has introduced the concept of default
methods which allow the interfaces to have methods with
implementation without affecting the classes that implement the
interface.
interface TestInterface {
// abstract method
public void square(int a);
// default method
default void show() {
System.out.println("Default Method Executed");
}
}
class TestClass implements TestInterface {
// implementation of square abstract method
public void square(int a) {
System.out.println(a*a);
}
public static void main(String args[]) {
TestClass d = new TestClass();
d.square(4);
d.show();// default method executed
}
}
static method in interface
• JDK 8 added another new capability to interface: the ability to define one or
more static methods. Like static methods in a class, a static method defined by
an interface can be called independently of an object.
• Syntax of calling a static method: InterfaceName.staticMethodName
interface TestInterface {
// abstract method
public void square (int a);
// static method
static void show() {
System.out.println("Static Method Executed");
}
}
class TestClass implements TestInterface {
public void square (int a) {
System.out.println(a*a);
}
public static void main(String args[]) {
TestClass d = new TestClass();
d.square(4);
// Static method executed
TestInterface.show();
}
}
Packages
• A java package is a group of similar types of classes, interfaces and
sub-packages.
• Package in Java is a mechanism to encapsulate a group of classes, sub
packages and interfaces.
• Package in java can be categorized in two form, built-in package and
user-defined package.
• We should put related classes into packages.
• There are many built-in packages such as java, lang, awt, javax,
swing, net, io, util, sql etc.
Advantage of java package
• Java package removes naming collision.
• Example: We can be two classes with name Employee in two packages,
college.staff.cse.Employee and college.staff.ee.Employee.
• For example there can be two classes with same name in two packages.
• Making searching/locating and usage of classes, interfaces are easier
• Java package provides access protection: protected and default have package
level access control. A protected member is accessible by classes in the same
package and its subclasses. A default member (without any access specifier) is
accessible by classes in the same package only.
• Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
• Packages can be considered as data encapsulation (or data-hiding).
Defining Packages
• To create a package, include a package command as the first statement in a Java source
file. Any classes declared within that file will belong to the specified package.
• The package statement defines a name space in which classes are stored. If you omit the
package statement, the class names are put into the default package, which has no
name.
• This is the general form of the package statement:
Syntax: package pkgName;
Example: package MyPackage;
• Java uses file system directories to store packages. For example, the .class files for any
classes you declare to be part of MyPackage must be stored in a directory called
MyPackage.
• More than one file can include the same package statement. The package statement
simply specifies to which package the classes defined in a file belong.
• We can create a hierarchy of packages. To do so, simply separate each package name
from the one above it by use of a period. The general form of a multileveled package
statement is shown here: package pkg1.pkg2.pkg3;
Steps to create a Java package
• Come up with a package name
• Pick up a base directory
• Make a subdirectory from the base directory that matches your package name.
• Place your source java files into the package subdirectory.
• Use the package statement in each source file.
• Compile your source files from the base directory.
• Run your program from the base directory.
Cont….
• Step1: Make a subdirectory from the base directory that matches your package
name.
• Step2: Define a class in a java file say A.java and include the first instruction as
package package-name;
package myPkg;
public class A{
……
A.java
…..
}

• Save this file under the directory myPkg, which is the subdirectory of base
directory
Cont….
• Step3: Compile the A.java File( Objective is to place the A.class file
inside the package myPkg)
• Step4:Create the source file under the base directory
(say pp.java)
• Step5: Import the package myPkg.A inside the file(pp.java)
• Step6: Compile and execute the source file

Easy Way to Run: The easiest way to run a program having package is to simply create
the package directories below your current development directory, put the .class files
into the appropriate directories, and then execute the programs from the development
directory.
package MyPack;
class Balance {
String name; double bal;
Balance(String n, double b) {
name = n;
Compile the program under the current directory
bal = b;
in normal way. Create a directory with the name
}
MyPack. Keep the .class files (both Balance.class
void show() {
and AccountBalance.class) of this program under
if(bal<0)
the folder MyPack. Run the program using
System.out.print("--> ");
command java MyPack.AccountBalance by staying
System.out.println(name + ": $" + bal);
just above MyPack folder.
}
class AccountBalance {
public static void main(String args[]) {
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
output
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33); K. J. Fielding: $123.23
for(int i=0; i<3; i++) Will Tell: $157.02
current[i].show(); --> Tom Jackson: $-12.33
}
}
Access package from another package?
• There are three standard ways to access the package from outside the package.
• import package.*;

• import package.classname;

• fully qualified name.


• import package.*;
• If you use import package.* then all the classes and interfaces of this package
will be accessible but not subpackages.
• import package.classname;
• If you import package.classname then only declared class of this package
will be accessible.
• fully qualified name.
• If you use fully qualified name then only declared class of this package will
be accessible.
• But you need to use fully qualified name every time when you are accessing
the class or interface.
• It is generally used when two packages have same class name e.g. java.util
and java.sql packages contain Date class.
Myclass.java
// Name of the package must be same as the directory First we create a directory myPackage
// under which this file is saved (name should be same as the name of
package myPackage; the package). Then create the
public class MyClass MyClass inside the directory with the
{ first statement being the package
public void getNames(String s) { name.
System.out.println(s); NOTE: MyClass.java must be saved
} inside the myPackage directory since
} it is a part of the package.
PrintName.java
import myPackage.MyClass;
public class PrintName {
public static void main(String args[]) {
// Initializing the String variable with a value
String name = "GeeksforGeeks";
// Creating an instance of class MyClass in the package.
MyClass obj = new MyClass();
obj.getNames(name);
}
}
Access Protection
• Java addresses four categories of visibility for class members:
 Subclasses in the same package
 Non-subclasses in the same package
 Subclasses in different packages
 Classes that are neither in the same package nor subclasses
• The three access specifiers, private, public, and protected, provide a variety of ways to produce
the many levels of access required by these categories. The following table sums up the
interactions:
• Anything declared public can be accessed from anywhere.
• Anything declared private cannot be seen outside of its class.
• When a member does not have an explicit access specification, it is visible to subclasses as well as
to other classes in the same package. This is the default access.
• If you want to allow an element to be seen outside your current package, but only to classes that
subclass your class directly, then declare that element protected.
//Save the following code in Protection.java
package p1;
public class Protection {
int n = 1;
private int n_pri = 2;
protected int n_pro = 3;
public int n_pub = 4;
public Protection() {
System.out.println("base constructor");
System.out.println("n = " + n);
System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
//Save the following code in Derived.java:
package p1;
class Derived extends Protection {
Derived() {
System.out.println("derived constructor");
System.out.println("n = " + n);
// class only System.out.println("n_pri = "4 + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}

//Save the following code in SamePackage.java:


package p1;
class SamePackage {
SamePackage() {
Protection p = new Protection();
System.out.println("same package constructor");
System.out.println("n = " + p.n);
// class only System.out.println("n_pri = " + p.n_pri);
System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}
//Save the following code in Protection2.java:
package p2;
class Protection2 extends p1.Protection {
Protection2() {
System.out.println("derived other package constructor");
// class or package only
// System.out.println("n = " + n);
// class only
// System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
//Save the following code in OtherPackage.java:
package p2;
class OtherPackage {
OtherPackage() {
p1.Protection p = new p1.Protection();
System.out.println("other package constructor");
// class or package only
// System.out.println("n = " + p.n);
// class only
// System.out.println("n_pri = " + p.n_pri);
// class, subclass or package only
// System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}
//Save the following code in Demo.java:
package p1;
// Instantiate the various classes in p1.
public class Demo {
public static void main(String args[]) {
Protection ob1 = new Protection();
Derived ob2 = new Derived();
SamePackage ob3 = new SamePackage();
}
}
Importing a Package
• To use a package in Java we need to import that by using import statement.
• In C/C++ if we include a header file in a program, during compilation the #include directive makes
the compiler go to the standard library and copies the entire header file contents into program.
As a result the program size increases unnecessarily wasting memory and processor’s time. When
a class name or a method name is used in a Java, the import statement makes the JVM goes to
the Java standard library, executes the code there, comes back and substitutes the result in that
place of the program. Thus, the Java program size is not increased.
• In a Java source file, import statements occur immediately following the package statement (if it
exists and before any class definitions.
• Since classes within packages must be fully qualified with their package name or names, it could
become tedious to type in the long dot-separated package path name for every class you want to
use.
• For this reason, Java includes the import statement to bring certain classes, or entire packages,
into visibility.
• Once imported, a class can be referred to directly, using only its name.
Importing Packages
• import pkg1[.pkg2].(classname | *);
• import java.util.Date;
• import java.io.*;
• The * form may increase compilation time—especially if you import several large packages.
• For this reason it is a good idea to explicitly name the classes that you want to use rather than
importing whole packages.
• However, the * form has absolutely no effect on the run-time performance or size of your
classes.
• There are no core Java classes in the unnamed default package
• All of the standard classes are stored in some named package
• All of the standard Java classes included with Java are stored in a package called java.
• The basic language functions are stored in a package inside of the java package called java.lang.
• Normally, you have to import every package or class that you want to use, but since Java is
useless without much of the functionality in java.lang, it is implicitly imported by the compiler for
all programs..
• When a package is imported, only those items within the package declared as public will be available to non-
subclasses in the importing code.

package MyPack; import MyPack.*;


Public class Balance { class TestBalance {
String name; public static void main(String args[]) {
double bal; Balance test = new Balance("J. J. Jaspers", 99.88);
test.show(); // you may also call show()
public Balance(String n, double b) {
}
name = n; bal = b; }
}
public void show() {
if(bal<0)
Note: Here the Balance class is now public. Also, its
System.out.print("--> "); constructor and its show() method are public, too. This
System.out.println(name + ": $" + bal); means that they can be accessed by any type of code outside
} the MyPack package. For example, here TestBalance imports
} MyPack and is then able to make use of the Balance class.
Subpackage
• Packages that are inside another package are the subpackages.
• These are not imported by default, they have to imported explicitly.
• Members of a subpackage have no access privileges, i.e., they are considered as
different package for protected and default access specifiers. i.e., they are
considered as different package for protected and default access specifiers.
• import package.*;// All the classes and interfaces of this package will be
accessible but not subpackages.
Example of creating Subpackage
package myPkg.subPkg
public class MyClass{
public void fun(){
System.out.println("I am inside subpackage");
}
}

import myPkg.subPkg.MyClass;
class Driver{
public static void main(String args[]){
MyClass ob=new MyClass();
ob.fun();
}
}
Note
1. Every class is part of some package.
2. If no package is specified, the classes in the file goes into a special unnamed package (the same
unnamed package for all files).
3. All classes/interfaces in a file are part of the same package. Multiple files can specify the same
package name.
4. If package name is specified, the file must be in a subdirectory called name (i.e., the directory
name must match the package name).
5. We can access public classes in another (named) package using: package-name.class-name.
Exception Handling
Dr. Kasturi Dhal
Department of CSE
Silicon Institute of Technology

[email protected]
Error
• While we are solving any problem, we generally come across the following three
types of error.
1. Syntax Error : During compilation
2. Runtime Error : It occurs at run time ( i.e. Input error )
3. Logic Error: Poor understanding of the problem.
Exception
• Exception is a run time error, which arises during the execution of program.
• When an exception occurs the normal flow of the program is interrupted and the
program is terminate abnormally.
• Exception can occur in many different reasons:
1. User entered invalid data
2. File not found
3. Network connection has been lost
4. JVM has run out of memory
• An exception is an unwanted or unexpected event, which occurs during the execution of
a program i.e. at run time, which disrupts the normal flow of the program’s instructions.
• A Java exception is an object that describes an exceptional (that is, error) condition that
has occurred in a piece of code.
Exception Handling
• The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors such as ClassNotFound, IO, SQL, Remote etc.
• so that the normal flow of the application can be maintained.
• Advantage of exception handling is to maintain normal flow of application.
• Example: Suppose there are 5 statements in a program and there occurs an
exception at statement number 3, rest of the code will not be executed i.e.
statement 4, 5 will not run. If we perform exception handling, rest of the
statement will be executed. That is why we use exception handling in java.
• All exception types are subclasses of the built-in class Throwable.
• Below Throwable there are two subclasses that partition exceptions into two distinct
branches. One branch is headed by Exception.
• This class is used for exceptional conditions that user programs should catch. This is also
the class that you will subclass to create your own custom exception types.
• One of the important subclass of Exception, called Runtime Exception. Exceptions of this
type are automatically defined for the programs that you write and include things such
as division by zero and invalid array indexing etc.
• The other branch (of Throwable) is topped by Error, which defines exceptions that are
not expected to be caught under normal circumstances by your program. Exceptions of
type Error are used by the Java run-time system to indicate errors having to do with the
run-time environment, itself. Stack overflow is an example of such an error.
All exception classes are subtypes of the
java.lang.Exception class.
The exception class is a subclass of the
Throwable class.
Other than the exception class there is
another subclass called Error which is
derived from the Throwable class. Errors
are abnormal conditions that happen in
case of severe failures, these are not
handled by the java programs. Errors are
generated to indicate errors generated by
the runtime environment.
The Exception class has two main
subclasses: IOException class and
RuntimeException Class.
Exception describes errors caused by your program
and external circumstances. These errors can be Runtime Exception is caused by
caught programming errors, such as bad
and handled by your program. casting, accessing an out-of-bounds

System errors are thrown by JVM and


represented in the Error class. The Error
class describes internal system errors.
Such errors rarely occur. If one does,
there is little you can do beyond notifying
the user and trying to terminate the
program gracefully.
Keyword used to handle exception
• Java provides five keywords that are used to handle the exception.
1. try
2. catch
3. throw
4. throws
5. finally
try Block
• Program statement that you want to monitor for exception are contained within
try block.
• Synatx: try {
// Protected code
}

• If an exception occurs within the try block, it is thrown.


• If an exception occurs at the particular statement in the try block, the rest of the
block code will not execute. So, it is recommended not to keep the code in try
block that will not throw an exception.
• Java try block must be followed by either catch or finally block.
Catch Block
• catch block is the handler, which catch the exception and handle it in some
rational manner.
• The "catch" block is used to handle the exception.
• It must be preceded by try block which means we can't use catch block alone.
• It can be followed by finally block later.
• Syntax: catch (ExceptionName e1) {
// Catch block
}
• If an exception occurs within the try block, it is thrown.
• Our code can catch this exception (using catch) and handle it in some rational
manner.
• System-generated exceptions are automatically thrown by the Java run-time
system.
General Format
try{
.....
}
catch(Exception type1 exob ){
.......
}
catch(Exception type2 exob ){
.......
}
…………….
finally{
.......
}
Uncaught exception
class Test{ output
public static void main(String []args){
java.lang.ArithmeticException: / by zero
int d=0; at Exc0.main(Exc0.java:4)
int a=20/d;
}
}

• When the Java run-time system detects the attempt to divide by zero, it constructs a new
exception object and then throws this exception.
• This causes the execution to stop, because once an exception has been thrown, it must be caught
by an exception handler and dealt with immediately.
• As we have not supplied any exception handlers of our own, so the exception is caught by the
default handler provided by the Java run-time system.
• Any exception that is not caught by your program will ultimately be processed by the default
handler. The default handler displays a string describing the exception, prints a stack trace from
the point at which the exception occurred, and terminates the program.
Using try and catch
The user should handle his/her exceptions because of two reasons:
o it allows you to fix the error.
o it prevents the program from automatically terminating.

class Test{
public static void main(String []args){
int d,a; output
try {
Division by zero.
d=0;
After catch statement.
a=20/d;
}
catch(ArithmeticException ob){
System.out.println(“Divided by zero”);
}
System.out.println(“After catch exception block”);
}
}
• Enclose the code that you want to monitor inside a try block.
• Immediately following the try block, include a catch clause that specifies the
exception type that you wish to catch.
• Once an exception is thrown, program control transfers out of the try block into
the catch block.
• Once the catch statement has executed, program control continues with the next
line in the program following the entire try/catch block.
• A try and its catch statement form a unit.
• A catch statement cannot catch an exception thrown by another try statement
(except in the case of nested try statements).
• The statements that are protected by try must be surrounded by curly braces.
• The goal of most well-constructed catch clauses should be to resolve the
exceptional condition and then continue on as if the error had never happened.
import java.util.Random;
class HandleError {
public static void main(String args[]) {
int a=0, b=0, c=0;
Random r = new Random();
for(int i=0; i<32000; i++) {
try {
b = r.nextInt();
c = r.nextInt();
a = 12345 / (b/c);
}
catch (ArithmeticException e) {
System.out.println("Division by zero.");
a = 0; // set a to zero and continue
}
System.out.println("a: " + a);
}
}
}
Multiple Catch clause
• In some cases, more than one exception could be raised by a single piece of code.
• To handle this type of situation, we can specify two or more catch clauses, each catching a
different type of exception.
• 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.
• When an exception is thrown, each catch statement is inspected in order, and the first one whose
type matches that of the exception is executed.
• After one catch statement executes, the others are bypassed, and execution continues after the
try/catch block.
• When you use multiple catch statements, it is important to remember that exception subclasses
must come before any of their superclasses. Otherwise a catch statement that uses a superclass
will catch exceptions of that type plus any of its subclasses.
• Thus, a subclass would never be reached if it came after its superclass. In that case Java will show
error since unreachable code is an error in Java.
• 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.
ArrayIndexOutOfBounds Exception occurs rest of the code
class Test{
public static void main(String[] args) {
try{
int a[]=new int[5];
System.out.println(a[10]);
}
catch(ArithmeticException e) {
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e) {
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

ArrayIndexOutOfBounds Exception occurs


rest of the code
Class MultiCatch {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println(“a = “ + a);
int b = 42 / a;
int c[] = {1};
c[42] = 99;
}
catch(ArithmeticException e){
System.out.println(“Divide by 0: “ + e);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println(“Array index oob: “ + e);
}
System.out.println(“After try/catch blocks.”);
}
}

java MultiCatch java MultiCatch TestArg


a=0 a=1
Divide by 0: java.lang.ArithmeticException: / by zero Array index oob: java.lang.ArrayIndexOutOfBoundsException:42
After try/catch blocks. After try/catch blocks.
class Test{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
Compile-time error
catch(Exception e){

System.out.println("common task completed");


}
catch(ArithmeticException e){
System.out.println("task1 is completed");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("task 2 completed");
}
System.out.println("rest of the code...");
}
}
Class SuperSubCatch {
public static void main(String args[]) {
try {
int a = 0;
int b = 42/a;
}
catch(Exception e) {
System.out.println(“Generic Exception catch.”);
}
catch(ArithmeticException e) {
System.out.println(“This is never reached.”);
}
}
}
Nested try statements
• A try statement can be nested inside the block of another try.
• Each time a try statement is entered, the context of that exception is pushed on
the stack. If an inner try statement does not have a catch handler for a particular
exception, the stack is unwound and the next try statement’s catch handlers are
inspected for a match. This continues until one of the catch statements succeeds,
or until all of the nested try statements are exhausted.
• If no catch statement matches, then the Java run-time system will handle the
exception.
Class NestTry {
public static void main(String args[]) {
java NestTry
try {
Divide by 0:
int a = args.length;
java.lang.ArithmeticException: /
int b = 42 / a;
by zero
System.out.println(“a = “ + a);
try {
if(a==1)
java NestTry One
a = a/(a-a);
a=1
if(a==2) {
Divide by 0:
int c[] = { 1 };
java.lang.ArithmeticException:
c[42] = 99;
/ by zero
}
}
catch(ArrayIndexOutOfBoundsException e){ java NestTry One Two
System.out.println(“Array index out-of-bounds:”+ a=2
e); Array index out-of-bounds:
} java.lang.ArrayIndexOutOfBoun
} dsException:42
catch(ArithmeticException e) {
System.out.println(“Divide by 0: “ + e);
}
}
}
• We can enclose a call to a method within a try block. Inside that method is another try statement.
In this case, the try within the method is still nested inside the outer try block, which calls the
method.
class MethNestTry { public static void main(String args[]) {
static void nesttry(int a) { try {
try { int a = args.length;
if(a==1) int b = 42 / a;
a = a/(a-a); System.out.println(“a = “ + a);
if(a==2) { nesttry(a);
int c[] = {1}; }
c[42] = 99; catch(ArithmeticException e) {
} Sop(“Divide by 0: “ + e);
} }
catch(ArrayIndexOutOfBoundsException e) { }
Sop(“Array index out-of-bounds:”+ e); }
}
}

java NestTry One java NestTry One Two


java NestTry
a=1 a=2
Divide by 0:
Divide by 0: Array index out-of-bounds:
java.lang.ArithmeticException: /
java.lang.ArithmeticException: java.lang.ArrayIndexOutOfBoun
by zero
/ by zero dsException:42
public class NestedTryBlock2 {
public static void main(String args[]) {
try {
try {
try {
int arr[] = { 1, 2, 3, 4 };
System.out.println(arr[10]);
}
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println(" inner try block 2");
} Java.lang.ArrayIndexOutOfBoundsExcetio
}
catch (ArithmeticException e) {
n: Index 10 out of bounds for length 4
System.out.println("Arithmetic exception"); outer (main) try block
System.out.println("inner try block 1");
}
}
catch (ArrayIndexOutOfBoundsException e4) {
System.out.print(e4);
System.out.println(" outer (main) try block");
}
catch (Exception e5) {
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
}
}
finally
• Any code that must be executed after a try block complete is put in a finally block.
• The finally block always executes when the try block exits.
• This ensures that the finally block is executed even if an unexpected exception occurs.
• finally block in Java can be used to put "cleanup" code such as closing a file, closing connection, etc.
• The important statements to be printed can be placed in the finally block.
• The keyword finally creates a block of code that will be executed after a try/catch block has completed and
before the code following the try/catch block.
• The finally block will execute whether or not an exception is thrown.
• If an exception is thrown, the finally block will execute even if no catch statement matches the exception.
• Any time a method is about to return to the caller from inside a try/catch block, via an uncaught exception
or an explicit return statement, the finally clause is also executed just before the method returns.
• The finally clause is optional. For each try block there can be zero or more catch blocks, but only one finally
block.
• However, each try block requires at least one catch or a finally clause.
• Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
class TestFinallyBlock {
public static void main(String args[]){
try{
int data=25/5; 5
System.out.println(data); finally block is always executed
} Rest of the code…
catch(NullPointerException e){
System.out.println(e);
}
finally {
System.out.println("finally block is always executed");
}
System.out.println(“Rest of the code...");
}
}
class TestFinallyBlock {
public static void main(String args[]){
try{
System.out.println(“Inside try”); Inside try
int data=25/0; finally block is always executed
System.out.println(data); Exception in thread “main”
} java.lang.ArithmeticException: /
catch(NullPointerException e){ by zero at TestFinallyBlock
System.out.println(e); .main(TestFinallyBlock.java:5)
}
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
class TestFinallyBlock {
public static void main(String args[]){
try{
System.out.println(“Inside try”); Inside try
int data=25/0; Exception handled
System.out.println(data); java.lang.ArithmeticException: /
} by zero
catch(ArithmeticException e){ finally block is always executed
System.out.println(“Exception handled”); Rest of the code……
System.out.println(e);
}
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Class FinallyDemo{
static void procA() {
try {
public static void main(String args[]) {
System.out.println(“inside procA”);
throw new RuntimeException(“demo”); try {
} procA();
finally { }
System.out.println(“procA’s finally”); catch (Exception e) {
} SOP(“Exception caught”);
} }
static void procB() { procB();
try {
procC();
System.out.println(“inside procB”);
return; }
} }
finally {
System.out.println(“procB’s finally”);
}
} output
static void procC() { inside procA
try {
System.out.println(“inside procC”);
procA’s finally
} Exception caught
finally { inside procB
System.out.println(“procC’s finally”); procB’s finally
} inside procC
} procC’s final
throw
• The throw keyword in Java is used to explicitly throw an exception from a method or any block of code.
• We can throw either checked or unchecked exception.
• Syntax: throw ThrowableInstance
• throw new exception_class(“error message”);
• Example:
• throw new ArithmeticException("/ by zero");
• Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
• There are two ways you can obtain a Throwable object:
• using a parameter in a catch clause, or
• creating one with the new operator
• The flow of execution stops immediately after the throw statement; any subsequent statements are not
executed.
• The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of
exception.
• If it does find a match, control is transferred to that statement. If not, then the next enclosing try statement
is inspected, and so on.
• If no matching catch is found, then the default exception handler halts the program and prints the stack
trace.
• If we throw a checked exception using throw keyword, it is must to handle the exception using catch block
or the method must declare it using throws declaration.
Throwing an unchecked Exception
class TestThrow1 {
public static void validate(int age) {
if(age<18) {
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
System.out.println(“Rest of the code……”);
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}

Exception in thread "main" java.lang.ArithmeticException: Person is not eligible to vote


at TestThrow1.validate(test.java:6)
at TestThrow1.main(test.java:15)
Class ThrowDemo {
static void demoproc() {
try {
output
throw new NullPointerException(“demo”);
}
Caught inside demoproc.
catch(NullPointerException e) {
Recaught:
System.out.println(“Caught inside demoproc.”);
java.lang.NullPointerException: demo
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
}
catch(NullPointerException e) {
System.out.println(“Recaught: “ + e);
}
}
}
• In the above program new is used to construct an instance of NullPointerException.
• While creating the instance it is calling the constructor by sending a string as parameter which describes the exception.
• This string is displayed when the object is used as an argument to print( ) or println( ). It can also be obtained by a call to
getMessage( ), which is defined by Throwable.
throws
• The "throws" keyword is used to declare exceptions.
• It specifies that there may occur an exception in the method.
• It doesn't throw an exception. It is always used with method signature.
• If a method is capable of causing an exception that it does not handle, it must specify this
behavior so that callers of the method can guard themselves against that exception.
• A throws clause lists the types of exceptions that a method might throw.
• This is necessary for all exceptions, except those of type Error or RuntimeException, or
any of their subclasses. All other exceptions that a method can throw must be declared
in the throws clause. If they are not, a compile-time error will result.
• Any method that can throw exceptions, it is mandatory to use the throws keyword to list
the exceptions that can be thrown.
• Syntax:
• return type method_name (arguments) throws Exception1, Exception2, … { ….. }
import java.io.*;
class ABC{
void fun()throws IOException{ Anybody call this function need to
throw new IOException(); placed in try block and put the
} handler,
}
otherwise compile time error
class Test{
public static void main(String []args){
ABC ob=new ABC();
ob.fun();
System.out.println("Smooth execution");
}
}

Compile time error:


ThrowsExample.java:17: unreported exception java.io.IOException; must be caught or
declared to be thrown
ob.fun(); ^
1 error
Corrected Code
import java.io.*;
class ABC{
void fun()throws IOException{
throw new IOException();
}
}
class Test{
public static void main(String []args){
ABC ob=new ABC();
try {
ob.fun();
}
catch(IOException e)
{
SOP( “Error caught “ + e);
}
System.out.println("Smooth execution");
}
}
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
}
catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
output
inside throwOne
caught java.lang.IllegalAccessException: demo
Difference between throw and throws
Throw Throws
The throw keyword is used inside a function. It The throws keyword is used in the function
is used when it is required to throw an signature. It is used when the function has
Exception logically. some statements that can lead to exceptions.
The throw keyword is used to throw an The throws keyword can be used to declare
exception explicitly. It can throw only one multiple exceptions, separated by a comma.
exception at a time. Whichever exception occurs, if matched with
the declared ones, is thrown automatically
then.
Syntax of throw keyword includes the instance Syntax of throws keyword includes the class
of the Exception to be thrown. Syntax wise names of the Exceptions to be thrown. Syntax
throw keyword is followed by the instance wise throws keyword is followed by exception
variable. class names.
is only used to propagate the unchecked throws keyword is used to propagate the
Exceptions checked Exceptions only.
We are allowed to throw only one exception at a We can declare multiple exceptions using throws
time i.e. we cannot throw multiple exceptions. keyword that can be thrown by the method. For
example, main() throws IOException, SQLException.
Types of Exception
• There are mainly two types of exceptions: checked and unchecked.
An error is considered as the unchecked exception. However,
according to Oracle, there are three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error: It is Irrecoverable
Checked Exception
• Checked exception are the exceptions that are checked at compile time.
• 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.
• If some code within a method throws a checked exception, then the method
must either handle the exception or it must specify the exception using throws
keyword.
import java.io.*;
class Main {
Public static void main(String[] args) throwsIOException {
FileReader file = new FileReader(“a.txt”);
BufferedReader fileInput = new BufferedReader(file);
// Print first 3 lines of file “a.txt”
for(int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());
fileInput.close();
}
}

FileReader() method which throws a checked exception FileNotFoundException. It also uses readLine()
and close() methods, and these methods also throw checked exception IOException.
Checked Exception in java.lang
Exception Meaning
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that does not
implement the Cloneable interface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class
or interface.
InterruptedException One thread has been interrupted by another
thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.
Unchecked Exception
• These exceptions are not checked at compiled time but they are checked at
runtime.
• The classes which inherit RuntimeException are known as unchecked exceptions
e.g.ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
etc.
• In Java exceptions under Error and RuntimeException classes are unchecked
exceptions, everything else under Throwable is checked.
class Main {
public static void main(String args[]) {
int x = 0;
int y = 10;
int z = y/x;
}
}
Unchecked Exception in java.lang
Creating your own Exception
• To create the custom exception , it must be derived from Exception class
• If we want to create our own exception types to handle situations specific to our
applications, we need to just define a subclass of Exception (which is, of course, a
subclass of Throwable).
• All exceptions, including those that we create, have methods defined by
Throwable available to them.
Creating your own Exception
class MyException extends Exception {
public MyException(String s) {
// Call constructor of parent Exception
super(s);
}
}

public class Test {


public static void main(String args[]) {
try{
throw new MyException("User Defind Error");
}
catch (MyException ex) {
System.out.println("Caught");
System.out.println(ex.getMessage());
}
}
}
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}
class Test{
public static void main(String args[]){
int age;
Scanner ob =new Scanner(System.in);
System.out.println("Entaer age");
age=ob.nextInt();
try{
if(age<18)
throw new InvalidAgeException("You can't Cast the vote");
else
SOP("welcome to vote");
}//End of try block
catch(Exception m){
SOP("Exception occured: "+m);
}
System.out.println("rest of the code...");
}
}
class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
public String toString() { output
return "MyException[" + detail + "]";
}
Called compute(1)
}
class ExceptionDemo { Normal exit
static void compute(int a) throws MyException { Called compute(20)
System.out.println("Called compute(" + a + ")"); Caught MyException[20]
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20);
}
catch (MyException e) {
System.out.println("Caught " + e);
}
}
}
Multi Threading
Multitasking
• Multitasking is a process of executing multiple tasks simultaneously.
• It is used for maximum utilization of CPU.
• Multitasking can be achieved in two ways.
• Process-based Multitasking (Multiprocessing)
• Thread-based Multitasking (Multithreading)
Process Based Multi Tasking
• Process-based multitasking is the feature that allows your computer to run two
or more programs concurrently. A program is the smallest unit of code that can
be dispatched by the scheduler.
• Example: Run the Java compiler at the same time that you are using a text editor.
Thread Based MultiTasking
• In a thread-based multitasking environment, the thread is the smallest unit of dispatchable code.
This means that a single program can perform two or more tasks simultaneously.
• Example: A text editor can format text at the same time that it is printing, as long as these two
actions are being performed by two separate threads.
• Multitasking threads require less overhead than multitasking processes.
• Processes are heavyweight tasks that require their own separate address spaces. Inter process
communication is expensive and limited. Context switching from one process to another is also
costly.
• A process can contain multiple threads.
• Threads share the same address space.
• A thread is lightweight.
• 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.
• Cost of communication between the thread is low.
Advantages of Multithreading:
• It doesn't block the user because threads are independent and we can perform
multiple operations at the same time.
• We 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.
Difference between multithreading and
multiprocessing

Multiprocessing MultiThreading
Process are heavy weight task Thread are light weight task
Each process has own address Threads are executed under
space, so they do not share the the address space of the
address space process
Context switching between the Context switching between the
process are slow threads are faster
IPC is required to communicate No IPC is required to
between the process communicate between the
threads
Multithreading in Java
• Multithreading in java is a process of executing multiple threads simultaneously.
• Java provides built-in support for multithreaded programming.
• A multithreaded program contains two or more parts (thread) that can run
concurrently.
• Multithreading is a specialized form of multitasking.
• Thread is basically a lightweight sub-process, a smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
• In a singled-threaded environment, when a thread blocks (that is, suspends execution)
because it is waiting for some resource, the entire program stops running.
• The benefit of Java’s multithreading is that one thread can pause without stopping other
parts of your program. For example, Multithreading allows animation loops to sleep for
a second between each frame without causing the whole system to pause.
Life Cycle of a Thread(Thread State)
• A thread can be running. It can be ready to run as soon as it gets CPU time.
• A running thread can be suspended, which temporarily suspends its activity.
• A suspended thread can then be resumed, allowing it to pick up where it left off.
• A thread can be blocked when waiting for a resource.
• At any time, a thread can be terminated, which halts its execution immediately. Once terminated,
a thread cannot be resumed.
• In java a thread exists in any one of the following state
1. New
2. Runnable
3. Running
4. Blocked:
5. Dead /Terminated.
1. New state: The thread is in new state if you create an instance of Thread class
but before the invocation of start() method. At this State, we can do by using
start() method. Whenever a new thread is created, it is always in the new state.
For a thread in the new state, the code has not been run yet and thus has not
begun its execution.
• Active :When a thread invokes the start() method, it moves from the new state to
the active state. The active state contains two states within it: one is runnable,
and the other is running.
2. Runnable state: It means that the thread is ready for execution and it is waiting
for the availability of the processor. The thread is in runnable state after
invocation of start() method, but the thread scheduler has not selected it to be
the running thread. It is the duty of the thread scheduler to provide the thread
time to run, i.e., moving the thread to the running state.
3. Running state : The thread is in running state if the thread scheduler has
selected it. When the thread gets the CPU, it moves from the runnable to the
running state. It means that the processor has given its time to the thread for its
execution. The thread runs until it relinquishes control on its own or it is
preempted by a higher priority thread.
4. Blocked state :In this state the thread is temporarily inactive, but the thread is
alive. This is the state when the thread is still alive, but is currently not eligible
to run.
5. Dead state :A running thread ends its life when it has completed executing its
run() method. It is a natural death. We can kill the thread by using stop()
method. A thread reaches the termination state because of the following
reasons:
• When a thread has finished its job, then it exists or terminates normally.
• Abnormal termination: It occurs when some unusual events such as an unhandled exception
or segmentation fault.
Java Thread Class
• Java’s multithreading system is built upon the Thread class, its methods, and
interface, Runnable.
• To create a new thread, your program should either extend Thread class or
implement the Runnable interface.
• 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.
• The Thread class defines several methods that help manage threads.
Commonly used methods of Thread class:
• public void run(): is used to perform action for a thread.
• public void start(): starts the execution of the thread.JVM calls the run() method on
the thread.
• public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
• public void join(): waits for a thread to die.
• public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
• public int getPriority(): returns the priority of the thread.
• public int setPriority(int priority): changes the priority of the thread.
• public String getName(): returns the name of the thread.
• public void setName(String name): changes the name of the thread.
• public Thread currentThread(): returns the reference of currently executing thread.
• public int getId(): returns the id of the thread.
• public Thread.State getState(): returns the state of the thread.
• public boolean isAlive(): tests if the thread is alive.
• public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
• public void suspend(): is used to suspend the thread(depricated).
• public void resume(): is used to resume the suspended thread(depricated).
• public void stop(): is used to stop the thread(depricated).
• public boolean isDaemon(): tests if the thread is a daemon thread.
• public void setDaemon(boolean b): marks the thread as daemon or user
thread.
• public void interrupt(): interrupts the thread.
• public boolean isInterrupted(): tests if the thread has been interrupted.
• public static boolean interrupted(): tests if the current thread has been
interrupted.
Creating a Thread
• We can create a thread either by:
1. Implementing the Runnable interface or by
2. Extending the Thread class
• Commonly used Constructors of Thread class
1. Thread()
2. Thread(String name)
3. Thread(Runnable r)
4. Thread(Runnable r, String name)
• The start() method of Thread class is used to start a newly created
thread. It performs the following tasks:
1. A new thread starts(with new callstack).
2. The thread moves from New state to the Runnable state.
3. When the thread gets a chance to execute, its target run() method will run.
Implementing 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().
• To implement Runnable, a class need only implement a single method called run( ), which is
declared like this:
• public void run( ) : is used to perform action for a thread.
• Inside run( ), we will define the code that constitutes the new thread.
• The run( ) establishes the entry point for another, concurrent thread of execution within our
program. This thread will end when run( ) returns.
• Once you create a class that implements Runnable, you will instantiate an object of type Thread
from within that class
• Thread defines several constructors. The used one has the following signature:
• Thread(Runnable threadOb, String threadName)
• In this constructor, threadOb is an instance of a class that implements the Runnable
interface.
• This defines where execution of the thread will begin. The name of the new thread is
specified by threadName.
• After the new thread is created, it will not start running until you call its start( ) method, which is
declared within Thread. In essence, start( ) executes a call to run( ).
• The start( ) method is shown here:
• void start( )
class Multi3 implements Runnable{
public void run(){
SOP("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
t1.start();
}
}

thread is running...

If you are not extending the Thread class, your class object would not be treated as a
thread object.
Need to explicitly create the Thread class object. We are passing the object of your
class that implements Runnable so that your class run() method may execute.
public class MyThread2 implements Runnable {
public void run() {
System.out.println("Now the thread is running ...");
}
public static void main(String argvs[]) {
// creating an object of the class MyThread2
Runnable r1 = new MyThread2();
// creating an object of the class Thread using Thread(Runnable r, String name)
Thread th1 = new Thread(r1, "My new thread");
// the start() method moves the thread to the active state
th1.start();
// getting the thread name by invoking the getName() method
String str = th1.getName();
System.out.println(str);
}
}

My new thread
Using the Constructor Thread(Runnable r, String name) Now the thread is running ...
Extending a Thread class
• We can create a thread by creating a new class that extends Thread,
and then to create an instance of that class.
• The extending class must override the run( ) method, which is the
entry point for the new thread.
• It must also call start( ) to begin execution of the new thread.
class Multi3 extends Thread{
public void run(){
SOP("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
t1.start();
}
}

thread is running...
My first thread
My first thread
public class MyThread1 {
public static void main(String args[]) {
// creating an object of the Thread class using the constructor Thread(String name)
Thread t= new Thread("My first thread");
// the start() method moves the thread to the active state
t.start();
// getting the thread name by invoking the getName() method
String str = t.getName();
System.out.println(str);
}
}

My first thread

Using Constructor Thread(String Name)


More than One thread
class MyThread extends Thread {
public void run() {
System.out.println("hello");
} Main thread starts
} Main thread is finished
hello
public class NewThread {
hello
public static void main(String[] args){
System.out.println("Main thread starts");
MyThread r1 = new MyThread();
MyThread r2=new MyThread();
r1.start();
r2.start();
System.out.println("Main thread is finished");
}
}
sleep()
• The sleep() method of Thread class is used to sleep a thread for the
specified amount of time.
• Syntax:
• public static void sleep(long miliseconds) throws InterruptedException
• Thread.sleep() interacts with the thread scheduler to put the current
thread in wait state for specified period of time. Once the wait time is
over, thread state is changed to runnable state and wait for the CPU
for further execution. So the actual time that current thread sleep
depends on the thread scheduler that is part of operatingsystem
class MyThread extends Thread{
public void run(){
for(int i=8;i>=1;i--){
try{
Thread.sleep(500);
}
catch(InterruptedException e){
SOP(e);
}
SOP("Childthread: "+ i); class Driver{
} PSVM(String args[]){
} MyThread t1=new MyThread();
} t1.start();
for(int i=1;i<8;i++){
try{
Thread.sleep(500);
}
catch(InterruptedException e){
SOP(e);
}
SOP ("Main thread: "+ i);
}
}
}
class A implements Runnable {
public void run(){
for(int i=0;i<5;i++) main
{ Thread-1 0
System.out.println(Thread.currentThread().getName()+" " +i+"\n");
try { Thread-0 0
Thread.sleep(1000);
} Thread-1 1
catch(Exception e) {
System.out.println(e);
} Thread-0 1

} Thread-1 2
}
} Thread-0 2
class BTest {
public static void main(String args[]) { Thread-1 3
System.out.println(Thread.currentThread().getName());
A a1=new A();
Thread t1=new Thread(a1); Thread-0 3
Thread t2=new Thread(a1);
t1.start(); Thread-1 4
t2.start();
} Thread-0 4
}
class TestSleepMethod1 extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{
Thread.sleep(500);
1
}
1
catch(InterruptedException e){
2
System.out.println(e);
2
}
3
System.out.println(i);
3
}
4
}
4
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();
t1.start();
t2.start();
}
}

At a time only one thread is executed. If you sleep a thread for the specified time, the thread scheduler picks up
another thread and so on.
getName(): To get the name of the thread
class MyThread extends Thread {
public void run() {
System.out.println("hello");
}
} Main thread starts
public class NewThread { Name of t1:Thread-2
public static void main(String[] args){ Name of t2:Thread-3
System.out.println("Main thread starts"); Main thread is finished
MyThread r1 = new MyThread(); hello
MyThread r2=new MyThread(); hello
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
t1.start();
t2.start();
System.out.println("Main thread is finished");
}
}
Change the Thread Name using Constructor
class MyThread extends Thread {
public void run() {
System.out.println("hello");
System.out.println(Thread.currentThread().getName());
}
} Main thread starts
public class NewThread { Main thread is finished
public static void main(String[] args){ hello
System.out.println("Main thread starts"); gopal
MyThread r1 = new MyThread(); hello
MyThread r2=new MyThread(); ram
Thread t1 = new Thread(r1,"ram");
Thread t2 = new Thread(r2,"gopal");
// System.out.println("Name of t1:"+t1.getName());
//System.out.println("Name of t2:"+t2.getName());
t1.start();
t2.start();
System.out.println("Main thread is finished");
}
}
Run Method for different Thread
class MyThread1 extends Thread {
public void run() {
System.out.println("First thread");
System.out.println(Thread.currentThread().getName());
}
} Main thread starts
class MyThread2 extends Thread { Main thread is finished
public void run() { First thread
System.out.println("Second Thread"); Second Thread
System.out.println(Thread.currentThread().getName());
ram
}
} ssgopal
class NewThread {
public static void main(String[] args){
System.out.println("Main thread starts");
MyThread1 r1 = new MyThread1();
MyThread2 r2=new MyThread2();
Thread t1 = new Thread(r1,"ram");
Thread t2 = new Thread(r2,"gopal");
t1.start();
t2.start();
System.out.println("Main thread is finished");
}
}
Different Task to same Thread
class Thread1 implements Runnable {
public void run()
{
System.out.println("first thread is running");
f1();
f2();
}
void f1() first thread is running
{ 5
System.out.println(2+3); 20
}
void f2()
{
System.out.println(5*4);
}
}
class NewThread1
{
public static void main(String args[])
{ Thread1 a1=new Thread1();
Thread t1=new Thread(a1);
t1.start();
}
}
The join() method
• It is a method of java.lang.Thread class that permits one thread to
wait until the other thread to finish its execution.
• Suppose th be the object the class Thread whose thread is doing its
execution currently, then the th.join(); statement ensures that th is
finished before the program does the execution of the next
statement.
• 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
class MyThread extends Thread{ class Driver{
public void run(){ psvm(String args[]){
for(int i=1;i<=4;i++){ MyThread t1=new MyThread();
try{ MyThread t2 = new MyThread();
Thread.sleep(500); MyThread t3 = new MyThread();
} t1.start();
catch(InterruptedException e){ try{
System.out.println(e); t1.join();
} }
SOP("Childthread: "+ i); catch(Exception e){
} System.out.println(e);
} }
} t2.start();
try{
Childthread: 1 t2.join();
Childthread: 2 }
Childthread: 3
Childthread: 4 catch(Exception e){
Childthread: 1 System.out.println(e);
Childthread: 2 }
Childthread: 3
Childthread: 4
t3.start();
Childthread: 1 }
Childthread: 2 }
Childthread: 3
Childthread: 4
class TestJoinMethod1 extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
1
}
catch(Exception e){
2
System.out.println(e); 3
} 4
System.out.println(i); 5
} 1 when t1 completes its task then t2 and t3
} 1 starts executing.
public static void main(String args[]){ 2
TestJoinMethod1 t1=new TestJoinMethod1();
2
TestJoinMethod1 t2=new TestJoinMethod1();
TestJoinMethod1 t3=new TestJoinMethod1();
3
t1.start(); 3
try{ 4
t1.join(); 4
} 5
catch(Exception e){ 5
System.out.println(e);
}
t2.start();
t3.start();
}
}
String
How to create String object
• In java, string is basically an object that represents sequence of
char values. An array of characters works same as java string
• There are two ways to create String object:
• By string literal
• By new keyword
• String literal: Java String literal is created by using double
quotes.
• For Example: String s = "welcome";
• String literal are anonymous objects of the String class
• Each time you create a string literal, the JVM checks the string
constant pool first. If the string already exists in the pool, a reference
to the pooled instance is returned. If string doesn't exist in the pool, a
new string instance is created and placed in the pool.
• For example:
String s1="Welcome";
String s2="Welcome";//will not create new instance
Note: String objects are stored in a special memory area known as
string constant pool.
By using new keyword
• new Keyword : String s=new String("Welcome");
• It creates two objects and one reference variable
• Such case, JVM will create a new string object in normal(non pool) heap memory
and the literal "Welcome" will be placed in the string constant pool. The variable
s will refer to the object in heap(non pool).
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");
//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
Immutability
• Once created, a string cannot be changed: none of its methods
changes the string.
• Such objects are called immutable.
• Immutable objects are convenient because several references can
point to the same object safely: there is no danger of changing an
object through one reference without the others being aware of the
change.
Advantage of Immutability
• An empty String has no characters. It’s length is 0.
• Creating empty string: To create an empty String, we need to call the default
constructor.
• String s = new String();
• String s1 = “”;
• Not the same as an initialized string.
• String Msg; MSG is NULL
• Creating string initialized by an array of characters: To create a String initialized by an
array of characters, use the constructor String(char chars[ ])
• char chars[] = { 'a', 'b', 'c' };
String s = new String(chars); // s is initialized with abc
• Creating string initialized with a subrange of a character array: To create a String,
initialized with a subrange of a character array use the constructor String(char chars[ ],
int startIndex, int numChars)
• char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3); // s is initialized with cde
• Creating string object that contains the same character sequence as
another String object: To create a String object that contains the
same character sequence as another String object use the constructor
String(String strObj)
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c); // s1 is initialized with Java
String s2 = new String(s1); // s2 is initialized with Java
• The java.lang.String class implements Serializable, Comparable and
CharSequence interfaces.
Method –length()
• int length(); : Returns the number of characters in the string
• It is method of String class.
”Problem".length(); Returns 7

char chars[] = { 'a', 'b', 'c' };


String s = new String(chars);
System.out.println(s.length()); // Output: 3
• String concatenation: In java, string concatenation forms a new
string that is the combination of multiple strings. There are two ways
to concat string in java:
1. By + operator
2. By concat() method of String class
• String Concatenation by + operator : We can use ‘+’ operator for
concatenation of multiple strings.
String age = "9“;
String s = "He is " + age + " years old.";
System.out.println(s); // Output: “He is 9 years old.

• We can concatenate strings with other types of data.


• NOTE: The compiler will convert an operand to its string equivalent
whenever the other operand of the + is an instance of String.
• Be careful when we mix other types of operations with string concatenation
expression.
String s1 = "four: " + 2 + 2; String s2 = "four: " + (2 + 2);
System.out.println(s1); // Output: four: 22 System.out.println(s2); // Output: four: 4
String s3 = 2 + 2 + ": four";
System.out.println(s3); // Output: 4: four
• String Concatenation by concat( ) method : The String concat() method concatenates
the specified string to the end of current string.
Syntax: public String concat(String another)
class TestStringConcat{
public static void main(String args[]){
String s1="Sachin ";
String s2="Tendulkar";
String s3=s1.concat(s2);
System.out.println(s3);//Sachin Tendulkar
}
}
• In java, string objects are immutable. Immutable simply means unmodifiable or
unchangeable. Once string object is created its data or state can't be changed but
a new string object is created.

String s="Sachin";
s.concat(" Tendulkar");
System.out.println(s); //print Sachin because strings are immutable objects
Now it can be understood by the diagram given. Here Sachin is not changed but a new
object is created with Sachin Tendulkar. That is why string is known as immutable.

in the above figure that two objects are created


but s reference variable still refers to "Sachin" not to
"Sachin Tendulkar".
• But if we explicitly assign it to the reference variable, it will refer to
"Sachin Tendulkar" object.
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);//print Sachin Tendulkar
Method charAt()
• char charAt(i); : Returns the char at ith index.
• Character positions in strings are numbered starting from 0 – just like
arrays.
”Window".charAt (2); Returns ‘n’

String s=new String(“INDIA”);


System.out.println(s.charAt(2)); Prints D
Method substring()
• A part of string is called substring. In other words, substring is a subset of another
string. In case of substring startIndex is inclusive and endIndex is exclusive.
• Returns a new String by copying characters from an existing String.
• String substring (int i): Return the substring from the ith index character to end.
• String substring (int i, int j): Returns the substring from i to j-1 index.
Method getChars()
• void getChars(int sourceStart, int sourceEnd, char target[ ], int
targetStart): Stores the character from index sourceStart to index
sourceEnd from the source string at the target string starting at
targetStart index.
class getCharsDemo {
public static void main(String args[]) {
String s = "This is a demo of the getChars method.";
int start = 10,end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);// prints demo
}
}
String Compare
• There are three ways to compare string in java:
1. By equals() method
2. By = = operator
3. By compareTo() method
Method equals()
• boolean equals( Object str): Here str is the String object being compared with
the invoking String object.
• Boolean out = “Geeks”.equals(“Geeks”); // returns true
• Boolean out = “Geeks”.equals(“geeks”); // returns false
• boolean equalsIgnoreCase (String anotherString): Compares invoking String object with another
string, ignoring case considerations.
• Boolean out= “Geeks”.equalsIgnoreCase(“Geeks”); // returns true
• Boolean out = “Geeks”.equalsIgnoreCase(“geeks”); // returns true
class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin"); true
String s4="Saurav"; true
System.out.println(s1.equals(s2));//true false
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}
• The equals( ) method compares the characters inside a String object.
The == operator compares two object references to see whether they
refer to the same instance.
• The == operator compares references not values.

String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1.equals(s2)); // prints true
System.out.println((s1 == s2)); // prints false
class Test {
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
SOP(s1==s2); //true (because both refer to same instance)
SOP(s1==s3); //false(because s3 refers to instance created in nonpool)
}
}

True
false
compareTo() method
• int compareTo(String str): This method compares String str with the
invoking String.
• The String class compareTo() method compares values
lexicographically and returns an integer value that describes if first
string is less than, equal to or greater than second string.
• Suppose s1 and s2 are two String objects. If:
• s1 == s2 : The method returns 0.
• s1 > s2 : The method returns a positive value.
• s1 < s2 : The method returns a negative value.
• int diff = word1.compareTo(word2); : returns the “difference” word1 - word2
• int diff = word1.compareToIgnoreCase(word2); : returns the “difference”
word1 - word2, Ignoring the case
Usually programmers don’t care what the numerical “difference” of word1 - word2 is,
just whether the difference is negative (word1 comes before word2), zero (word1 and
word2 are equal) or positive (word1 comes after word2). Often used in conditional
statements.

if(word1.compareTo(word2) > 0){


//word1 comes after word2…
}
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}

0
1
-1
Methods — Find (indexOf)
Method: trim()
• The trim() method returns a copy of the invoking string from which
any leading and trailing whitespace has been removed.

String word2 = word1.trim ();


returns a new string formed from word1 by removing white space at both ends
does not affect whites space in the middle

String word1 = “ Hi Bob “;


String word2 = word1.trim();
//word2 is “Hi Bob” – no spaces on either end
//word1 is still “ Hi Bob “ – with spaces
Method: replace()
• The trim() method returns a copy of the invoking string from which
any leading and trailing whitespace has been removed.
• Syntax: String replace(char original, char replacement)

String word2 = word1.replace(oldCh, newCh);


returns a new string formed from word1 by replacing all occurrences of oldCh with newCh

String word1 = “rare“;


String word2 = “rare“.replace(‘r’, ‘d’);
//word2 is “dade”, but word1 is still “rare“
String s1 = "javatpoint is a very good website";
String s2 = s1.replace('a','e');//replaces all occurrences of 'a' to 'e'

String s1="my name is khan my name is java";


String s2=s1.replace("is","was");//replaces all occurrences of "is" to "was"
Methods : Changing the case
• String toLowerCase( )
• String toUpperCase( )

String word2 = word1.toUpperCase();


String word3 = word1.toLowerCase();
returns a new string formed from word1 by converting its characters to upper (lower)
case.

String word1 = “HeLLo“;


String word2 = word1.toUpperCase(); //”HELLO”
String word3 = word1.toLowerCase(); //”hello”
//word1 is still “HeLLo“
valueof()
• valueOf():This method converts different types of values into string.
By the help of string valueOf() method, we can convert int to string,
long to string, boolean to string, character to string, float to string,
double to string, object to string and char array to string.

int value=30;
String s1=String.valueOf(value);
System.out.println(s1+10);//Prints 3010
• Three ways to convert a number into a string:
1. String s = "" + num;
s = “” + 123;//”123” Integer and Double are “wrapper” classes
2. String s = Integer.toString (i); from java.lang that represent numbers as
objects. They also provide useful static methods.
String s = Double.toString (d);
s= Integer.toString(123);//”123”
s = Double.toString(3.14); //”3.14”
3. String s = String.valueOf (num);
s = String.valueOf(123);//”123”
The output of the following fraction of code is
public class Test{
public static void main(String args[]){
String s1 = new String("Hello");
String s2 = new String("Hellow");
System.out.println(s1 = s2);
}
}
Hellow
class LogicalCompare{
public static void main(String args[]){
String str1 = new String("OKAY");
String str2 = new String(str1);
System.out.println(str1 == str2);
}
}
false
public class Test{
public static void main(String args[]){
String x = "hellow";
int y = 9;
System.out.println(x += y);
}
} hellow9
public class Test{
public static void main(String args[]){
String s1 = "java";
String s2 = "java"; true
System.out.println(s1.equals(s2)); true
System.out.println(s1 == s2);
}
}
How many objects will be created?

String a = new String("Examveda");


String b = new String("Examveda");
String c = "Examveda";
3
String d = "Examveda";
Object will be created each time whenever we use new keyword. So, 2 object will
be created simply for the first two line .
The remaining two bottom line. String c="examveda“ creates an object and store it
in String pool, next time when we are writing String d="examveda" it will first
check in String pool whether object already exists or not. Since, it is existing, no
new object will be created. Hence reference "d" points to existing object
"examveda". So ultimately 3 object will be created at the end.
String Buffer
• StringBuffer class is used to create mutable (modifiable) string. The StringBuffer
class in java is same as String class except it is mutable.
• StringBuffer represents growable and writeable character sequences. StringBuffer
may have characters and substrings inserted in the middle or appended to the
end.
• Constrctor:
1. StringBuffer(): creates an empty string buffer with the initial capacity of 16.
2. StringBuffer(String str): creates a string buffer with the specified string.
3. StringBuffer(int capacity): creates an empty string buffer with the specified
capacity as length.
Methods
• The insert() method inserts the given string with this string at the given position.

class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
Method

• The append() method concatenates the given argument with


this String.
class StringBufferExample{
PSVM(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}

HelloJava
Method
• The replace() method replaces the given String from the
specified beginIndex and endIndex.

class StringBufferExample3{
PSVM(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
SOP(sb);//prints HJavalo
}
}
Method
• The delete() method of the StringBuffer class deletes the String
from the specified beginIndex to endIndex.

class StringBufferExample4{
PSVM(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
SOP(sb);//prints Hlo
}
}
Method
• The reverse() method of the StringBuilder class reverses the
current String.
class Example{
PSVM(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Method
• The capacity() method of the StringBuffer class returns the
current capacity of the buffer.
• The default capacity of the buffer is 16.
• If the number of character increases from its current capacity, it
increases the capacity by (oldcapacity*2)+2. For example if
your current capacity is 16, it will be (16*2)+2=34.
class StringBufferExample6{
psvm(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}

16
16
34
Method
• The ensureCapacity() method of the StringBuffer class ensures that the given
capacity is the minimum to the current capacity.
• If it is greater than the current capacity, it increases the capacity by
(oldcapacity*2)+2.
• For example if your current capacity is 16, it will be (16*2)+2=34.
class Example{
PSVM(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity()); //now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity()); //now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}

16
16
34
34
70
String Builder
• Java StringBuilder class is used to create mutable (modifiable) string.
• The Java StringBuilder class is same as StringBuffer class except that it is non
synchronized.
• It is available since JDK 1.5.
• Constructor:
1. StringBuilder() : creates an empty string Builder with the initial capacity of
16.
2. StringBuilder(String str): creates a string Builder with the specified string.
3. StringBuilder(int length): creates an empty string Builder with the specified
capacity as length.
Commonly Used Method
• public int length(): is used to return the length of the string i.e. total number of
characters.
• public String substring(int beginIndex): is used to return the substring from the
specified beginIndex.
• public StringBuilder insert(int offset, String s): is used to insert the specified
string with this string at the specified position.
• The insert() method is overloaded like insert(int, char), insert(int, boolean),
insert(int, int), insert(int, float), insert(int, double) etc.
class Example{
PSVM(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
• The StringBuilder replace() method replaces the given string from the specified
beginIndex and endIndex.

class StringBuilderExample3{
PSVM(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
• The reverse() method of StringBuilder class reverses the current string.

class Example{
PSVM(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Difference between StringBuffer and StringBuilder
StringBuffer StringBuilder
StringBuffer is synchronized i.e. thread safe. It StringBuilder is non- synchronized i.e. not
means two threads can‘ t call the methods of thread safe. It means two threads can call
StringBuffer simultaneously. the methods of StringBuilder
simultaneously.
StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than
StringBuffer.
StringBuffer was introduced in Java 1.0 StringBuilder was introduced in Java 1.5
Difference between String and StringBuffer
String StringBuffer
String class is immutable. StringBuffer class is mutable.
String is slow and consumes more memory StringBuffer is fast and consumes less
when you concat too many strings because memory when you concat strings.
every time it creates new instance.
String class overrides the equals() method of StringBuffer class doesn't override the
Object class. So you can compare the equals() method of Object class.
contents of two strings by equals() method.
Java Tokenizer
• The java.util.StringTokenizer class allows you to break a String into tokens. It is
simple way to break a String.
• Parsing is the division of text into a set of discrete parts, or tokens
• The StringTokenizer class provides the first step in this parsing process, often
called the lexer (lexical analyzer) or scanner.
• To use StringTokenizer, we specify an input string and a string that contains
delimiters. Delimiters are characters that separate tokens.
• Each character in the delimiters string is considered a valid delimiter—for
example, “,;:” sets the delimiters to a comma, semicolon, and colon.
• The default set of delimiters consists of the whitespace characters: space, tab,
newline, and carriage return.
Constructor of StringTokenizer class
• There 3 constructors of StringTokenizer class
1. StringTokenizer(String str): It creates StringTokenizer with specified string.
2. StringTokenizer(String str, String delim): It creates StringTokenizer with
specified string and delimiter.
3. StringTokenizer(String str, String delim, boolean returnValue): It creates
StringTokenizer with specified string, delimiter and returnValue. If return
value is true, delimiter characters are considered to be tokens. If it is false,
delimiter characters serve to separate tokens.
Methods of StringTokenizer class
Methods Description
boolean hasMoreTokens() It checks if there is more tokens available.

String nextToken() It returns the next token from the


StringTokenizer object.
String nextToken(String delim) It returns the next token based on the
delimiter.
boolean hasMoreElements() It is the same as hasMoreTokens() method.

Object nextElement() It is the same as nextToken() but its return


type is Object.
int countTokens() It returns the total number of tokens.
import java.util.StringTokenizer;
class STDemo {
static String in = "title=Java: The Complete Reference;" + "author=Schildt;" + "publisher=Osborne/McGraw-Hill;"
+ "copyright=2007";
public static void main(String args[]) {
StringTokenizer st = new StringTokenizer(in, "=;");
while(st.hasMoreTokens()) {
String key = st.nextToken();
System.out.println(key );
}
}
}

title
Java: The Complete Reference
author
Schildt
publisher
Osborne/McGraw-Hill
copyright
2007
AWT
• Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based
applications in java.
• Java AWT components are platform-dependent.
• Components are displayed according to the view of operating system.
• AWT is heavyweight. (Its components are using the resources of OS.)
• The java.awt package provides classes for AWT api such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.
• Application developed in AWT have different look and feel when executed on
different platform.
• The java.awt package contains the core AWT graphics classes:
• GUI Component classes, such as Button, TextField, and Label.
• GUI Container classes, such as Frame and Panel.
• Layout managers, such as FlowLayout, BorderLayout and GridLayout.
• Custom graphics classes, such as Graphics, Color and Font.
• The java.awt.event package supports event handling:
• Event classes, such as ActionEvent, MouseEvent, KeyEvent and
WindowEvent,
• Event Listener Interfaces, such as ActionListener, MouseListener,
MouseMotionListener, KeyListener and WindowListener,
• Event Listener Adapter classes, such as MouseAdapter, KeyAdapter, and
WindowAdapter.
AWT Hierarchy
• There are two types of GUI elements:
1. Component
2. Container
1. Component: All the elements like the button, text fields, scroll bars, etc. are
called components.
• In Java AWT, there are classes for each component.
• In order to place every component in a particular position on a screen, we need
to add them to a container.
• Component is an abstract class that encapsulates all of the attributes of a visual
component.
• All user interface elements that are displayed on the screen and that interact with
the user are subclasses of Component.
2. Container: The Container is a component in AWT that can contain another
components like buttons, textfields, labels etc.
• The classes that extends Container class are known as container such as Frame,
Dialog and Panel.
• It is basically a screen where the where the components are placed at their
specific locations. Thus it contains and controls the layout of components.
• A container itself is a component, therefore we can add a container inside
container.
• It is a subclass of components
• It has additional methods that allow other Component objects to be nested
within it. Other Container objects can be stored inside of a Container.
• There are four types of container in java awt
• Window: The window is the container that have no borders and menu bars. You
must use frame, dialog or another window for creating a window.
• Panel: The Panel is the container that doesn't contain title bar and menu bars. It
can have other components like button, textfield etc. An instance of Panel class
creates a container, in which we can add components.
• Frame: The Frame is the container that contain title bar and border and can have
menu bars. It can have other components like button, text field, scrollbar etc. It is
the widely used container.
• Dialog :
• The class Component is the abstract base class for the non-menu
user-interface controls of AWT.
• A component represents an object with graphical representation.
• The class Container is the superclass for the containers of AWT.
• The container object can contain other AWT components.
In the above figure, there are three containers: a Frame and two Panels.

A Frame is the top-level container of an AWT program. A Frame has a title bar (containing an icon, a title, and
the minimize/maximize/close buttons), an optional menu bar and the content display area.

The Panel class is a concrete subclass of Container. It doesn’t add any new methods; it simply implements
Container. A Panel is a rectangular area used to group related GUI components in a certain layout. In the above
figure, the top-level Frame contains two Panels. There are five components: a Label (providing description), a
TextField (for users to enter text), and three Buttons (for user to trigger certain programmed actions).
Component class
• It is a subclass of Object class.
• In order to have a particular component in a window, you must add the
component to the window.
• Component add(Component obj)
• The method return the reference of the obj
• Example:
• Button red=new Button(“red”);
• add(red);
• Remove a button:
• void remove(Component ob);
• The object of the component removed., which has passed as an argument.
• //Constructor of the Button class
• Button(); //Create Button without level
• Button(String str); // //Create Button level
• Example:
• Button obj= new Button(str);
• add(obj);
Methods of Component class
• public void add(Component c) :Inserts a component on this
component.
• public void setSize(int width,int height) : Sets the size (width and
height) of the component.
• public void setLayout(LayoutManager m) : Defines the layout
manager for the component.
• public void setVisible(boolean status): Changes the visibility of the
component, by default false.
Container class
Frame and Window: A Frame provides the "main window" for your GUI application. It
has a title bar (containing an icon, a title, the minimize, maximize/restore-down and close
buttons), an optional menu bar, and the content display area. To write a GUI program, we
typically start with a subclass extending from java.awt.Frame.
Dialog
Dialog: An AWT Dialog is a "pop-up window" used for interacting with the users. A Dialog
has a title-bar (containing an icon, a title and a close button) and a content display area.
Secondary containers are placed inside a top-level container or another secondary
container. AWT provides these secondary containers:
1. Panel: a rectangular box used to layout a set of related GUI components in pattern
such as grid or flow.
2. ScrollPane: provides automatic horizontal and/or vertical scrolling for a single child
component others.
A Container has a LayoutManager to layout the components in a certain pattern.
Frame
• There are two ways to create a frame in AWT.
• By extending Frame class (inheritance)
• By creating the object of Frame class (association)
By extending Frame class (inheritance)
import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
} class Demo{
public static void main(String args[]){
First f=new First();
}
}
Cont...

• The setBounds(int xaxis, int yaxis, int width, int height): This method
is used in the above example that sets the position of the awt button.
Creating a Frame by Association
import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
class Demo{
public static void main(String args[]){
First2 f=new First2();
}
}
TextField
• The textField component allows the user to edit single line of text.
• When the user types a key in the text field the event is sent to the
TextField.
• public class TextField extends TextComponent
• The object of a TextField class is a text component that allows the
editing of a single line text. It inherits TextComponent class
Constructor
• TextField() : Constructs a new text field.
• TextField(int columns): Constructs a new empty text field with the
specified number of columns.
• TextField(String text) : Constructs a new text field initialized with the
specified text.
• TextField(String text, int columns): Constructs a new text field
initialized with the specified text to be displayed, and wide enough to
hold the specified number of columns.
Important Methods
• void setText(String t) : Sets the text that is presented by this text
component to be the specified text.

• String getText(): Get the text that is presented by this text


component.
Method Inherited
• The AWT TextField class inherits the methods from below classes:
1. java.awt.TextComponent
2. java.awt.Component
3. java.lang.Object
import java.awt.*;
class TextFieldDemo{
public static void main(String []args){
Frame f =new Frame();
TextField t1= new TextField("Hello");
t1.setBounds(50,80,100,30);
f.add(t1);
f.setSize(500,500);
f.setLayout(null);
f.setVisible(true);
}
}
Example
import java.awt.*;
class TextFieldExample{
public static void main(String args[]){
Frame f= new Frame("TextField Example");
TextField t1,t2,t3;
t1=new TextField("Welcome to Silicon");
t1.setBounds(50,100, 200,30);
t2=new TextField("TextField Demo");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400); f.setLayout(null); f.setVisible(true);
}
}
Example
import java.awt.*;
class TextFieldDemo{
public static void main(String []args){
Frame f =new Frame();
TextField t1= new TextField("11");
t1.setBounds(50,80,100,30);
TextField t2= new TextField("22");
t2.setBounds(50,120,100,30);
TextField t3= new TextField();
t3.setBounds(50,160,100,30);
int sum= Integer.parseInt(t1.getText())+ Integer.parseInt(t2.getText());
String s="";
s=s+sum;
t3.setText(s);
f.add(t1);
f.add(t2);
f.add(t3);
f.setSize(500,500); f.setLayout(null); f.setVisible(true);
}
}
import java.awt.*;
class AWTExample2 {
AWTExample2() {
Frame f = new Frame();
Label l = new Label("Employee id:");
Button b = new Button("Submit");
TextField t = new TextField();
l.setBounds(20, 80, 80, 30);
t.setBounds(20, 100, 80, 30);
b.setBounds(100, 100, 80, 30);
f.add(b);
f.add(l);
f.add(t);
f.setSize(400,300);
f.setTitle("Employee info");
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]) {
AWTExample2 awt_obj = new AWTExample2();
}
}
Java AWT Panel
• The Panel is a simplest container class.
• It provides space in which an application can attach any other
component. It inherits the Container class.
• It doesn't have title bar.
Event Handling
• When we create a component, the component is displayed but is not capable of
performing any action.
• An event is an object that describes a state change in a source.
• An event represents a specific action done on a component. Example: clicking, typing,
mouse over etc.
• Changing the state of an object is known as an event.
• For example, click on button, dragging mouse etc.
• The java.awt.event package provides many event classes and Listener interfaces for
event handling.
• The java.awt.event package provides many event classes and Listener interfaces for
event handling.
• To let the component understand that an event is generated on it, we should add
some listener to the component. A listener is an interface which listens to an
event coming from a component. A listener will have some abstract methods
which need to be implemented by the programmer.
• When an event is generated by the user on the component, the component
sends (delegates) that event to the listener attached to it. The listener hands over
(delegates) the event to an appropriate method. Finally, the method is executed
and the event is handled. This is called event delegation model as shown in the
following diagram.
Delegation event model has two parts: sources and listeners.
Event Sources

• A source is an object that generates an event.


• This occurs when the internal state of that object changes in some way.
Sources may generate more than one type of event.
• A source must register listeners in order for the listeners to receive
notifications about a specific type of event.
• Each type of event has its own registration method.
• Here is the general form:
• public void addTypeListener (TypeListener el ).
• When an event occurs, all registered listeners are notified and receive a
copy of the event object. This is known as multicasting the event.
• In all cases, notifications are sent only to listeners that register to receive
them.
Event Listeners
• A listener is an object that is notified when an event occurs.
• It has two major requirements.
• First, it must have been registered with one or more sources to
receive notifications about specific types of events.
• Second, it must implement methods to receive and process these
notifications.
Event classed
• At the root of the Java event class hierarchy is EventObject, which is in java.util. It
is the superclass for all events.
• EventObject(Object src)
• Here, src is the object that generates this event.
• EventObject contains two methods: getSource( ) and toString( ).
• The getSource( ) method returns the source of the event. Its general form is
shown here:
• Object getSource( )
• toString( ) returns the string equivalent of the event.
• The class AWTEvent, defined within the java.awt package, is a subclass of
EventObject.
• It is the superclass (either directly or indirectly) of all AWT-based events.
• Its getID( ) method can be used to determine the type of the event.

Event classes
• ActionEvent Generated when a button is pressed, a list item is double-clicked, or a menu item is selected.
• AdjustmentEvent Generated when a scroll bar is manipulated.
• ComponentEvent Generated when a component is hidden, moved, resized, or becomes visible.
• ContainerEvent Generated when a component is added to or removed from a container.
• FocusEvent Generated when a component gains or loses keyboard focus.
• InputEvent Abstract superclass for all component input event classes.
• ItemEvent Generated when a check box or list item is clicked; also occurs when a choice selection is made
or a checkable menu item is selected or deselected.
• KeyEvent Generated when input is received from the keyboard.
• MouseEvent Generated when the mouse is dragged, moved, clicked, pressed, or released; also generated
when the mouse enters or exits a component.
• MouseWheelEvent Generated when the mouse wheel is moved.
• TextEvent Generated when the value of a text area or text field is changed.
• WindowEvent Generated when a window is activated, closed, deactivated, deiconified, iconified, opened,
or quit.
Event Source & Description

• Button Generates action events when the button is pressed.


• Check box Generates item events when the check box is selected or deselected.
• Choice Generates item events when the choice is changed.
• List Generates action events when an item is double-clicked; generates item
events when an item is selected or deselected.
• Menu item Generates action events when a menu item is selected; generates
item events when a checkable menu item is selected or deselected.
• Scroll bar Generates adjustment events when the scroll bar is manipulated.
• Text components Generates text events when the user enters a character.
• Window Generates window events when a window is activated, closed,
deactivated, deiconified, iconified, opened, or quit.
Steps to perform Event Handling
• Following steps are required to perform event handling:
1. Implement the Listener interface and override its methods
2. Register the component with the Listener
• Listeners are created by implementing one or more of the interfaces
defined by the java.awt.event package.
Method
• Button
• public void addActionListener(ActionListener a){}
• MenuItem
• public void addActionListener(ActionListener a){}
• TextField
• public void addActionListener(ActionListener a){}
• public void addTextListener(TextListener a){}
• TextArea
• public void addTextListener(TextListener a){}
• Checkbox
• public void addItemListener(ItemListener a){}
• Choice
• public void addItemListener(ItemListener a){}
• List
• public void addActionListener(ActionListener a){}
• public void addItemListener(ItemListener a){}
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
b.addActionListener(this);//passing current instance
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome "+ tf.getText());
}
public static void main(String args[]){
new AEvent();
}
}
import java.awt.*;
import java.awt.event.*;
class AEvent2 extends Frame{
TextField tf;
AEvent2(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
Outer o=new Outer(this);
b.addActionListener(o);//passing outer class instance
add(b);add(tf);
setSize(300,300);
import java.awt.event.*;
setLayout(null);
class Outer implements ActionListener{
setVisible(true);
AEvent2 obj;
}
Outer(AEvent2 obj){
public static void main(String args[]){
this.obj=obj;
new AEvent2();
}
}
public void actionPerformed(ActionEvent e){
}
obj.tf.setText("welcome “ + obj.tf.getText());
}
}
import java.awt.*;
import java.awt.event.*;
public class ButtonExample3 {
public static void main(String[] args) {
Frame f = new Frame("Button Example");
final TextField tf=new TextField();
tf.setBounds(50,50, 150,20);
Button b=new Button("Click Here");
b.setBounds(50,100,60,30);
b.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
tf.setText("Welcome to JavaAWT.");
}
});
f.add(b);
f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
import java.awt.*; public void actionPerformed(ActionEvent e){
import java.awt.event.*; if (e.getSource() == b1) {
class ex1 extends Frame implements ActionListener { this.setBackground(Color.red);
Button b1,b2,b3; }
ex1() { if (e.getSource() == b2) {
b1 = new Button("RED"); this.setBackground(Color.green);
b2 = new Button("GREEN"); }
b3 = new Button("BLUE"); if (e.getSource() == b3) {
b1.setBounds(50,50,100,100); this.setBackground(Color.blue);
b2.setBounds(170,50,100,100); }
b3.setBounds(290,50,100,100); }
b1.addActionListener(this); public static void main(String args[]) {
b2.addActionListener(this); new ex1();
b3.addActionListener(this); }
add(b1); }
add(b2);
add(b3);
setSize(500,500);
setLayout(null);
setVisible(true);
}
import java.awt.*; public void actionPerformed(ActionEvent e) {
import java.awt.event.*; String s1 = tf1.getText();
public class ex2 extends Frame implements ActionListener { String s2 = tf2.getText();
TextField tf1, tf2, tf3;
Button b1, b2,b3,b4;
int a = Integer.parseInt(s1);
ex2() { int b = Integer.parseInt(s2);
tf1 = new TextField(); int c = 0;
tf1.setBounds(50, 50, 150, 20); if (e.getSource() == b1){
tf2 = new TextField(); c = a + b;
tf2.setBounds(50, 100, 150, 20); }
tf3 = new TextField(); else if (e.getSource() == b2){
tf3.setBounds(50, 150, 150, 20);
tf3.setEditable(false);
c = a - b;
b1 = new Button("+"); }
b1.setBounds(50, 200, 50, 50); else if (e.getSource() == b3){
b2 = new Button("-"); c = a * b;
b2.setBounds(120,200,50,50); }
b3 = new Button("*"); else if (e.getSource() == b4){
b3.setBounds(190,200,50,50); c = a / b;
b4 = new Button("/");
b4.setBounds(260,200,50,50);
}
b1.addActionListener(this); String result = String.valueOf(c);
b2.addActionListener(this); tf3.setText(result);
b3.addActionListener(this); }
b4.addActionListener(this); public static void main(String[] args) {
add(tf1); add(tf2); add(tf3); add(b1); add(b2); add(b3); add(b4); new ex2();
setSize(350,350); setLayout(null); setVisible(true); }
}
}
import java.awt.*;
import java.awt.event.*;
class MyFrameTextArea extends Frame implements ActionListener{ public void actionPerformed(ActionEvent e){
Label l1,l2;
TextArea area;
String text=area.getText();
Button b; String words[]=text.split("\\s");
MyFrameTextArea(){ l1.setText("Words: "+words.length);
l1=new Label(); l2.setText("Characters: "+text.length());
l1.setBounds(50,50,100,30);
l2=new Label(); }
l2.setBounds(160,50,100,30); public static void main(String args[]){
area=new TextArea(); new MyFrame();
area.setBounds(20,100,300,300);
b=new Button("Count Words");
}
b.setBounds(100,400,100,30); }
b.addActionListener(this);
add(l1);add(l2);add(area);add(b);
setSize(400,450);
setLayout(null);
setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e){
System.exit(0);
}
});

}
import java.awt.*;
import java.awt.event.*;
class MyFrameCheckBox extends Frame implements ItemListener{ public void itemStateChanged(ItemEvent ie) {
String msg=""; repaint();
Checkbox c1,c2; }
MyFrameCheckBox() { public void paint(Graphics g) {
c1 = new Checkbox("Bold",true); g.drawString("Curent state:",10,100);
c1.setBounds(100,100, 50,50); msg="Bold"+c1.getState();
c2 = new Checkbox("Itaic"); g.drawString(msg,10,120);
c2.setBounds(100,150, 50,50); msg="Italic:"+c2.getState();
add(c1); g.drawString(msg,10,140);
add(c2); }
c1.addItemListener(this); public static void main(String args[]){
c2.addItemListener(this); new MyFrameCheckBox();
setSize(400,400); }
setLayout(null); }
setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
Panel
import java.awt.*;
public class PanelExample {
PanelExample() {
Frame f= new Frame("Panel Example");
Panel panel=new Panel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
Button b1=new Button("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
Button b2=new Button("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel); f.setSize(400,400); f.setLayout(null); f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}
• The Dialog control represents a top level window with a border and a
title used to take some form of input from the user. It inherits the
Window class.
• Unlike Frame, it doesn't have maximize and minimize buttons.
• Frame vs Dialog
1. Frame and Dialog both inherits Window class.
2. Frame has maximize and minimize buttons but Dialog doesn't have.
import java.awt.*;
import java.awt.event.*;
public cla DialogExample {
private static Dialog d;
DialogExample() {
Frame f= new Frame();
d = new Dialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
Button b = new Button ("OK");
b.addActionListener ( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
DialogExample.d.setVisible(false);
}
});
d.add( new Label ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[]) {
new DialogExample();
}
}
Mouse Listener Interface
• The Java MouseListener is notified whenever you change the state of
mouse.
• It is notified against MouseEvent.
• The MouseListener interface is found in java.awt.event package. It has
five methods.
Methods of Mouse Listener Interface
• public abstract void mouseClicked(MouseEvent e);
• public abstract void mouseEntered(MouseEvent e);
• public abstract void mouseExited(MouseEvent e);
• public abstract void mousePressed(MouseEvent e);
• public abstract void mouseReleased(MouseEvent e);
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);
l=new Label(); public void mousePressed(MouseEvent e) {
l.setBounds(20,50,100,20); l.setText("Mouse Pressed");
add(l); }
setSize(300,300); public void mouseReleased(MouseEvent e) {
setLayout(null); l.setText("Mouse Released");
setVisible(true); }
} public static void main(String[] args) {
public void mouseClicked(MouseEvent e) { new MouseListenerExample();
l.setText("Mouse Clicked"); }
} }
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
KeyListener Interface
• The Java KeyListener is notified whenever you change the state of key.
• It is notified against KeyEvent.
• The KeyListener interface is found in java.awt.event package. It has
three methods.
Methods of KeyListener interface
• public abstract void keyPressed(KeyEvent e);
• public abstract void keyReleased(KeyEvent e);
• public abstract void keyTyped(KeyEvent e);
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements KeyListener{
Label l;
TextArea area;
KeyListenerExample(){
l=new Label(); public void keyTyped(KeyEvent e) {
l.setBounds(20,50,100,20); l.setText("Key Typed");
area=new TextArea(); }
area.setBounds(20,80,300, 300);
area.addKeyListener(this); public static void main(String[] args) {
add(l);add(area); new KeyListenerExample();
setSize(400,400); }
setLayout(null); }
setVisible(true);
}
public void keyPressed(KeyEvent e) {
l.setText("Key Pressed");
}
public void keyReleased(KeyEvent e) {
l.setText("Key Released");
}
Closing the Frame
• We have to attach a listener to the frame component.
• f.addwindowListener(WindowListener obj);
• Implement all the methods of WindowListener interface.
• Public void windowActivated(WindowEvent e)
• Public void windowClosed(WindowEvent e)
• Public void windowClosing(WindowEvent e)
• Public void windowDeactivated(WindowEvent e)
• Public void windowDeiconified(WindowEvent e)
• Public void windowIconified (WindowEvent e)
• Public void windowOpened (WindowEvent e)
import java.awt.*;
import java.awt.event.*;
class MyFrameClosing extends Frame {
public static void main(String args[]) {
MyFrameClosing f1=new MyFrameClosing();
f1.setTitle("my AWT");
f1.setSize(300,250);
f1.setVisible(true);
f1.addWindowListener(new Myclass());
}
}
class Myclass implements WindowListener {
public void windowActivated(WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowClosing(WindowEvent e) {
System.exit(0);
}
public void windowDeactivated(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowIconified (WindowEvent e){}
public void windowOpened (WindowEvent e){}
}
Java Adapter Classes
• An adapter class is an implementation class of a listener interface
which contains all the methods with empty body.
• For example WindowAdapter is an adapter class of WindowListener
interface.
• If you inherit the adapter class, you will not be forced to provide the
implementation of all the methods of listener interfaces. So it saves
code.
class Myclass extends WindowAdapter {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
Java Adapter Classes
• Java adapter classes provide the default implementation of
listener interfaces.
• If you inherit the adapter class, you will not be forced to provide the
implementation of all the methods of listener interfaces. So it saves
code.
import java.awt.*;
import java.awt.event.*;
public class MouseAdapterExample extends MouseAdapter{
Frame f;
MouseAdapterExample(){
f=new Frame("Mouse Adapter");
f.addMouseListener(this);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void mouseClicked(MouseEvent e) {
Graphics g=f.getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}
public static void main(String[] args) {
new MouseAdapterExample();
}
}
import java.awt.*;
import java.awt.event.*;
public class AdapterExample{
Frame f;
AdapterExample(){
f=new Frame("Window Adapter");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
f.dispose();
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new AdapterExample();
}
}
Layout
• The layout manager automatically positions all the components
within the container. If we do not use layout manager then also the
components are positioned by the default layout manager.
• The layout manager is associated with every Container object. Each
layout manager is an object of the class that implements the
LayoutManager interface.

• LayoutManager- The LayoutManager interface declares those
methods which need to be implemented by the class whose object
will act as a layout manager.

AWT Layout Manager Classes:

• BorderLayout- The borderlayout arranges the components to fit in


the five regions: east, west, north, south and center. We can add
only one component per region to a container controlled by a
BorderLayout layout manager. However, this limitation can be
overcome by adding a container with multiple components (such as
Panel).

• The java.awt.BorderLayout class contain the following
constructors and methods that can use to customize this manager:
1. BorderLayout ()
2. BorderLayout(int hgap, int vgap)
• getHgap ()
• getVgap ()
• setHgap (int)
• setVgap (int)
import java.awt.*;
class Border extends Frame
{
Border() {
f = new Frame();
Button b1 = new Button("NORTH");
Button b2 = new Button("SOUTH");
Button b3 = new Button("EAST");
Button b4 = new Button("WEST");
Button b5 = new Button("CENTER");
f.add(b1, BorderLayout.NORTH);
f.add(b2, BorderLayout.SOUTH);
f.add(b3, BorderLayout.EAST);
f.add(b4, BorderLayout.WEST);
f.add(b5, BorderLayout.CENTER);
f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
CardLayout

• The java.awt.CardLayout layout manager is significantly different from


the other layout managers. Unlike other layout managers, that display
all the components within the container at once, a CardLayout layout
manager displays only one component at a time .
• Each component in a container with this layout fills the entire
container. The name cardlayout evolves from a stack of cards where
one card is piled upon another and only one of them .

import java.awt.*;
import java.awt.event.*;
class CardLayoutExample extends Frame implements ActionListener
{
CardLayout card1 = new CardLayout(20,20);
CardLayoutExample{
setLayout(card1);
Button Btnfirst = new Button("first ");
Button BtnSecond = new Button ("Second");
Button BtnThird = new Button("Third");
add(Btnfirst,"Card1");
add(BtnSecond,"Card2"); class Card {
add(BtnThird,"Card3"); public static void main(String args[]) {
Btnfirst.addActionListener(this); CardLayoutExample frame = new CardLayoutExample();
BtnSecond.addActionListener (this); frame.setTitle("CardLayout in Java Example");
BtnThird.addActionListener(this); frame.setSize(220,150);
} frame.setResizable(false);
public void actionPerformed(ActionEvent e) frame.setVisible(true);
{ }
card1.next(this); }
}
}
FlowLayout-
• The FlowLayout is the default layout.It layouts the components in a
directional flow.
• It places components in a container from left to right in the order in
which they were added to the container.
• When one row is filled, layout advances to the next row.
• It is analogous to lines of text in a paragraph. Components managed
by a FlowLayout are always set to their preferred size (both width and
height) regardless of the size of the parent container. Whenever the
container is resized then the components in the container are also
adjusted from the top-left comer. The FlowLayout is the default layout
manager for a Panel, Applet and JPanel.
import java.awt.*;
class FlowLayoutExample extends Frame class Flow1 {
{ public static void main(String args[]) {
FlowLayoutExample() FlowLayoutExample frame = new FlowLayoutExample();
{ frame.setTitle("FlowLayout in Java Example");
frame.setSize(400,150);
Button[] button =new Button[10];
frame.setVisible(true);
setLayout(new FlowLayout()); }
for(int i=0;i<button.length;i++) }
{
button[i]=new Button("Button "+(i+1));
add(button[i]);
}
}
}
import java.awt.*;
class GridLayoutExample extends Frame
{
GridLayoutExample()
{ Button[] button =new Button[12];
setLayout(new GridLayout(4,3));
for(int i=0; i<button.length;i++) {
button[i]=new Button("Button "+(i+i));
add(button[i]);
}
}
}
class Grid1{
public static void main(String args[]) {
GridLayoutExample frame = new GridLayoutExample();
frame.setTitle("GridLayout in Java Example");
frame.setSize(400,150);
frame.setVisible(true);
}
}
Collection
Collection
• Any group of individual objects which are represented as single unit is known as
the collection.
• Collections are used to store, retrieve, manipulate, and communicate aggregate
data.
• All the operations that you perform on a data such as searching, sorting,
insertion, manipulation, deletion, etc. can be achieved by Java Collections.
• Java Collection means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque, etc.) and classes (ArrayList, Vector,
LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet, etc.).
Framework
• A framework is a set of classes and interfaces which provide a readymade
architecture.
• An optimal object-oriented design always includes a framework with a collection
of classes such that all the classes perform the same kind of task.
Collection Framework
• Collection framework is an API, which provides architecture to store and
manipulate group of objects.
• The Java Collections Framework is a collection of interfaces and classes
which helps in storing and processing the data efficiently.
• This framework has several useful classes which have tons of useful
functions which makes a programmer task easy.
• Java Collection Framework provides interfaces such as Set, List, Queue,
Deque, and classes such as ArrayList, Vector, LinkedList, HashSet,
PriorityQueue, TreeSet, and LinkedHashSet.
• The Collection interface is the foundation upon which the Collections
Framework is built because it must be implemented by any class that
defines a collection.
What is a Java Collection Framework?
• A Java collection framework provides an architecture to store and
manipulate a group of objects. A Java collection framework includes
the following:
1. Interfaces
2. Classes
3. Algorithm
• Note: Collection interface is inside collection framework
• The two main interfaces of the Java Collection classes are the
Collection interface (java.util.Collection) and the Map interface
(java.util.Map).
• Java Collections can perform all operations on data such as searching,
sorting, insertion, manipulation, and so on.
• Java Collection Framework provides interfaces such as Set, List,
Queue, Deque, and classes such as ArrayList, Vector,
LinkedList, HashSet, PriorityQueue, TreeSet, and
LinkedHashSet.
• The Collection interface (java.util.Collection) and Map interface
(java.util.Map) are the two main “root” interfaces of Java collection
classes.
Hierarchy of Collection Framework
The Collection Interfaces
• Collection Interface: This enables you to work with groups of
objects. It is at the top of the collections hierarchy.
• List Interface: This extends Collection and an instance of List stores
an ordered collection of elements. It can have duplicate values.
• Set: This extends Collection to handle sets, which must contain
unique elements.
• SortedSet: This extends Set to handle sorted sets.
• The Map: This maps unique keys to values.
Advantages of the Collection Framework

• Reduces Programming effort: A programmer can focus more on


the
best use of the collection rather than focusing on the design of the
collection. This helps in implementing abstraction.
• Improves program speed: Collections provide a high-
performance implementation of data structures and this improves
performance.
List Interface
• This extends Collection and an instance of List stores an ordered
collection of elements.
• 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 :
• List <data-type> list1= new ArrayList();
• List <data-type> list2 = new LinkedList();
• List <data-type> list3 = new Vector();
• List <data-type> list4 = new Stack();
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.
Example
import java.util.*;
class LearnArrayList{
public static void main(String args[]){
ArrayList l=new ArrayList(); output:
[10, 20]
l.add(10);
l.add(20);
System.out.println(l);
}
}
Example

import java.util.*;
class LearnArrayList{
output:
public static void main(String args[]){
[10, 20]
ArrayList<Integer> l=new ArrayList<Integer>(); [10, 100, 20]
l.add(10);
l.add(20);
System.out.println(l);
l.add(1,100); //Adding at specific index
System.out.println(l);
}
}
Example
import java.util.*;
class Test {
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Pradipta");//Adding object in arraylist
list.add("Hrisikesh");
list.add("Pryanshu"); output:
list.add("Pravid");
//Traversing list through Iterator Pradipta
Iterator itr=list.iterator(); Hrisikesh
Pryanshu
while(itr.hasNext()){
Pravid
System.out.println(itr.next());
}
}
}
import java.util.*;
class ArrayListDemo {
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();
System.out.println("Initial size of al: " + al.size());
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " + al.size());
System.out.println("Contents of al: " + al);
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
}
}
import java.util.*;
class ArrayListToArray {
public static void main(String args[]) {
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(1);
al.add(2);
al.add(3);
al.add(4); Contents of al: [1, 2, 3, 4]
System.out.println("Contents of al: " + al); Sum is: 10
Integer ia[] = new Integer[al.size()];
ia = al.toArray(ia);
int sum = 0;
for(int i : ia)
sum += i;
System.out.println("Sum is: " + sum);
}
}

Sometimes we need to obtain an actual array that contains the contents of the list. We can do this by calling toArray( ),
which is defined by Collection.
Linked List class
• Java LinkedList class uses doubly linked list to store the elements. It
provides a linked-list data structure.
• It inherits the AbstractList class and implements List and Deque
interfaces.
• Java LinkedList class can contain duplicate elements.
• Java LinkedList class maintains insertion order.
• In Java LinkedList class, manipulation is fast because no shifting
needs to be occurred.
• Java LinkedList class can be used as list, stack or queue.
Traversing
import java.util.*;
class Test{
public static void main(String args[]){
LinkedList<Integer> list=new LinkedList<Integer>(); //Creating
arraylist
list.add(10);//Adding object in arraylist
list.add(20);
list.add(30);
list.add(40);
//Traversing list through Iterator
System.out.println(list);
}
}
output: [10, 20, 30, 40]
Three different way we can traverse the
list
1.
output:
for(int i=0;i<list.size();i++){ The elements are: 10
System.out.println("The elements are: "+list.get(i)); The elements are: 20
The elements are: 30
} The elements are: 40
2.
for(Integer ele:list){ output:
System.out.println("The elements are: "+ele); The elements are: 10
The elements are: 20
} The elements are: 30
The elements are: 40
Traverse the list using iterator

Iterator<Integer> it=list.iterator();
output:
while(it.hasNext()){ The elements are: 10
System.out.println("The elements are: "+it.next()); The elements are: 20
} The elements are: 30
The elements are: 40
Operation on list
• list.add(ele)
• list.add(index,ele) # add the eleement into the specific index O(n)time
• Updating eleement:
• list.set(2,55);
• Remove eleement
• list.remove(1)
• list.remove(Integer.valueOf(30)) //remove the specified value...
• Delete the entire list:
• list.clear()
• Search element avilable or not:
• list.contains(40) #return true/false
import java.util.*;
class Test{
public static void main(String args[]){
LinkedList<String> list=new LinkedList<String>();
//Creating arraylist
list.add("PKP");//Adding object in arraylist
list.add("Hrisikesh"); output:
Pradipta
list.add("Pryanshu");
Hrisikesh
list.add("Pravid"); Pryanshu
//Traversing list through Iterator Pravid
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
import java.util.*;
class LinkedListDemo {
public static void main(String args[]) {
LinkedList<String> ll = new LinkedList<String>();
ll.add("F"); ll.add("B"); ll.add("D"); ll.add("E"); ll.add("C"); Original contents of ll: [A, A2,
ll.addLast("Z"); ll.addFirst("A"); ll.add(1, "A2"); F, B, D, E, C, Z]
Contents of ll after deletion: [A,
System.out.println("Original contents of ll: " + ll);
A2, D, E, C, Z]
ll.remove("F");
ll after deleting first and last:
ll.remove(2); [A2, D, E, C]
System.out.println("Contents of ll after deletion: " + ll); ll after change: [A2, D, E
ll.removeFirst(); Changed, C]
ll.removeLast();
System.out.println("ll after deleting first and last: " + ll);
String val = ll.get(2);
ll.set(2, val + " Changed");
System.out.println("ll after change: " + ll);
}
}
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
OUTPUT:
this.publisher = publisher; 101 Let us C Yashwant Kanetkar BPB 8
this.quantity = quantity; 102 Data Communications & Networking
Forouzan Mc Graw Hill 4
} 103 Operating System Galvin Wiley 6
}
public class LinkedListDemo {
public static void main(String[] args) {
List<Book> list=new LinkedList<Book>();
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System", "Galvin","Wiley",6);
list.add(b1);
list.add(b2);
list.add(b3);
for(Book b:list) {
System.out.println(b.id+" "+b.name+" "+b.author+ " "+b.publisher+" "+b.quantity);
}
}
}
Difference between array list and Linked list
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.
import java.util.*;
class Test{
public static void main(String args[]){
Vector<String> vec=new Vector<String>();
vec.add("PKP"); //Adding object in arraylist
vec.add("Hrisikesh");
vec.add("Pryanshu");
vec.add("Pravid"); output:
Pradipta
//Traversing list through Iterator Hrisikesh
Iterator itr=vec.iterator(); Pryanshu
Pravid
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.
import java.util.Stack;
import java.util.*;
class Test{
public static void main(String args[]){
Stack<String> st= new Stack<String>();
st.push("Ayush");
st.push("Garvit");
st.push("Amit");
st.push("Ashish");
st.push("Garima");
st.pop();
Iterator itr=st.Iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
• The Queue interface present in the java.util package and extends
the Collection interface is used to hold the elements about to be
processed in FIFO(First In First Out) order.
• It is an ordered list of objects with its use limited to insert elements at
the end of the list and deleting elements from the start of the list.
• It follows the FIFO or the First-In-First-Out principle
• Since Queue is an interface, objects cannot be created of the type
queue. We always need a class which extends this list in order to
create an object.
import java.util.*;
class Test{
public static void main(String args[]){
Queue<Integer> q= new LinkedList<Integer>();
q.add(20);
q.add(30);
q.add(50);
System.out.println(q);
int rem = q.remove(); //Remove element
System.out.println("removed element-"+ rem );
int head = q.peek(); // To view the head of queue
System.out.println("head of queue-"+ head);
System.out.println(q)
}
}
PriorityQueue
• The PriorityQueue class implements the Queue interface. It holds the
elements or objects which are to be processed by their priorities.
PriorityQueue doesn't allow null values to be stored in the queue.
• A PriorityQueue is used when the objects are supposed to be processed based
on the priority.
• The PriorityQueue is based on the priority heap. The elements of the priority
queue are ordered according to the natural ordering, or by a Comparator
provided at queue construction time, depending on which constructor is used.
• PriorityQueue doesn’t permit NULL pointers.
• We can’t create PriorityQueue of Objects that are non-comparable.
• PriorityQueue are unbound queues.
• It inherits methods from AbstractQueue, AbstractCollection, Collection and
Object class.
import java.util.*;
class Test{
public static void main(String args[]){
Queue<Integer> q= new PriorityQueue<Integer>();
q.add(100); //While adding, it create the min-priority queue
q.add(30);
output:
q.add(55); [30, 70, 55, 100]
q.add(70); removed element-30
System.out.println(q); head of queue-30
[30, 70, 55, 100]
System.out.println("removed element-"+ q.peek());
int head = q.peek();
System.out.println("head of queue-"+ head);
System.out.println(q);
}
}
Remove elements from queue
• queue.remove();
• queue.poll();
import java.util.*;
class Test{
public static void main(String args[]){
Queue<Integer> q= new PriorityQueue<Integer>();
q.add(100); //While adding, it create the min-priority queue
q.add(30);
q.add(55);
q.add(70);
[30, 70, 55, 100]
System.out.println(q); head of queue-30
int head = q.poll(); [55, 70, 100]
System.out.println("head of queue-"+ head);
System.out.println(q);
}
}
class Exercise {
public static void main(String[] args){
PriorityQueue<String> pq1 = new PriorityQueue<String>();
pq1.add("Red"); pq1.add("Green"); //While adding, it create the priority queue
pq1.add("Black"); pq1.add("White");
System.out.println("First Priority Queue: "+pq1);
PriorityQueue<String> pq2 = new PriorityQueue<String>();
pq2.add("Red"); pq2.add("Pink");
pq2.add("Black"); pq2.add("Orange");
System.out.println("Second Priority Queue: "+pq2);
//comparison output in Priority Queue
for (String element : pq1){
System.out.println(pq2.contains(element) ? "Yes" : "No");
}
}
}
First Priority Queue: [Black, Red, Green,
White]
Second Priority Queue: [Black, Orange,
Pink, Red]
Yes
Yes
No
No
import java.util.*;
class Example {
public static void main(String args[]) {
PriorityQueue<String> pQueue = new PriorityQueue<String>();
pQueue.add("C");
pQueue.add("C++");
pQueue.add("Java");
pQueue.add("Python");
System.out.println("Head value using peek function:"+ pQueue.peek());
System.out.println("The queue elements:"+pQueue);
pQueue.poll();
System.out.println("After removing an element with poll function, the queue elements: "+pQueue);
pQueue.remove("Java");
System.out.println("After removing Java with remove function:"+pQueue);
boolean b = pQueue.contains("C");
System.out.println ( "Priority queue contains C or not?: " + b);
Object[] arr = pQueue.toArray();
System.out.println ( "Value in array: ");
for (int i = 0; i<arr.length; i++)
System.out.println ( "Value: " + arr[i].toString()) ;
}
Head value using peek function:C
The queue elements:[C, C++, Java, Python]
After removing an element with poll function, the queue
elements: [C++, Python, Java]
After removing Java with remove function:[C++, Python]
Priority queue contains C or not?: false
Value in array:
Value: C++
Value: Python
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<data-type> s1 = new HashSet<data-type>();
• Set<data-type> s2 = new LinkedHashSet<data-type>();
• Set<data-type> s3 = new TreeSet<data-type>();
import java.util.*;
class Test{
public static void main(String args[]){
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
Iterator<String> itr=set.iterator(); output:
while(itr.hasNext()){ Vijay
System.out.println(itr.next());
}
Ajay
} Ravi
}
• 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.
import java.util.*;
class Test{
public static void main(String args[]){
LinkedHashSet<String> set=new
LinkedHashSet<String>(); output
set.add("Ravi"); :
set.add("Vijay"); Ravi
set.add("Ravi");
set.add("Ajay");
Vijay
Iterator<String> itr=set.iterator(); Ajay
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
SortedSet Interface
• SortedSet is the alternate of Set interface that provides a total
ordering on its elements. The elements of the SortedSet are arranged
in the increasing (ascending) order. The SortedSet provides the
additional methods that inhibit the natural ordering of the elements
• SortedSet<data-type> set = new TreeSet();
TreeSet

• 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.*;
class Test{
public static void main(String args[]){
TreeSet<String> set=new TreeSet<String>();
set.add("Ravi"); output:
set.add("Vijay");
Ajay
set.add("Ravi");
set.add("Ajay"); Ravi
Iterator<String> itr=set.iterator(); Vijay
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Write a Java program to create a new tree set, add some colors
(string) and print out the tree set.

import java.util.TreeSet;
class Exercise {
public static void main(String[] args) {
TreeSet<String> tree_set = new
TreeSet<String>(); output:
tree_set.add("Red"); Tree set:
tree_set.add("Green"); [Black, Green, Orange, Red, White]
tree_set.add("Orange");
tree_set.add("White");
tree_set.add("Black");
System.out.println("Tree set: ");
System.out.println(tree_set);
}
}
Get the first and last elements in a tree
set.

// Find first element of the tree set


Object first_element = tree_set.first();
System.out.println("First Element is: "+first_element);

// Find last element of the tree set

Object last_element = tree_set.last();


System.out.println("Last Element is: "+last_element);
Map interface
• A map contains values on the basis of key, i.e. key and value pair. Each
key and value pair is known as an entry.
• A Map contains unique keys.
• A Map is useful if you have to search, update or delete elements on
the basis of a key.
• A Map doesn't allow duplicate keys, but you can have duplicate
values.
• HashMap and LinkedHashMap allow null keys and values, but
TreeMap doesn't allow any null key or value.

You might also like