Anda di halaman 1dari 364

WHY JAVA?

HISTORY OF JAVA-
The history of Java is very interesting. Java was originally designed for interactive television, but
it was too advanced technology for the digital cable television industry at the time. The history
of java starts from Green Team. Java team members (also known as Green Team), initiated this
project to develop a language for digital devices such as set-top boxes, televisions etc. But, it was
suited for internet programming. Later, Java technology was incorporated by Netscape
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in
June 1991. The small team of sun engineers called Green Team.
2) Originally designed for small, embedded systems in electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
WHAT IS JAVA?
Java is a programming language and a platform.
Java is a high level, robust, secured and object-oriented programming language.
Platform: Any hardware or software environment in which a program runs, is known as a
platform. Since Java has its own runtime environment (JRE) and API, it is called platform.
Features of Java
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Dynamic
8. Multithreaded
9. Distributed over the internet
10. Generics
11. Collection
Types of Java App
Java SE (Standard Edition)
Java EE (Enterprise Edition)
Java MC (Micro Edition)
Java TV (Television Edition)
Java Card (Sim Card)
Types of Applications Made by Java
Standalone Application
Mobile Application
Web Application
Enterprise Application
Naming Convention
Java naming convention is a rule to follow as you decide what to name your identifiers such as
class, package, variable, constant, method etc.
But, it is not forced to follow. So, it is known as convention not rule.
All the classes, interfaces, packages, methods and fields of java programming language are given
according to java naming convention.
Hello World Program
class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
Internal Programming of Java Program

At compile time, java file is compiled by Java Compiler (It does not interact with OS)
and converts the java code into bytecode.
What happens at Runtime?
Classloader: is the subsystem of JVM
that is used to load class files.

Bytecode Verifier: checks the code


fragments for illegal code that can violate
access right to objects.

Interpreter: read bytecode stream then


execute the instructions.
Can you save a java source file by other
name than the class name?
Yes, if the class is not public. It is explained in the figure given below:
Can you have multiple classes in a java
source file?
Yes, like the figure given below illustrates:
JDK
JDK is an acronym for Java Development Kit. It physically exists. It contains JRE + development
tools.
JRE
JRE is an acronym for Java Runtime Environment. It is used to provide runtime environment. It is
the implementation of JVM. It physically exists. It contains set of libraries + other files that JVM
uses at runtime.
Implementation of JVMs are also actively released by other companies besides Sun Micro
Systems.
JVM
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform
dependent because configuration of each OS differs. But, Java is platform independent. There
are three notions of the JVM: specification, implementation, and instance.
The JVM performs following main tasks:
1. Loads code
2. Verifies code
3. Executes code
4. Provides runtime environment
What is JVM?
It is:
A specification where working of Java Virtual Machine is specified. But implementation provider
is independent to choose the algorithm. Its implementation has been provided by Sun and other
companies.
An implementation Its implementation is known as JRE (Java Runtime Environment).
Runtime Instance Whenever you write java command on the command prompt to run the java
class, an instance of JVM is created.
What JVM does?
The JVM performs following operation:
1. Loads code
2. Verifies code
3. Executes code
4. Provides runtime environment
Variables In JAVA
A variable is a container which holds the value while the java program is executed. A variable is
assigned with a datatype.
 Variable is a name of memory location. There are three types of variables in java: local,
instance and static.
Types of Variables
There are three types of variables
in java:
1. local variable
2. instance variable
3. static variable
Types of Variables
1. Local Variable:
A variable declared inside the method is called local variable.
2. Instance Variable:
A variable declared inside the class but outside the method, is called instance
variable . It is not declared as static.
3. Static variable:
A variable which is declared as static is called static variable. It cannot be local.
Datatypes In Java
Data types represent the different values
to be stored in the variable. In java, there
are two types of data types:

 Primitive data types

 Non-primitive data types


Java Heap Memory
Heap Memory is created by the
Java Virtual Machine when it
starts. The memory is used as
long as the application is
running.
When an object is created, it is
always created in Heap and has
global access. That means all
objects can be referenced from
anywhere in the application.
Java Stack Memory
Stack Memory is the temporary
memory where variable values
are stored when their methods
are invoked. After the method is
finished, the memory containing
those values is cleared to make
room for new methods.
When a new method is invoked,
a new block of memory will be
created in the Stack.
Example Of Heap and Stack Memory
class Student8{ ..void display ()
int rollno; {
System.out.println(rollno+" "+name+" "+coll
String name; ege);}
static String college ="ITS";
public static void main(String args[]){
Student8 s1 = new Student8(111,"Karan");
Student8(int r,String n){
Student8 s2 = new Student8(222,"Aryan");
rollno = r;
name = n; s1.display();
} .. s2.display();
}
}
Operators in Java
Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in java which are given below:
1. Unary Operator,
2. Arithmetic Operator,
3. Relational Operator,
4. Bitwise Operator,
5. Logical Operator,
6. Ternary Operator and
7. Assignment Operator.
Types of Operators
Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%

additive +-

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ?:

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=


How to take input from user?
package InputOutput; String name=sc.next();
System.out.println("Enter your fee");
import java.util.Scanner; double fee=sc.nextDouble();
class WrapperClass{ System.out.println("Rollno:"+rollno+"
name:"+name+" fee:"+fee);
public static void main(String args[]){ sc.close(); } }
Scanner sc=new Scanner(System.in);

System.out.println("Enter your rollno");


int rollno=sc.nextInt();
System.out.println("Enter your name");
BufferReader and Input Stream
import java.io.*;
public class CalcArea
{
public static void main ( String args[] ) throws IOException
{
System.out.print ( "Enter the radius: " );

BufferedReader input = new BufferedReader ( new InputStreamReader ( System.in ) );

String inputString = input.readLine();

double radius = Double.parseDouble ( inputString );


double area = 3.14159 * radius * radius;

System.out.println ( "Area is: " + area ); }}


Control Statements In Java
1. Java If-else Statement
2. Java Switch Statement
3. Java For Loop
4. Java While Loop
5. Java do-while Loop
6. Java Break Statement
7. Java Continue Statement
Java If-else Statement
The Java if statement is used to test the condition. It checks boolean
condition: true or false.
There are various types of if statement in java.
1. if statement
2. if-else statement
3. if-else-if ladder
4. nested if statement
Java if Statement
The Java if statement tests the condition. It executes the if block if condition is true.

public class IfExample {


public static void main(String[] args) {
int age=20;

if(age>18)
{

System.out.print("Age is greater than 18");

}
}
}
Java if-else Statement
The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed. public class IfElseExample
{
public static void main(String[] args)
{
int number=13;
if(number%2==0)
{
System.out.println("even number");
}
else
{
System.out.println("odd number");
}
}
}
Java if-else-if ladder Statement
The if-else-if ladder statement executes one condition from multiple statements.
Program For if-else-if Ladder
..}
public class IfElseIfExample { else if(marks>=70 && marks<80)
public static void main(String[] args) { {
System.out.println("B grade");
int marks=65; }
else if(marks>=80 && marks<90)
{
if(marks<50){ System.out.println("A grade");
System.out.println("fail"); }
else if(marks>=90 && marks<100)
} {
else if(marks>=50 && marks<60){ System.out.println("A+ grade");
}
System.out.println("D grade"); else
} {
System.out.println("Invalid!");
else if(marks>=60 && marks<70){ }
System.out.println("C grade"); .. }
}
Java Switch Statement
The Java switch statement executes one statement from multiple conditions. It is like if-else-if
ladder statement.
Program of Switch Statement
public class SwitchExample {
public static void main(String[] args) {
int number=20;
switch(number){
case 10: System.out.println("10");break;
case 20: System.out.println("20");break;
case 30: System.out.println("30");break;
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Java For Loop
The Java for loop is used to iterate a part of the program several times. If the
number of iteration is fixed, it is recommended to use for loop.

There are three types of for loops in java.


1. Simple For Loop
2. For-each or Enhanced For Loop
3. Labeled For Loop
Simple For Loop
public class ForExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
System.out.println(i);
}
}
}
Java for-each Loop
The for-each loop is used to traverse array or collection in java. It is easier to use than simple for
loop because we don't need to increment value and use subscript notation.

public class ForEachExample


{
public static void main(String[] args)
{
int arr[]={12,23,44,56,78};
for(int i:arr)
{
System.out.println(i);
}
}
}
Java Labeled For loop
We can have name of each for loop. To do so, we use label before the for loop. It is useful if we
have nested for loop so that we can break/continue specific for loop.
public class LabeledForExample
{
public static void main(String[] args)
{
aa:
for(int i=1;i<=3;i++)
{
bb:
for(int j=1;j<=3;j++)
{
if(i==2&&j==2)
{
break aa;
}
System.out.println(i+" "+j);
}
}
}
}
Java While Loop
The Java while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed, it is recommended to use while loop.

public class WhileExample


{
public static void main(String[] args)
{
int i=1;
while(i<=10)
{
System.out.println(i);
i++;
}
}
}
Java do-while Loop
The Java do-while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed and you must have to execute the loop at least once, it is recommended to
use do-while loop.
public class DoWhileExample
{
public static void main(String[] args)
{
int i=1;
do
{
System.out.println(i);
i++;
}
while(i<=10);
}
}
Java Break Statement
The Java break is used to break loop or
switch statement. It breaks the current flow
of the program at specified condition. In case
of inner loop, it breaks only inner loop.
Program of Break Statement
public class BreakExample {
public static void main(String[] args) {
for(int i=1;i<=10;i++){
if(i==5){
break;
}
System.out.println(i);
}
}
}
Java Continue Statement
The Java continue statement is used to continue loop. It continues the current flow of the
program and skips the remaining code at specified condition. In case of inner loop, it continues
only inner loop.
public class ContinueExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
if(i==5)
{
continue;
}
System.out.println(i);
}
}
}
Java OOPs Concepts
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a
methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Object And Class
Object :
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class :
Collection of objects is called class. It is a logical entity.
Inheritance and Polymorphism
Polymorphism :
When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.

Inheritance :
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Abstraction and Encapsulation
Abstraction :
Hiding internal details and showing functionality is known as abstraction. For example: phone
call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.

Encapsulation :
Binding (or wrapping) code and data together into a single unit is known as encapsulation. For
example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.
Encapsulation In Java
Encapsulation in java is a process of wrapping
code and data together into a single unit, for
example capsule i.e. mixed of several medicines.

We can create a fully encapsulated class in java by


making all the data members of the class private.
Now we can use setter and getter methods to set
and get the data in it.
The Java Bean class is the example of fully
encapsulated class.
Simple example of encapsulation in java
//save as Student.java //save as Test.java
package com.javatpoint; package java;
class Test
public class Student{
{
private String name; public static void main(String[] args)
{
Student s=new Student();
public String getName(){
s.setName("vijay");
return name; System.out.println(s.getName());
} }
}
public void setName(String name){
this.name=name
} Output: vijay
}
Access Modifiers in Java
The access modifiers in java specifies
accessibility (scope) of a data member,
method, constructor or class.
There are 4 types of java access
modifiers:
1. private
2. default
3. protected
4. public
There are many non-access modifiers
such as static, abstract etc.
private access modifier
The private access modifier is accessible only within class.
class A
{
private int data=40;
In this example, we have
private void msg() created two classes A and
{ Simple. A class contains
System.out.println("Hello java"); Private access modifier private data member and
} private method. We are
} accessing these private
public class Simple{ members from outside the
public static void main(String args[]){
class, so there is compile
A obj=new A();
System.out.println(obj.data);//Compile Time Error
time error.

obj.msg();//Compile Time Error


}
}
default access modifier
If you don't use any modifier, it is treated as default by default. The default modifier
is accessible only within package.

In this example, we have package pack;


created two packages class A{ //save by A.java
void msg()
pack and mypack. {System.out.println("Hello");}
}
package mypack;
import pack.*;
In the above example, the class B{
scope of class A and its public static void main(String args[])
{
method msg() is default so //save by B.java A obj = new A();//Compile Time Error
it cannot be accessed from obj.msg();//Compile Time Error
outside the package. }
}
protected access modifier
The protected access modifier is accessible //save by A.java
within package and outside the package but package pack;
through inheritance only. public class A{
protected void msg() Output: Hello
The protected access modifier can be applied {System.out.println("Hello");}
on the data member, method and }
constructor. It can't be applied on the class.
In this example, we have created the two
packages pack and mypack. The A class of //save by B.java
pack package is public, so can be accessed package mypack;
from outside the package. But msg method import pack.*;
of this package is declared as protected, so it class B extends A{
can be accessed from outside the class only public static void main(String args[]){
through inheritance. B obj = new B();
obj.msg();
}
}
public access modifier
The public access modifier is accessible everywhere. It has the widest scope
among all other modifiers.

//save by B.java
//save by A.java
package mypack;
import pack.*;
package pack;
class B{
public class A{
public static void main(String args[]){
public void msg()
A obj = new A();
{System.out.println("Hello");}
obj.msg();
}
}
}

Output: Hello
Understanding Java Modifiers
Access Modifier within class within package outside package by outside package
subclass only

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y
Fibonacci series in Java
In fibonacci series, next number is the class FibonacciExample1
sum of previous two numbers for {
example 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 public static void main(String args[])
{
etc. The first two numbers of fibonacci int n1=0,n2=1,n3,i,count=10;
series are 0 and 1. System.out.print(n1+" "+n2);
//printing 0 and 1
for(i=2;i<count;++i)
Output //loop starts from 2 because 0 and 1 are alread
y printed
{
0 1 1 2 3 5 8 13 21 34 n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}}
Armstrong Number in Java
Armstrong Number in Java: A positive number is called armstrong number if it is equal to the
sum of cubes of its digits for example 0, 1, 153, 370, 371, 407 etc.
public class Arm {
153 = (1*1*1)+(5*5*5)+(3*3*3)
public static void main (String [] args)
{
where: int n= 155;
int temp = n;
(1*1*1)=1 int r,sum=0;

(5*5*5)=125 while(n>0)
{
r=n%10;
(3*3*3)=27 n= n/10;
sum = sum + r*r*r;
So: }
1+125+27=153 if (temp == sum){
System.out.println(“it is an Armstrong number”);}
else {
System.out.println(“it is not an Armstrong number”);}
Factorial number in java
class FactorialExample{
public static void main(String args[])
{
int i,fact=1; Output
int number=5;//It is the number to calculate factorial
for(i=1;i<=number;i++){ Factorial of 5 is : 120
fact=fact*i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Palindrome Number in Java
class PalindromeExample{ }
public static void main(String args[]){ if(temp==sum)
System.out.println("palindrome number ");
int r,sum=0,temp;
else
int n=454; System.out.println("not palindrome");
}
}
temp=n;
while(n>0){ A palindrome number is a number that is
same after reverse.
r=n%10; //getting remainder
For example 545, 151, 34543, 343, 171,
sum=(sum*10)+r; 48984.
n=n/10;
Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors
of parent object. It is an important part of OPPs(Object Oriented programming system).

Why use inheritance in java

• For Method Overriding (so runtime polymorphism


can be achieved).

• For Code Reusability.


Types of inheritance in java
Single Inheritance Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark(); Output barking... eating...
d.eat();
}}
Multilevel Inheritance Example
class Animal{ class TestInheritance2{
void eat(){System.out.println("eating...");} public static void main(String args[]){
BabyDog d=new BabyDog();
} d.weep();
class Dog extends Animal{ d.bark();
d.eat();
void bark(){System.out.println("barking...");} }}
}
Output weeping... barking... eating...
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
Hierarchical Inheritance Example
class Animal{ class TestInheritance3{
public static void main(String args[]){
void eat(){System.out.println("eating...");}
Cat c=new Cat();
} c.meow();
class Dog extends Animal{ c.eat();
//c.bark();//C.T.Error
void bark(){System.out.println("barking...");} }}
}
Output meowing... eating...
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
Why multiple inheritance is not supported
in java?
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
Compile Time Error

class C extends A,B{//suppose if it were

Public Static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Polymorphism in Java
Method Overloading in Java:
If a class has multiple methods having same name but different in parameters, it is
known
as Method Overloading.
If we have to perform only one operation, having same name of the methods increases
the readability of the program.
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
Method Overloading: changing data type
of arguments
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
} Output 22 24.9
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Method Overloading: changing no. of
arguments
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
} Output 22 33

class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java.
In other words, If subclass provides the specific implementation of the method that has been
provided by one of its parent class, it is known as method overriding.
Rules for Java Method Overriding :
1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).
Example of Method Overriding
class Vehicle{
void run(){System.out.println("Vehicle is running");} Output
}
Bike is running safely
class Bike2 extends Vehicle{
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();
obj.run();
}
Java static keyword
The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the
class than instance of the class.
The static can be:
1. variable (also known as class variable)
2. method (also known as class method)
3. block
4. nested class
Example for Static Keyword
class Counter2{ public static void main(String args[])
static int count=0; {
Counter2 c1=new Counter2();
//will get memory only once and retain its value
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
Counter2(){ }
}
count++;
System.out.println(count);
}
Output: 1 2 3
Types of Classes
1. Java Inner Class
2. Abstract Class
3. Final Class
4. Singleton Class
Java Inner Class
Java inner class or nested class is a class which is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place so that it can be more
readable and maintainable.
Additionally, it can access all the members of outer class including private data members and
methods.
Types of Inner Classes

1. Member inner class

2. Anonymous inner class

3. Static Inner Class


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

class TestMemberOuter1
{
private int data=30;
class Inner Output
{
void msg(){System.out.println("data is "+data); data is 30
} }
public static void main(String args[])
{
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}
Java Anonymous inner class
A class that have no name is known as anonymous inner class in java. It should be used if you
have to override method of class or interface. Java Anonymous inner class can be created by two
ways:
1. Class (may be abstract or concrete).
2. Interface

Anonymous
Class in Java
Java anonymous inner class example
using class
abstract class Person{
abstract void eat();
}
class TestAnonymousInner{
Output
public static void main(String args[]){
Person p=new Person(){ nice fruits
void eat(){System.out.println("nice fruits");}
};
p.eat();
}
}
Java anonymous inner class example
using interface
interface Eatable{
void eat();
}
class TestAnnonymousInner1{ Output
public static void main(String args[]){
Eatable e=new Eatable(){ nice fruits
public void eat(){System.out.println("nice fruits");}
};
e.eat();
}
}
Java static Inner class
A static class i.e. created inside a class is called static nested class in java. It cannot access non-
static data members and methods. It can be accessed by outer class name.
It can access static data members of outer class including private.
Static nested class cannot access non-static (instance) data member or method

Static Inner
Class in Java
Java static Inner class example with
instance method
class TestOuter1{
static int data=30;
static class Inner{
void msg(){System.out.println("data is "+data);} Output
}
public static void main(String args[]){ data is 30
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}
Abstract Class in Java
A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.
Abstraction in Java :

Abstraction is a process of hiding the implementation details and showing only


functionality to the user.

Another way, it shows only important things to the user and hides the internal details
for example sending sms, you just type the text and send the message. You don't
know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
1.Abstract class (0 to 100%)
2.Interface (100%)
Final Class in Java
If you make any class as final, you cannot extend it.

final class Bike{}

class Honda1 extends Bike{


void run()
Output: Compile Time Error
{System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}
Singleton Class In Java
In object-oriented programming, a singleton class is a class that can have only
one object (an instance of the class) at a time.
We can make constructor as private. ...
This property is useful to create singleton class in java.
Singleton pattern helps us to keep only one instance of a class at any time.
The purpose of singleton is to control object creation by keeping private
constructor.
Constructor in Java
In Java, constructor is a block of codes similar to method. It is called when an instance of object
is created and memory is allocated for the object.
It is a special type of method which is used to initialize the object.

Rules for creating java constructor :


There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
Types of Constructor
There are two types of constructors in java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.

class Bike1 Rule: If there is no constructor in a class,


{ compiler automatically creates a default
Bike1() constructor.
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}

Output Bike is created


Java parameterized constructor
A constructor which has a specific number of parameters is called parameterized constructor.

class Student4{
int id;
String name;

Student4(int i,String n){


id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display(); Output 111 Karan 222 Aryan
}
}
Constructor Overloading in Java
In Java, a constructor is just like a method but without return type. It can also be overloaded like
Java methods.
class Student5 …void display()
{ {
int id; System.out.println(id+" "+name+" "+age);
String name; }
int age; public static void main(String args[])
Student5(int i,String n) {
{ Student5 s1 = new Student5(111,"Karan");
id = i; Student5 s2 = new Student5(222,"Aryan",25);
name = n; s1.display();
} s2.display();
Student5(int i,String n,int a) }
{ }
id = i;
name = n;
age=a;
Output 111 Karan 0 222 Aryan 25
} …
Difference between constructor and
method in java
Java Constructor Java Method

• Constructor is used to initialize the • Method is used to expose behaviour of


state of an object. an object.

• Constructor must not have return type. • Method must have return type.

• Constructor is invoked implicitly. • Method is invoked explicitly.

• The java compiler provides a default • Method is not provided by compiler in


constructor if you don't have any any case.
constructor.

• Constructor name must be same as the • Method name may or may not be same
class name. as class name.
Java Copy Constructor
There is no copy constructor in java. But, we can copy the values of one object to another like
copy constructor in C++.
class Student6{ … void display()
int id; {
String name; System.out.println(id+" "+name);
Student6(int i,String n){ }
id = i; public static void main(String args[])
name = n; {
} Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
Student6(Student6 s){ s1.display();
id = s.id; s2.display();
name =s.name; }
} …. } Output 111 Karan 111 Karan
Constructor Chaining
class Temp // parameterized constructor 2
{ Temp(int x)
{
// default constructor 1 // calls constructor 3
this(5, 15);
// default constructor will call another constructor System.out.println(x);
// using this keyword from same class }
// parameterized constructor 3
Temp() Temp(int x, int y)
{
{
System.out.println(x * y);
// calls constructor 2 }
public static void main(String args[]) Output
this(5); {
// invokes default constructor first
System.out.println("The Default constructor"); 75
new Temp();
5
} }
} The Default constructor
Java Packages
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Advantages of Java Package :

1. Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2. Java package provides access protection.
3. Java package removes naming collision.
Types of Packages
Simple example of java package
//save as Simple.java

package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to access package from another
package?
There are three ways to access the package from outside
the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1. Using packagename.*
The import keyword is used to make the classes and interface of another package accessible to
the current package

//save by A.java //save by B.java

package pack; package mypack;


public class A{ import pack.*;
public void msg() class B
{ {
System.out.println("Hello"); public static void main(String args[])
} {
} A obj = new A();
obj.msg();
}
} Output Hello
2. Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.

//save by A.java //save by B.java

package pack; package mypack;


public class A{ import pack.A;
public void msg() class B
{ {
System.out.println("Hello"); public static void main(String args[])
} {
} A obj = new A();
obj.msg();
}
} Output Hello
3. Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
. //save by B.java
//save by A.java
package mypack;
package pack; class B
public class A{ {
public void msg() public static void main(String args[])
{ {
System.out.println("Hello"); pack.A obj = new pack.A();
} //using fully qualified name
} obj.msg();
}
} Output Hello
Sequence of the program must be
package then import then class.
Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in java is a mechanism to achieve abstraction. There can be only abstract methods
in the java interface not method body. It is used to achieve abstraction and multiple inheritance
in Java.
In other words, you can say that interfaces can have methods and variables but the methods
declared in interface contain only method signature, not body.

Java Interface also represents IS-A relationship.


It cannot be instantiated just like abstract class.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
1. It is used to achieve abstraction.
2. By interface, we can support the functionality of multiple inheritance.
3. It can be used to achieve loose coupling

How to declare interface?


Interface is declared by using interface keyword. It provides total abstraction; means all the
methods in interface are declared with empty body and are public and all fields are public, static
and final by default. A class that implement interface must implement all the methods declared
in the interface.
Internal addition by compiler
In other words, Interface fields are public, static and final by default,
and methods are public and abstract.
Understanding relationship between
classes and interfaces
As shown in the figure given below, a class extends another class, an
interface extends another interface but a class implements an
interface.
Java Interface Example
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");
}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
Output Hello
} }
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends
multiple interfaces i.e. known as multiple inheritance.
Example of multiple inheritance by
Interface
interface Printable{ public static void main(String args[]){
A7 obj = new A7();
void print();
obj.print();
} obj.show();
interface Showable{ }
}
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");
} Output Hello Welcome
Interface inheritance
A class implements interface but one interface extends another interface .
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");
}
public static void main(String args[]){
TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
} Output Hello Welcome
}
Java 8 Default Method in Interface
Since Java 8, we can have method body in interface. But we need to make it default method.
Let's see an example:
interface Drawable class TestInterfaceDefault
{ {
void draw(); public static void main(String args[])
default void msg() {
{ Drawable d=new Rectangle();
System.out.println("default method"); d.draw();
} d.msg();
} }
class Rectangle implements Drawable{ }
public void draw()
{
System.out.println("drawing rectangle");
drawing rectangle
} Output
} default method
Java 8 Static Method in Interface
Since Java 8, we can have static method in interface. Let's see an example:
interface Drawable class TestInterfaceStatic
{ {
void draw(); public static void main(String args[])
static int cube(int x) {
{ Drawable d=new Rectangle();
return x*x*x; d.draw();
} System.out.println(Drawable.cube(3));
} }
class Rectangle implements Drawable }
{
public void draw()
{
System.out.println("drawing rectangle"); drawing rectangle
} Output
} 27
super keyword in java
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 java super Keyword :
super can be used to refer immediate parent class instance variable.
super can be used to invoke immediate parent class method.
super() can be used to invoke immediate parent class constructor.
super is used to refer immediate parent
class instance variable.
We can use super keyword to access the data member or field of parent class. It is used if parent
class and child class have same fields.
class Animal class TestSuper1
{ {
String color="white"; public static void main(String args[])
} {
class Dog extends Animal Dog d=new Dog();
{ d.printColor();
String color="black"; }
void printColor() }
{
System.out.println(color);//prints color of Dog class

System.out.println(super.color);//prints color of Animal


Output black white
}
}
super can be used to invoke parent class
method
class Animal …void bark()
{ {
void eat() System.out.println("barking...");
{ }
System.out.println("eating..."); void work()
} {
} super.eat();
class Dog extends Animal bark();
{ }
void eat() }
{ class TestSuper2
System.out.println("eating bread..."); {
}… public static void main(String args[])
{
Dog d=new Dog();
d.work();
Output eating... barking... }
}
super is used to invoke parent class
constructor.
class Animal class TestSuper3
{ {
Animal(){System.out.println("animal is created"); public static void main(String args[])
{
} Dog d=new Dog();
} }
class Dog extends Animal{ }

Dog(){
super();
System.out.println("dog is created"); animal is created
Output
} dog is created
}
super() is added in each class constructor automatically
by compiler if there is no super() or this().
super example: real use
class Person{ class Emp extends Person
{
int id; float salary;
String name; Emp(int id,String name,float salary)
{
Person(int id,String name){ super(id,name);//reusing parent constructor
this.salary=salary;
this.id=id; }
this.name=name; void display(){
System.out.println(id+" "+name+" "+salary);}
} }
class TestSuper5{
}
public static void main(String[] args){
Emp e1=new Emp(1,"ankit",45000f);
Output 1 ankit 45000 e1.display();
}}
java instanceof operator
The java instanceof operator is used to test whether the object is an instance of the specified
type (class or subclass or interface). The instanceof in java is also known as type comparison
operator because it compares the instance with type. It returns either true or false.
Simple example of java instanceof :
class Simple1{
public static void main(String args[]){
Output true
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);//true
}
}
instanceof in java with a variable that
have null value
If we apply instanceof operator with a variable that have null value, it returns false. Let's see the
example given below where we apply instanceof operator with the variable that have null value.

class Dog2
{
public static void main(String args[]){ Output false
Dog2 d=null;
System.out.println(d instanceof Dog2);//false
}
}
Downcasting with java instanceof
operator
class Animal { } public static void main (String [] args)
class Dog3 extends Animal {
Animal a=new Dog3();
{
Dog3.method(a);
static void method(Animal a) }
{ }

if(a instanceof Dog3){


Dog3 d=(Dog3)a;//downcasting
System.out.println("ok downcasting performed");
}
} Output ok downcasting performed
Java Array
Normally, array is a collection of similar type of elements that have contiguous memory location.
Java array is an object the contains elements of similar data type. It is a data structure where we
store similar elements. We can store only fixed set of elements in a java array.
Array in java is index based, first element of the array is stored at 0 index.
Advantage & Disadvantage of Java Array
Advantage of Java Array :
1. Code Optimization : It makes the code optimized, we can retrieve or sort the
data easily.
2. Random access : We can get any data located at any index position.

Disadvantage of Java Array :


1. Size Limit : We can store only fixed size of elements in the array. It doesn't
grow its size at runtime. To solve this problem, collection framework is used
in java.
Types of Array in java
There are two types of array.
1. Single Dimensional Array
2. Multidimensional Array
Single Dimensional Array in java
class Testarray{ //printing array
public static void main(String args[]) for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
{
}
int a[]=new int[5];//declaration and instantiation }
a[0]=10;//initialization 10
a[1]=20; Output 20
a[2]=70;
a[3]=40; 70
a[4]=50; 40
50
Declaration, Instantiation and
Initialization of Java Array
class Testarray1
{
33
public static void main(String args[]) Output
{ 3
int a[]={33,3,4,5};//declaration, instantiation and initialization 4
//printing array 5
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Passing Array to method in java
We can pass the java array to method so that we can reuse the same logic on any array.
class Testarray2
{
static void min(int arr[])
{
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
Output 3
min=arr[i];
System.out.println(min);
}
public static void main(String args[])
{
int a[]={33,3,4,5};
min(a);//passing array to method
}
}
Multidimensional array in java
class Testarray3{
public static void main(String args[])
{
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; 123
//printing 2D array Output 245
for(int i=0;i<3;i++){ 445
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
} System.out.println();
}}}
What is the class name of java
array?
In java, array is an object. For array object, an proxy class is created whose name can be
obtained by getClass().getName() method on the object.

class Testarray4{
public static void main(String args[]){

int arr[]={4,4,5}; Output I


Class c=arr.getClass();
String name=c.getName();

System.out.println(name);

}}
Copying a java array
class TestArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
Output caffein

System.arraycopy(copyFrom, 2, copyTo, 0, 7);


System.out.println(new String(copyTo));
}
}
Addition of 2 matrices in java
class Testarray5{ //adding and printing addition of 2 matrices
public static void main(String args[]){ for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
//creating two matrices c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
int a[][]={{1,3,4},{3,4,5}};
}
int b[][]={{1,3,4},{3,4,5}}; System.out.println();//new line
}

}} 44

int c[][]=new int[2][3];


268
Output
6 8 10
//adding and printing addition of 2 matrices
Type Casting
Assigning a value of one type to a variable of another type is known as Type
Casting.
Types of Type Casting in Java
In Java, type casting is classified into two types,

1. Widening Casting(Implicit)

2. Narrowing Casting(Explicitly done)


Widening Casting(Implicit)
Automatic Type casting take place when, public class Test
{
 The two types are compatible public static void main(String[] args)
 The target type is larger than the source type {
int i = 100;
long l = i;
float f = l;
System.out.println("Int value "+i);
Output System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
Int value 100
Long value 100 }
Float value 100.0
Narrowing or Explicit type conversion
When you are assigning a larger type value to a variable of smaller type, then you need to
perform explicit type casting.
public class Test
{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required
Output
System.out.println("Double value "+d);
System.out.println("Long value "+l); Double value 100.04
System.out.println("Int value "+i); Long value 100
} Int value 100
}
Wrapper class in Java
Wrapper class in java provides the mechanism to convert primitive into object and object into
primitive.
Primitive Type Wrapper class

boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Wrapper class Example: Primitive to
Wrapper
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
System.out.println(a+" "+i+" "+j);
}
Output
}
20 20 20
Wrapper class Example: Wrapper to
Primitive
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int
int j=a;//unboxing, now compiler will write a.intValue() internally
System.out.println(a+" "+i+" "+j);
Output
}
} 333
Generic Classes
Generic class can have one or more type parameters separated by commas. These classes are
known as parameterized classes or parameterized types because they accept one or more
parameters.
Infoseek
String in Java
Generally, string is a sequence of characters. But in java, string is an object that represents a
sequence of characters. The java.lang.String class is used 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.
The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.
How to create String object?
There are two ways to create String object:
1. By string literal Infoseek

2. By new keyword
String Literal
Java String literal is created by using double quotes. 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.

String s1="Welcome";
String s2="Welcome";//will not create new instance
By new keyword
In 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).

String s=new String("Welcome");

//creates two objects and one reference variable


Java String Example
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); Output

System.out.println(s3); java
} Strings
} example
Immutable String in Java
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.
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
} Output
Now it can be understood by the diagram given below. Here
} Sachin is not changed but a new object is created with Sachin
sachintendulkar. That is why string is known as immutable.
Another Example
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}

Output Sachin Tendulkar


Java String compare
We can compare string in java on the basis of content and reference.
It is used in authentication (by equals() method), sorting (by compareTo() method), reference
matching (by == operator) etc.
There are three ways to compare string in java:
1. By equals() method
2. By = = operator
3. By compareTo() method
String compare by equals() method
The String equals() method compares the original content of the string. It compares values of string for equality.
class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav"; Output
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true true
true
System.out.println(s1.equals(s4));//false
false
}
}
String compare by == operator
The = = operator compares references not values .
class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2); //true (because both refer to same instance)
System.out.println(s1==s3); //false(because s3 refers to instance created in nonpool)
}
} true
Output
false
String compare by compareTo() method
The String 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 variables. If:


 s1 == s2 :0
 s1 > s2 :positive value
 s1 < s2 :negative value
Example for string compare by ==
operator
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan"; 0
System.out.println(s1.compareTo(s2));//0 Output 1
System.out.println(s1.compareTo(s3));//1(because s1>s3) -1
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
String Concatenation in Java
In java, string concatenation forms a new string that is the
combination of multiple strings. There are two ways to concat string
in java:

By + (string concatenation) operator


 By concat() method
String Concatenation by + (string
concatenation) operator
String Concatenation by + (string concatenation) operator

class TestStringConcatenation1
{
public static void main(String args[])
{
String s="Sachin"+" Tendulkar";
Output
System.out.println(s);//Sachin Tendulkar
} Sachin Tendulkar
}
String Concatenation by concat() method
The String concat() method concatenates the specified string to the end of current string.

class TestStringConcatenation3
{
public static void main(String args[])
{
String s1="Sachin ";
String s2="Tendulkar";
String s3=s1.concat(s2);
System.out.println(s3);//Sachin Tendulkar Output
}
} Sachin Tendulkar
Java String class methods
The java.lang.String class provides a lot of methods to work on
string. By the help of these methods, we can perform operations on
string such as trimming, concatenating, converting, comparing,
replacing strings etc.
Java String is a powerful concept because everything is treated as a
string if you submit any form in window based, web based or mobile
application.
1. Java String toUpperCase() and
toLowerCase() method
The java string toUpperCase() method converts this string into uppercase letter and string
toLowerCase() method into lowercase letter.

String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)
Output

SACHIN
sachin
Sachin
2. Java String trim() method
The string trim() method eliminates white spaces before and after string.

String s=" Sachin ";


System.out.println(s);// Sachin
System.out.println(s.trim());//Sachin

Sachin
Output
Sachin
Java String startsWith() and endsWith()
method

String s="Sachin";
System.out.println(s.startsWith("Sa"));//true
System.out.println(s.endsWith("n"));//true

Output true true


3. Java String charAt() method
The string charAt() method returns a character at specified index.

String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h

Output S
h
4. Java String length() method
The string length() method returns length of the string.

String s="Sachin";
System.out.println(s.length());//6

Output 6
Java StringBuffer class
Java StringBuffer class is used to create mutable (modifiable) string.
The StringBuffer class in java is same as String class except it is
mutable i.e. it can be changed.

Java StringBuffer class is thread-safe i.e. multiple threads cannot


access it simultaneously. So it is safe and will result in an order
Important methods of StringBuffer class
public synchronized StringBuffer append(String s) is used to append the specified string with this string.
The append() method is overloaded like append(char),
append(boolean), append(int), append(float),
append(double) etc.

public synchronized StringBuffer 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.

public synchronized StringBuffer replace(int startIndex, int endIndex, is used to replace the string from specified startIndex
String str) and endIndex.

public synchronized StringBuffer delete(int startIndex, int endIndex) is used to delete the string from specified startIndex and
endIndex.

public synchronized StringBuffer reverse() is used to reverse the string.


1. StringBuffer append() method
The append() method concatenates the given argument with this string.

class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
2. StringBuffer insert() method
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
}
}
3. StringBuffer replace() method
The replace() method replaces the given string from the specified beginIndex and endIndex.

class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
4. StringBuffer delete() method
The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex.
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
5. StringBuffer reverse() method
The reverse() method of StringBuilder class reverses the current string.

class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Java StringBuilder class
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.
Java StringBuilder Examples
public StringBuilder append(String s) is used to append the specified string with this string. The
append() method is overloaded like append(char),
append(boolean), append(int), append(float),
append(double) etc.
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.

public StringBuilder replace(int startIndex, int endIndex, is used to replace the string from specified startIndex and
String str) endIndex.
public StringBuilder delete(int startIndex, int endIndex) is used to delete the string from specified startIndex and
endIndex.
public StringBuilder reverse() is used to reverse the string.
1. StringBuilder append() method
The StringBuilder append() method concatenates the given argument with this string.

class StringBuilderExample{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
2. StringBuilder insert() method
The StringBuilder insert() method inserts the given string with this string at the given position.

class StringBuilderExample2{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
3. StringBuilder replace() method
The StringBuilder replace() method replaces the given string from the specified beginIndex and
endIndex.

class StringBuilderExample3{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
4. StringBuilder delete() method
The delete() method of StringBuilder class deletes the string from the specified beginIndex to
endIndex.

class StringBuilderExample4{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
5. StringBuilder reverse() method
The reverse() method of StringBuilder class reverses the current string.

class StringBuilderExample5{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Difference between String and
StringBuffer
There are many differences between String and StringBuffer. A list of differences between String
and StringBuffer are given below:

N String StringBuffer
o.
1) String class is immutable. StringBuffer class is mutable.
2) String is slow and consumes more memory StringBuffer is fast and consumes less memory when you
when you concat too many strings because cancat strings.
every time it creates new instance.

3) String class overrides the equals() method StringBuffer class doesn't override the equals() method of
of Object class. So you can compare the Object class.
contents of two strings by equals()
method.
Difference between StringBuffer and
StringBuilder
There are many differences between StringBuffer and StringBuilder. A list of differences between
StringBuffer and StringBuilder are given below:

No. StringBuffer StringBuilder

1) 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 the
StringBuffer simultaneously. methods of StringBuilder simultaneously.

2) StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than


StringBuffer.
Java toString() method
If you want to represent any object as a string, toString() method comes into existence.
The toString() method returns the string representation of the object.
If you print any object, java compiler internally invokes the toString() method on the object. So
overriding the toString() method, returns the desired output, it can be the state of an object etc.
depends on your implementation.

Advantage of Java toString() method


By overriding the toString() method of the Object class, we can return values of the object, so
we don't need to write much
Example of Java toString() method
class Student{ public String toString()
{ //overriding the toString() method
int rollno; return rollno+" "+name+" "+city;
}
String name; public static void main(String args[]){
String city; Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");

System.out.println(s1);//compiler writes here s1.toString()


Student(int rollno, String name, String city){ System.out.println(s2);//compiler writes here s2.toString()
this.rollno=rollno; }
}
this.name=name;
101 Raj lucknow
this.city=city; Output
102 Vijay ghaziabad
}
Exception Handling in Java
The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.

What is exception :
Exception is an abnormal condition.
In java, exception is an event that disrupts the normal flow of the program. It is an object which
is thrown at runtime.

What is exception handling :


Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL,
Remote etc.
Types of Exception
There are mainly two types of exceptions: checked and unchecked
where error is considered as unchecked exception. The sun
microsystem says there are three types of exceptions:

1. Checked Exception
2. Unchecked Exception
3. Error
Difference between checked and
unchecked exceptions
1. Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known
as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are
checked at compile-time.
2. Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at
runtime.
3. Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Common scenarios where exceptions may
occur
There are given some scenarios where unchecked exceptions can occur. They are as follows:

1. Scenario where ArithmeticException occurs :


If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException

2. Scenario where NullPointerException occurs


If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.

String s=null;
System.out.println(s.length());//NullPointerException
Common scenarios where exceptions may
occur
3. Scenario where NumberFormatException occurs
The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string
variable that have characters, converting this variable into digit will occur NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException

4. Scenario where ArrayIndexOutOfBoundsException occurs


If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as
shown below:

int a[]=new int[5];


a[10]=50; //ArrayIndexOutOfBoundsException
Java Exception Handling Keywords
There are 5 keywords used in java exception handling.
1. try
2. catch
3. finally
4. throw
5. throws
Java try-catch
Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
Java try block must be followed by either catch or finally block.

Syntax of java try-catch Syntax of try-finally block


try{
try{
//code that may throw exception //code that may throw exception
}catch(Exception_class_Name ref){} }finally{}
Java catch block
Java catch block is used to handle the Exception. It must be used
after the try block only.
You can use multiple catch block with a single try

Infoseek
Problem without exception handling
Let's try to understand the problem if we don't use try-catch block.

As displayed in the above example, rest of


public class Testtrycatch1{
the code is not executed (in such case, rest of
public static void main(String args[]){ the code... statement is not printed).
There can be 100 lines of code after
int data=50/0;//may throw exception
exception. So all the code after exception will
System.out.println("rest of the code..."); not be executed.
}
}
Exception in thread main java.lang.ArithmeticException:/
Output
by zero
Solution by exception handling
Let's see the solution of above problem by java try-catch block.

public class Testtrycatch2{ Now, as displayed in the above example,


rest of the code is executed i.e. rest of the
public static void main(String args[]){ code... statement is printed.
try{
int data=50/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}
} Exception in thread main java.lang.ArithmeticException:/
Output
by zero rest of the code...
Internal working of java try-catch block
Internal working of java try-catch block
The JVM firstly checks whether the exception is handled or not. If exception is
not handled, JVM provides a default exception handler that performs the
following tasks:

1. Prints out exception description.


2. Prints the stack trace (Hierarchy of methods where the exception occurred).
3. Causes the program to terminate.
But if exception is handled by the application programmer, normal flow of the
application is maintained i.e. rest of the code is executed.
Java Multi catch block
If you have to perform different tasks at the occurrence of different Exceptions, use java multi
catch block.
public class TestMultipleCatchBlock catch(ArrayIndexOutOfBoundsException e)
{ {
public static void main(String args[]){ System.out.println("task 2 completed");}
try catch(Exception e)
{ {
int a[]=new int[5]; System.out.println("common task completed");
a[5]=30/0; }
} System.out.println("rest of the code...");
catch(ArithmeticException e) }
{ }
System.out.println("task1 is completed");
} Output task1 completed rest of the code...
Java Nested try block
The try block within a try block is known as nested try block in java.
Why use nested try block
Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.

Infoseek
Syntax:
....
try }
catch(Exception e)
{ {
statement 1; }
}
statement 2; catch(Exception e)
try {
}
{ ....
statement 1;
statement 2;
Java nested try example
class Excep6{ int a[]=new int[5];
a[5]=4;
public static void main(String args[]){ }
try{ catch(ArrayIndexOutOfBoundsException e)
{
try{ System.out.println(e);
System.out.println("going to divide"); }
System.out.println("other statement);
int b =39/0;
}
} catch(Exception e)
{
catch(ArithmeticException e)
System.out.println("handeled");
{ }
System.out.println("normal flow..");
System.out.println(e);}
}
try{ }
Java finally block
Java finally block is a block that is used to execute important code such as closing connection,
stream etc. Java finally block is always executed whether exception is handled or not. Java finally
block follows try or catch block.
Why use java finally
Finally block in java can be used to put "cleanup" code such as
closing a file, closing connection etc.

Usage of Java finally

Let's see the different cases where java finally block can be used.
Case 1
Let's see the java finally example where exception doesn't occur.

class TestFinallyBlock{
public static void main(String args[]){
try{ Output
int data=25/5;
System.out.println(data); 5
} finally block is always executed
catch(NullPointerException e){System.out.println(e);} rest of the code...
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Case 2
Let's see the java finally example where exception occurs and not handled.

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

try{ finally block is always executed


int data=25/0; Exception in thread main java.lang.ArithmeticException:/
System.out.println(data); by zero
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Case 3
Let's see the java finally example where exception occurs and handled.

public class TestFinallyBlock2{


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

try{
Exception in thread main java.lang.ArithmeticException:/
int data=25/0;
by zero
System.out.println(data); finally block is always executed
} rest of the code...
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Java throw keyword
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception. We will see custom exceptions later.

The syntax of java throw keyword is given below.


throw exception;
Let's see the example of throw IOException
throw new IOException("sorry device error);
java throw keyword example
If the age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote.
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
} Output
public static void main(String args[]){
validate(13); Exception in thread main
System.out.println("rest of the code...");
java.lang.ArithmeticException:not valid
}
}
Java throws keyword
The Java throws keyword is used to declare an exception. It gives an information to the programmer
that there may occur an exception so it is better for the programmer to provide the exception
handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked
exception such as NullPointerException, it is programmers fault that he is not performing check up
before the code being used.

Syntax of java throws

return_type method_name() throws exception_class_name{


//method code
}
Which exception should be declared
Answer : checked exception only, because:
unchecked Exception: under your control so correct your code.
error: beyond your control e.g. you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.

Advantage of Java throws keyword


Now Checked Exception can be propagated (forwarded in call stack).
It provides information to the caller of the method about the exception.
Java throws example
Let's see the example of java throws clause which describes that checked exceptions can be propagated by
throws keyword.
import java.io.IOException; try
{
class Testthrows1{ n();
void m()throws IOException{ }
catch(Exception e)
throw new IOException("device error"); {
//checked exception System.out.println("exception handled");
}
} }
void n()throws IOException{ public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
m(); obj.p();
} System.out.println("normal flow...");
Output
}
void p()
}
{ exception handled normal flow...
Cases
There are two cases:
Case1: You caught the exception i.e. handle the exception using
try/catch.
Case2: You declare the exception i.e. specifying throws with the
method.
Case1: You handle the exception
In case you handle the exception, the code will be executed fine whether exception occurs
during the program or not.
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{ Output
M m=new M();
m.method(); exception handled normal flow...
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow...");
}
}
Case2: You declare the exception
A . In case you declare the exception, if exception does not occur, the
code will be executed fine.
B . In case you declare the exception if exception occures, an
exception will be thrown at runtime because throws does not handle
the exception.
A. Program if exception does not occur
import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
}
}
class Testthrows3{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
Output

System.out.println("normal flow...");
device operation performed normal flow...
}
}
B . program if exception occurs
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
class Testthrows4{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
Output

System.out.println("normal flow...");
Runtime Exception
}
}
Difference between throw and throws in
Java
No. throw throws
1) Java throw keyword is used to explicitly throw an Java throws keyword is used to declare an
exception. exception.
2) Checked exception cannot be propagated using Checked exception can be propagated with
throw only. throws.
3) Throw is followed by an instance. Throws is followed by class.
4) Throw is used within the method. Throws is used with the method signature.

5) You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException
Difference between final, finally and
finalize
No. final finally finalize
1) Final is used to apply restrictions on Finally is used to place Finalize is used to
class, method and variable. Final class important code, it will be perform clean up
can't be inherited, final method can't be executed whether exception processing just before
overridden and final variable value can't is handled or not. object is garbage
be changed. collected.

2) Final is a keyword. Finally is a block. Finalize is a method.


Java final example
class FinalExample{
public static void main(String[] args){
final int x=100;
x=200;//Compile Time Error
}}
Java finally example
class FinallyExample{
public static void main(String[] args){
try{
int x=300;
}catch(Exception e){System.out.println(e);}
finally{System.out.println("finally block is executed");}
}}
Java finalize example
class FinalizeExample{
public void finalize(){System.out.println("finalize called");}
public static void main(String[] args){
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
System.gc();
}}
Java Custom Exception
If you are creating your own Exception that is known as custom exception or
user-defined exception. Java custom exceptions are used to customize the
exception according to user need.
By the help of custom exception, you can have your own exception and
message.
Let's see a simple example of java custom exception.
Example of java custom exception
class InvalidAgeException extends Exception{ class TestCustomException1
{
InvalidAgeException(String s){ static void validate(int age)throws InvalidAgeException
{
super(s); if(age<18)
throw new InvalidAgeException("not valid");
} else
System.out.println("welcome to vote");
} }
public static void main(String args[]){
try{
validate(13);
}
catch(Exception m)
{
System.out.println("Exception occured: "+m);}
System.out.println("rest of the code...");
}
}
Multithreading in Java
Multithreading in java is a process of executing multiple threads simultaneously.
Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
But we use multithreading than multiprocessing because threads share a common memory
area. They don't allocate separate memory area so saves memory, and context-switching
between the threads takes less time than process.
Java Multithreading is mostly used in games, animation etc.
Advantages of Java Multithreading
1. It doesn't block the user because threads are independent and
you can perform multiple operations at same time.
2. You can perform many operations together so it saves time.
3. Threads are independent so it doesn't affect other threads if
exception occur in a single thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use
multitasking to utilize the CPU. Multitasking can be achieved by two ways:

1. Process-based Multitasking(Multiprocessing)

2. Thread-based Multitasking(Multithreading)
Process-based Multitasking
(Multiprocessing)
1. Each process have its own address in memory i.e. each process
allocates separate memory area.
2. Process is heavyweight.
3. Cost of communication between the process is high.
4. Switching from one process to another require some time for
saving and loading registers, memory maps, updating lists etc.
Thread-based Multitasking
(Multithreading)

1. Threads share the same address space.


2. Thread is lightweight.
3. Cost of communication between the thread is
low.
What is Thread in java?
A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of
execution.
Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area.

As shown in the above figure,


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.
Life cycle of a Thread (Thread States)
A thread can be in one of the five states. According to sun, there is only 4 states
in thread life cycle in java new, runnable, non-runnable and terminated. There is no
running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
Life Cycle of a thread
Components
1. New : The thread is in new state if you create an instance of Thread class but
before the invocation of start() method.
2. Runnable : The thread is in runnable state after invocation of start()
method, but the thread scheduler has not selected it to be the running thread.
3. Running : The thread is in running state if the thread scheduler has
selected it.
4. Non-Runnable (Blocked) : This is the state when the thread is still alive,
but is currently not eligible to run.
5. Terminated : A thread is in terminated or dead state when its run() method
exits.
How to create thread
There are two ways to create a thread: Infoseek

Infoseek
1. By extending Thread class

2. By implementing Runnable interface.


Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

1. Thread()
2. Thread(String name)
3. Thread(Runnable r)
4. Thread(Runnable r,String name)
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.
Commonly used methods of Thread class:
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.
Runnable interface:
The Runnable interface should be implemented by any class whose instances
are intended to be executed by a thread. Runnable interface have only one
method named run().
public void run(): is used to perform action for a thread.

Starting a thread:

start()method of Thread class is used to start a newly created thread. It performs following
tasks:

•A new thread starts(with new callstack).


•The thread moves from New state to the Runnable state.
•When the thread gets a chance to execute, its target run() method will run.
Java Thread Example by extending Thread
class
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start(); Output

}
thread is running...
}
Java Thread Example by implementing
Runnable interface
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
Output
t1.start();
}
thread is running...
}
Thread Scheduler in Java
Thread scheduler in java is the part of the JVM that decides which thread should
run.
There is no guarantee that which runnable thread will be chosen to run by the
thread scheduler.
Only one thread at a time can run in a single process.
The thread scheduler mainly uses preemptive or time slicing scheduling to
schedule the threads.
Sleep method in java
The sleep() method of Thread class is used to sleep a thread for the specified
amount of time.
Syntax of sleep() method in java
The Thread class provides two methods for sleeping a thread:
1. public static void sleep(long miliseconds)throws InterruptedException
2. public static void sleep(long miliseconds, int nanos)throws
InterruptedException
Example of sleep method in java
class TestSleepMethod1 extends Thread{ public static void main(String args[])
{
public void run(){
TestSleepMethod1 t1=new TestSleepMethod1();
for(int i=1;i<5;i++){ TestSleepMethod1 t2=new TestSleepMethod1();
try{ t1.start();
thread.sleep(500); t2.start();
}
} } 1
catch(InterruptedException e) 1
{ 2
2
System.out.println(e); Output
3
} 3
System.out.println(i); 4
} 4
}
Can we start a thread twice
public class TestThreadTwice1 extends Thread{
No. After starting a thread, it can never
public void run(){
be started again. If you does so, an
System.out.println("running..."); IllegalThreadStateException
} is thrown. In such case, thread will run
once but for second time, it will throw
public static void main(String args[]){
exception
TestThreadTwice1 t1=new TestThreadTwice1();
t1.start();
t1.start();
Output
}
} running
Exception in thread "main" java.lang.IllegalThreadStateException
What if we call run() method directly
instead start() method?
 Each thread starts in a separate call stack.
 Invoking the run() method from main thread, the run() method goes onto the current call stack
rather than at the beginning of a new call stack.
class TestCallRun1 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestCallRun1 t1=new TestCallRun1();
t1.run();//fine, but does not start a separate call stack Output
}
} running...
The join() method
The join() method waits for a thread to die. In other words, it causes
the currently running threads to stop executing until the thread it
joins with completes its task.
Syntax :

public void join()throws InterruptedException


public void join(long milliseconds)throws InterruptedException
Example of join() method
package amir; public void run()
{
class thread1 extends Thread for(int i=0;i<=5;i++)
{ {
System.out.println("hi"); hello
public void run() try {Thread.sleep(1000);}catch(Exception e){}
} hi
{
} hello
for(int i=0;i<=5;i++) } hi
public class Join {
{
public static void main(String[] args) throws Exception {
hello
System.out.println("hello"); thread1 obj=new thread1(); hi
try {Thread.sleep(1000);}catch(Exception e){}
thread2 obj1=new thread2(); hello
obj.start(); hi
} try {Thread.sleep(10);}catch(Exception e){}
obj1.start(); Output hello
} obj.join(); hi
} obj1.join(); hello
System.out.println("bye");
class thread2 extends Thread }
hi
{ } bye
The currentThread() method:
class TestJoinMethod4 extends Thread{
public void run(){
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String args[]){
TestJoinMethod4 t1=new TestJoinMethod4();
TestJoinMethod4 t2=new TestJoinMethod4();
t1.start(); Output
t2.start();
Thread-0
}
Thread-1
}
Naming Thread
The Thread class provides methods to change and get the name of a
thread. By default, each thread has a name i.e. thread-0, thread-1
and so on. By we can change the name of the thread by using
setName() method. The syntax of setName() and getName()
methods are given below:
1. public String getName(): is used to return the name of a thread.
2. public void setName(String name): is used to change the name of
a thread.
Example of naming a thread
class TestMultiNaming1 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestMultiNaming1 t1=new TestMultiNaming1();
TestMultiNaming1 t2=new TestMultiNaming1();
Output
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName()); Name of t1:Thread-0
t1.start(); Name of t2:Thread-1
t2.start(); id of t1:8 running...
After changeling name of t1:Sonoo Jaiswal
t1.setName("Sonoo Jaiswal");
System.out.println("After changing name of t1:"+t1.getName()); running...
} }
Current Thread
The currentThread() method returns a reference of currently executing thread.

class TestMultiNaming2 extends Thread{


public void run(){
System.out.println(Thread.currentThread().getName());
}
public static void main(String args[]){
TestMultiNaming2 t1=new TestMultiNaming2();
TestMultiNaming2 t2=new TestMultiNaming2();
t1.start();
t2.start(); Thread-0
} Output
Thread-1
}
Priority of a Thread (Thread Priority):
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread schedular schedules the threads according to their priority (known as preemptive
scheduling). But it is not guaranteed because it depends on JVM specification that which
scheduling it chooses.
3 constants defined in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value
of MAX_PRIORITY is 10.
Example of priority of a Thread:
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
Output
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
running thread name is:Thread-0
m1.start(); running thread priority is:10
m2.start(); running thread name is:Thread-1
} running thread priority is:1
}
Synchronization in Java
Synchronization in java is the capability to control the access of multiple threads to any
shared resource.
Java Synchronization is better option where we want to allow only one thread to access
the shared resource.

Why use Synchronization :


The synchronization is mainly used to
To prevent thread interference.
To prevent consistency problem.
Thread Synchronization
There are two types of thread synchronization mutual exclusive and
inter-thread communication.
1. Mutual Exclusive
◦ Synchronized method.
◦ Synchronized block.
◦ static synchronization.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one
another while sharing data. This can be done by three ways in java:
1. by synchronized method

2. by synchronized block

3. by static synchronization
Concept of Lock in Java
Synchronization is built around an internal entity known as the lock
or monitor. Every object has an lock associated with it. By
convention, a thread that needs consistent access to an object's
fields has to acquire the object's lock before accessing them, and
then release the lock when it's done with them.
From Java 5 the package java.util.concurrent.locks contains several
lock implementations.
Java synchronized method
//example of java synchronized method } class MyThread2 extends Thread{
class Table{ Table t;
synchronized void printTable(int n){ MyThread2(Table t){
//synchronized method this.t=t;
for(int i=1;i<=5;i++){ }
5
System.out.println(n*i); public void run(){ Output
try{ t.printTable(100); 10
Thread.sleep(400); } 15
}catch(Exception e){System.out.println(e);} } 20
} } } public class TestSynchronization2{ 25
class MyThread1 extends Thread{ public static void main(String args[]){ 100
Table t; Table obj = new Table();//only one object 200
MyThread1(Table t){ MyThread1 t1=new MyThread1(obj); 300
this.t=t; MyThread2 t2=new MyThread2(obj);
400
} t1.start();
public void run(){ t2.start(); 500
t.printTable(5); }
} }
Example of synchronized method by using
annonymous class
class Table final Table obj = new Table();//only one object
{
synchronized void printTable(int n) Thread t1=new Thread(){
{ public void run(){
//synchronized method obj.printTable(5);
for(int i=1;i<=5;i++) 5
}
{ 10
};
System.out.println(n*i); 15
Thread t2=new Thread(){
try{ 20
public void run(){
Thread.sleep(400); 25
obj.printTable(100);
}catch(Exception e){System.out.println(e);} 100
}
} 200
};
} 300
t1.start();
} Output 400
t2.start();
public class TestSynchronization3{ } 500
public static void main(String args[]){ }
Synchronized block in java
Synchronized block can be used to perform synchronization on any specific resource of the
method.
Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you
can use synchronized block.
If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method
Points to remember for Synchronized block
1. Synchronized block is used to lock an object for any shared resource.
2. Scope of synchronized block is smaller than the method.
Example of synchronized block
class Table{
}
void printTable(int n){
class MyThread2 extends Thread{
synchronized(this){//synchronized block
Table t;
for(int i=1;i<=5;i++){
MyThread2(Table t){
System.out.println(n*i);
this.t=t;
try{
}
Thread.sleep(400);
public void run(){
}catch(Exception e){System.out.println(e);} 5
t.printTable(100);
} 10
}
}
}//end of the method
} 15
public class TestSynchronizedBlock1{ 20
}
public static void main(String args[]){
class MyThread1 extends Thread{ 25
Table obj = new Table();//only one object
Table t;
MyThread1 t1=new MyThread1(obj); 100
MyThread1(Table t){
MyThread2 t2=new MyThread2(obj); 200
this.t=t;
t1.start();
} 300
t2.start();
public void run(){ 400
}
t.printTable(5);
} Output
} 500
Same Example of synchronized block by
using annonymous class:
class Table{ Thread t1=new Thread(){
void printTable(int n){ public void run(){
synchronized(this){//synchronized block obj.printTable(5);
for(int i=1;i<=5;i++){ }
System.out.println(n*i); };
try{ Thread t2=new Thread(){
5
Thread.sleep(400); public void run(){
10
}catch(Exception e){System.out.println(e);} obj.printTable(100);
15
} }
20
} };
25
}//end of the method
100
} t1.start();
200
public class TestSynchronizedBlock2{ t2.start();
300
public static void main(String args[]){ }
Output 400
final Table obj = new Table();//only one object }
500
Static synchronization
If you make any static method as synchronized, the lock will be on the class not on object.
Example of static synchronization
class Table{ class MyThread2 extends Thread{ public class TestSynchronization4{
synchronized static void printTable(int n){ public void run(){ public static void main(String t[]){
for(int i=1;i<=10;i++){ Table.printTable(10); MyThread1 t1=new MyThread1();
System.out.println(n*i); } MyThread2 t2=new MyThread2();
} MyThread3 t3=new MyThread3();
try{
class MyThread3 extends Thread{ MyThread4 t4=new MyThread4();
Thread.sleep(400); public void run(){ t1.start();
}catch(Exception e){} Table.printTable(100); t2.start();
} } t3.start();
} } t4.start();
} class MyThread4 extends Thread{ }
class MyThread1 extends Thread{ public void run(){ }
public void run(){ Table.printTable(1000);
}
Table.printTable(1);
}
}
}
Output :
1 60 1000
2 70 2000
3 80 3000
4 90 4000
5 100 5000
6 100 6000
7 200 7000
8 300 8000
9 400 9000
10 500 10000
10 600
20 700
30 800
40 900
50 1000
Same example of static synchronization by
annonymous class
class Table{ Thread t2=new Thread(){
synchronized static void printTable(int n){ public void run(){
for(int i=1;i<=10;i++){ Table.printTable(10);
System.out.println(n*i); } };
try{ Thread t3=new Thread(){
Thread.sleep(400); public void run(){
}catch(Exception e){} Table.printTable(100);
} } };
} Thread t4=new Thread(){
} public void run(){
public class TestSynchronization5 { Table.printTable(1000);
public static void main(String[] args) { } };
Thread t1=new Thread(){ t1.start();
public void run(){ t2.start();
Table.printTable(1); t3.start();
} }; t4.start();
} }
Output:
1 60 1000
2 70 2000
3 80 3000
4 90 4000
5 100 5000
6 100 6000
7 200 7000
8 300 8000
9 400 9000
10 500 10000
10 600
20 700
30 800
40 900
50 1000
Deadlock in java
Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is
waiting for an object lock, that is acquired by another thread and second thread is waiting for an
object lock that is acquired by first thread. Since, both threads are waiting for each other to
release the lock, the condition is called deadlock.
Example of Deadlock in java
public class TestDeadlockExample1 { // t2 tries to lock resource2 then resource1
public static void main(String[] args) { Thread t2 = new Thread() {
final String resource1 = "ratan jaiswal"; public void run() {
final String resource2 = "vimal jaiswal"; synchronized (resource2) {
// t1 tries to lock resource1 then resource2 System.out.println("Thread 2: locked resource 2");
Thread t1 = new Thread() { try { Thread.sleep(100);}
public void run() { catch (Exception e) {}
synchronized (resource1) { synchronized (resource1) {
System.out.println("Thread 1: locked resource 1"); System.out.println("Thread 2: locked resource 1");
try { Thread.sleep(100);} } } } };
catch (Exception e) {} t1.start();
synchronized (resource2) { t2.start();
System.out.println("Thread 1: locked resource 2"); }}
} } } };
Output Thread 1: locked resource 1 Thread 2: locked resource 2
Java I/O
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
We can perform file handling in java by Java I/O API.
Stream
A stream is a sequence of data.In Java a stream is composed of bytes. It's called
a stream because it is like a stream of water that continues to flow.

In java, 3 streams are created for us automatically. All these streams are
attached with console.

1. System.out: standard output stream


2. System.in: standard input stream
3. System.err: standard error stream
OutputStream InputStream
OutputStream :
Java application uses an output stream to write data to a destination, it may be a
file, an array, peripheral device or socket.
InputStream :
Java application uses an input stream to read data from a source, it may be a file,
an array, peripheral device or socket.
Figure of I/O Streams
OutputStream class
OutputStream class is an abstract class. It is the super class of all classes representing an output
stream of bytes. An output stream accepts output bytes and sends them to some sink.
Useful methods of OutputStream

Method Description
1) public void write(int)throws IOException is used to write a byte to the current output stream.
2) public void write(byte[])throws IOException is used to write an array of byte to the current
output stream.
3) public void flush()throws IOException flushes the current output stream.
4) public void close()throws IOException is used to close the current output stream.
Java FileOutputStream Class
Java FileOutputStream is an output stream used for writing data to a file.
If you have to write primitive values into a file, use FileOutputStream class. You can write byte-
oriented as well as character-oriented data through FileOutputStream class. But, for character-
oriented data, it is preferred to use FileWriter than FileOutputStream.

INFOSEEK
FileOutputStream class declaration
Let's see the declaration for Java.io.FileOutputStream class:
public class FileOutputStream extends OutputStream
FileOutputStream class methods
Method Description
protected void finalize() It is used to clean up the connection with the file output
stream.
void write(byte[] ary) It is used to write ary.length bytes from the byte array to
the file output stream.
void write(byte[] ary, int off, int len) It is used to write len bytes from the byte array starting at
offset off to the file output stream.

void write(int b) It is used to write the specified byte to the file output
stream.
FileChannel getChannel() It is used to return the file channel object associated with
the file output stream.
FileDescriptor getFD() It is used to return the file descriptor associated with the
stream.
void close() It is used to closes the file output stream.
Java FileOutputStream example: write
string
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to Infoseek";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b); Output Success...
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);} testout.txt Welcome to Infoseek
} }
Java FileInputStream Class
Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented
data (streams of raw bytes) such as image data, audio, video etc. You can also read character-
stream data. But, for reading streams of characters, it is recommended to use FileReader class.
Java FileInputStream class declaration :
public class FileInputStream extends InputStream
Java FileInputStream class methods
Method Description
int available() It is used to return the estimated number of bytes that can be read from the input
stream.
int read() It is used to read the byte of data from the input stream.

int read(byte[] b) It is used to read up to b.length bytes of data from the input stream.

int read(byte[] b, int off, int len) It is used to read up to len bytes of data from the input stream.

long skip(long x) It is used to skip over and discards x bytes of data from the input stream.

FileChannel getChannel() It is used to return the unique FileChannel object associated with the file input stream.

FileDescriptor getFD() It is used to return the FileDescriptor object.

protected void finalize() It is used to ensure that the close method is call when there is no more reference to
the file input stream.
void close() It is used to closes the stream.
Java FileInputStream example : read all
characters
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i); Output Welcome to Infoseek
}
fin.close();
}catch(Exception e){System.out.println(e);}
} }
Java BufferedOutputStream Class
Java BufferedOutputStream class is used for buffering an output stream. It internally uses buffer
to store data. It adds more efficiency than to write data directly into a stream. So, it makes the
performance fast.
For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see the
syntax for adding the buffer in an OutputStream:
OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\IO Package\\testo
ut.txt"));

Java BufferedOutputStream class declaration :


public class BufferedOutputStream extends FilterOutputStream
Java BufferedOutputStream class
constructors
Constructor Description
BufferedOutputStream(OutputStream It creates the new buffered output
os) stream which is used for writing the
data to the specified output stream.
BufferedOutputStream(OutputStream It creates the new buffered output
os, int size) stream which is used for writing the
data to the specified output stream
with a specified buffer size.
Java BufferedOutputStream class
methods
Method Description
void write(int b) It writes the specified byte to the
buffered output stream.
void write(byte[] b, int off, int len) It write the bytes from the specified
byte-input stream into a specified
byte array, starting with the given
offset
void flush() It flushes the buffered output stream.
Example of BufferedOutputStream class:
import java.io.*;
public class BufferedOutputStreamExample{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to infoseek.";
byte b[]=s.getBytes();
bout.write(b);
bout.flush(); Output Success...
bout.close();
fout.close();
System.out.println("success"); testout.txt Welcome to Infoseek
} }
Java BufferedInputStream Class
Java BufferedInputStream class is used to read information from stream. It internally uses buffer
mechanism to make the performance fast.
The important points about BufferedInputStream are:
When the bytes from the stream are skipped or read, the internal buffer automatically refilled
from the contained input stream, many bytes at a time.
When a BufferedInputStream is created, an internal buffer array is created.

Java BufferedInputStream class declaration :


public class BufferedInputStream extends FilterInputStream
Java BufferedInputStream class
constructors
Constructor Description
BufferedInputStream(InputStream IS) It creates the BufferedInputStream and
saves it argument, the input stream IS,
for later use.
BufferedInputStream(InputStream IS, It creates the BufferedInputStream
int size) with a specified buffer size and saves it
argument, the input stream IS, for later
use.
Java BufferedInputStream class methods
Method Description
int available() It returns an estimate number of bytes that can be read from the input
stream without blocking by the next invocation method for the input stream.

int read() It read the next byte of data from the input stream.
int read(byte[] b, int off, int It read the bytes from the specified byte-input stream into a specified byte
ln) array, starting with the given offset.
void close() It closes the input stream and releases any of the system resources
associated with the stream.
void reset() It repositions the stream at a position the mark method was last called on
this input stream.
void mark(int readlimit) It sees the general contract of the mark method for the input stream.
long skip(long x) It skips over and discards x bytes of data from the input stream.
boolean markSupported() It tests for the input stream to support the mark and reset methods.
Example of Java BufferedInputStream
import java.io.*;
Here, we are assuming that you
public class BufferedInputStreamExample{ have following data
public static void main(String args[]){ in "testout.txt" file:
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
Output infoseek
}
bin.close();
fin.close();
testout.txt infoseek
}catch(Exception e){System.out.println(e);}
} }
Java SequenceInputStream Class
Java SequenceInputStream class is used to read data from
multiple streams. It reads data sequentially (one by one).

Java SequenceInputStream Class declaration :

public class SequenceInputStream extends InputStream


Constructors of SequenceInputStream
class

Constructor Description
SequenceInputStream(InputStream s1, creates a new input stream by reading the data
InputStream s2) of two input stream in order, first s1 and then
s2.

SequenceInputStream(Enumeration e) creates a new input stream by reading the data


of an enumeration whose type is InputStream.
Methods of SequenceInputStream class
Method Description
int read() It is used to read the next byte of data from
the input stream.
int read(byte[] ary, int off, int It is used to read len bytes of data from the
len) input stream into the array of bytes.
int available() It is used to return the maximum number of
byte that can be read from an input stream.

void close() It is used to close the input stream.


Java SequenceInputStream Example
import java.io.*;
class InputStreamExample {
testout.txt:
public static void main(String args[])throws Exception{
FileInputStream input1=new FileInputStream("D:\\testin.txt");
It is the example of Java SequenceInputStream class.
FileInputStream input2=new FileInputStream("D:\\testout.txt");
SequenceInputStream inst=new SequenceInputStream(input1, input2);
int j;
while((j=inst.read())!=-1){ Output
System.out.print((char)j);
testin.txt:
}
inst.close();
Welcome to Java IO Programming.
Welcome to Java IO Programming. It is the example of Java SequenceInputStream class.
input1.close();
input2.close();
} }
Example that reads the data from two
files and writes into another file
import java.io.*; fout.write(i);
class Input1{ }
sis.close();
public static void main(String args[])throws Exception{
fout.close();
FileInputStream fin1=new FileInputStream("D:\\testin1.txt"); fin1.close();
FileInputStream fin2=new FileInputStream("D:\\testin2.txt");
fin2.close();
System.out.println("Success..");
FileOutputStream fout=new FileOutputStream("D:\\testout.txt"); }
SequenceInputStream sis=new SequenceInputStream(fin1,fin2); }
int i;
while((i=sis.read())!=-1)
Output Success...
{
Collections In Java
INFOSEEK
Collections in Java
Collections in java is a framework that provides an architecture to
store and manipulate the group of objects.
All the operations that you perform on a data such as searching,
sorting, insertion, manipulation, deletion etc. can be performed by
Java Collections.
Java Collection simply 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).
What is Collection in java?
Collection represents a single unit of objects i.e. a group.
What is framework in java :
1. provides readymade architecture.
2. represents set of classes and interface.
3. is optional.
What is Collection framework :
Collection framework represents a unified architecture for storing and manipulating group of
objects. It has:
1. Interfaces and its implementations i.e. classes
2. Algorithm
Hierarchy of Collection Framework
Methods of Collection interface
No. Method Description
1 public boolean add(Object element) is used to insert an element in this collection.

2 public boolean addAll(Collection c) is used to insert the specified collection elements in the invoking collection.

3 public boolean remove(Object element) is used to delete an element from this collection.

4 public boolean removeAll(Collection c) is used to delete all the elements of specified collection from the invoking collection.

5 public boolean retainAll(Collection c) is used to delete all the elements of invoking collection except the specified collection.

6 public int size() return the total number of elements in the collection.

7 public void clear() removes the total no of element from the collection.

8 public boolean contains(Object element) is used to search an element.

9 public boolean containsAll(Collection c) is used to search the specified collection in this collection.

10 public Iterator iterator() returns an iterator.


11 public Object[] toArray() converts collection into array.
12 public boolean isEmpty() checks if collection is empty.
13 public boolean equals(Object element) matches two collection.
14 public int hashCode() returns the hashcode number for collection.
Iterator interface
Iterator interface provides the facility of iterating the elements in forward direction only.

Methods of Iterator interface :

No. Method Description


1 public boolean hasNext() It returns true if iterator has more elements.
2 public Object next() It returns the element and moves the cursor pointer
to the next element.
3 public void remove() It removes the last elements returned by the iterator.
It is rarely used.
Java ArrayList class
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class
and implements List interface.
The important points about Java ArrayList class are:
Java ArrayList class can contain duplicate elements.
Java ArrayList class maintains insertion order.
Java ArrayList class is non synchronized.
Java ArrayList allows random access because array works at the index basis.
In Java ArrayList class, manipulation is slow because a lot of shifting needs to
be occurred if any element is removed from the array list.
Hierarchy of ArrayList class
As shown in above diagram, Java ArrayList class extends AbstractList class which
implements List interface. The List interface extends Collection and Iterable
interfaces in hierarchical order.
ArrayList class declaration
Let's see the declaration for java.util.ArrayList class.
public class ArrayList<E> extends AbstractList<E> implements List<E>, Random
Access, Cloneable, Serializable
Constructors of Java ArrayList
Constructor Description
ArrayList() It is used to build an empty array list.
ArrayList(Collection c) It is used to build an array list that is initialized with the elements of the
collection c.
ArrayList(int capacity) It is used to build an array list that has the specified initial capacity.
Methods of Java ArrayList
Method Description
void add(int index, Object element) It is used to insert the specified element at the specified position index in a list.

boolean addAll(Collection c) It is used to append all of the elements in the specified collection to the end of this list, in the order
that they are returned by the specified collection's iterator.

void clear() It is used to remove all of the elements from this list.
int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list
does not contain this element.
Object[] toArraya() It is used to return an array containing all of the elements in this list in the correct order.

Object[] toArray(Object[] a) It is used to return an array containing all of the elements in this list in the correct order.

boolean add(Object o) It is used to append the specified element to the end of a list.
boolean addAll(int index, It is used to insert all of the elements in the specified collection into this list, starting at the specified
Collection c) position.
Object clone() It is used to return a shallow copy of an ArrayList.
int indexOf(Object o) It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List
does not contain this element.
void trimToSize() It is used to trim the capacity of this ArrayList instance to be the list's current size.
Java Non-generic Vs Generic Collection
Java collection framework was non-generic before JDK 1.5. Since 1.5, it is
generic.
Java new generic collection allows you to have only one type of object in
collection. Now it is type safe so typecasting is not required at run time.
Let's see the old non-generic example of creating java collection.
ArrayList al=new ArrayList();//creating old non-generic arraylist
Let's see the new generic example of creating java collection.
ArrayList<String> al=new ArrayList<String>();//creating new generic arraylist
In generic collection, we specify the type in angular braces. Now ArrayList is
forced to have only specified type of objects in it. If you try to add another type
of object, it gives compile time error.
Java ArrayList Example
import java.util.*;
class TestCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay"); Output
//Traversing list through Iterator
Ravi
Iterator itr=list.iterator(); Vijay
while(itr.hasNext()){ Ravi
System.out.println(itr.next()); Ajay
} } }
Two ways to iterate the elements of
collection in java
There are two ways to traverse collection elements:
1. By Iterator interface.
2. By for-each loop.
Iterating Collection through for-each loop
import java.util.*;
class TestCollection2{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi"); Output
al.add("Ajay");
Ravi
for(String obj:al)
Vijay
System.out.println(obj); Ravi
} Ajay
}
User-defined class objects in Java
ArrayList
Let's see an example where we are storing Student class object in array list.
class Student{
int rollno;
String name;
int age; User-defined
Student(int rollno,String name,int age){ class objects
in Java ArrayList
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
User-defined class objects in Java
ArrayList
import java.util.*; //Getting Iterator
public class TestCollection3{ Iterator itr=al.iterator();
public static void main(String args[]){ //traversing elements of ArrayList object
//Creating user-defined class objects while(itr.hasNext()){
Student s1=new Student(101,"Sonoo",23); Student st=(Student)itr.next();
Student s2=new Student(102,"Ravi",21); System.out.println(st.rollno+" "+st.name+" "+st.age);
Student s2=new Student(103,"Hanumat",25); }
//creating arraylist }
ArrayList<Student> al=new ArrayList<Student>(); }
al.add(s1);//adding Student class object 101 Sonoo 23
al.add(s2);
Output
al.add(s3); 102 Ravi 21
103 Hanumat 25
Example of addAll(Collection c) method
import java.util.*;
class TestCollection4{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi"); Output
al.add("Vijay");
al.add("Ajay"); Ravi
ArrayList<String> al2=new ArrayList<String>(); Vijay
al2.add("Sonoo"); Ajay
al2.add("Hanumat"); Sonoo
al.addAll(al2);//adding second list in first list Hanumat
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Example of removeAll() method
import java.util.*;
class TestCollection5{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi"); Output
al.add("Vijay");
al.add("Ajay"); iterating the elements after removing the elements of al2...
ArrayList<String> al2=new ArrayList<String>(); Vijay
al2.add("Ravi"); Ajay
al2.add("Hanumat");
al.removeAll(al2);
System.out.println("iterating the elements after removing the e
lements of al2...");
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Example of retainAll() method
import java.util.*;
class TestCollection6{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi"); Output
al.add("Vijay");
al.add("Ajay"); iterating the elements after removing the elements of al2...
ArrayList<String> al2=new ArrayList<String>(); Ravi
al2.add("Ravi");
al2.add("Hanumat");
al.retainAll(al2);
System.out.println("iterating the elements after retaining the el
ements of al2...");
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Java ArrayList Example: Book
import java.util.*; public class ArrayListExample {
class Book { public static void main(String[] args) {
int id; //Creating list of Books
String name,author,publisher; List<Book> list=new ArrayList<Book>();
//Creating Books
int quantity;
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
public Book(int id, String name, String author, Book b2=new Book(102,"Data Communications & Networking","Forouz
String publisher, int quantity) { an","Mc Graw Hill",4);
this.id = id; Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
this.name = name; //Adding Books to list
this.author = author; list.add(b1);
this.publisher = publisher; list.add(b2);
this.quantity = quantity; } } list.add(b3);
//Traversing list
Output for(Book b:list){
101 Let us C Yashwant Kanetkar BPB 8 System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b
102 Data Communications & Networking Forouzan Mc Graw Hill 4 .quantity);
103 Operating System Galvin Wiley 6 } } }
Java LinkedList 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.
The important points about Java LinkedList are:
1. Java LinkedList class can contain duplicate elements.
2. Java LinkedList class maintains insertion order.
3. Java LinkedList class is non synchronized.
4. In Java LinkedList class, manipulation is fast because no shifting needs to be occurred.
5. Java LinkedList class can be used as list, stack or queue.
Java LinkedList class
Hierarchy of LinkedList class
As shown in above diagram, Java LinkedList class extends AbstractSequentialList class and
implements List and Deque interfaces.
Doubly Linked List :
In case of doubly linked list, we can add or remove elements from both side.
LinkedList class declaration
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cl
oneable, Serializable

Constructors of Java LinkedList :

Constructor Description
LinkedList() It is used to construct an empty list.
LinkedList(Collection c) It is used to construct a list containing the
elements of the specified collection, in the
order they are returned by the collection's
iterator.
Methods of Java LinkedList
Method Description
void add(int index, Object element) It is used to insert the specified element at the specified position index in a list.

void addFirst(Object o) It is used to insert the given element at the beginning of a list.
void addLast(Object o) It is used to append the given element to the end of a list.
int size() It is used to return the number of elements in a list
boolean add(Object o) It is used to append the specified element to the end of a list.
boolean contains(Object o) It is used to return true if the list contains a specified element.
boolean remove(Object o) It is used to remove the first occurence of the specified element in a list.

Object getFirst() It is used to return the first element in a list.


Object getLast() It is used to return the last element in a list.
int indexOf(Object o) It is used to return the index in a list of the first occurrence of the specified element, or -1 if
the list does not contain any element.
int lastIndexOf(Object o) It is used to return the index in a list of the last occurrence of the specified element, or -1 if
the list does not contain any element.
Java LinkedList Example
import java.util.*;
public class TestCollection7{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi"); Output
al.add("Vijay");
Ravi
al.add("Ravi");
Vijay
al.add("Ajay"); Ravi
Iterator<String> itr=al.iterator(); Ajay
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Difference between ArrayList and
LinkedList
ArrayList LinkedList
1) ArrayList internally uses dynamic array to LinkedList internally uses doubly linked list to
store the elements. store the elements.
2) Manipulation with ArrayList is slow because Manipulation with LinkedList is faster than
it internally uses array. If any element is ArrayList because it uses doubly linked list so
removed from the array, all the bits are shifted no bit shifting is required in memory.
in memory.

3) ArrayList class can act as a list only because LinkedList class can act as a list and
it implements List only. queue both because it implements List and
Deque interfaces.
4) ArrayList is better for storing and LinkedList is better for manipulating data.
accessing data.
Example of ArrayList and LinkedList in Java
import java.util.*; List<String> al2=new LinkedList<String>();//creating link
class TestArrayLinked{ edlist
al2.add("James");//adding object in linkedlist
public static void main(String args[]){ al2.add("Serena");
List<String> al=new ArrayList<String>(); al2.add("Swati");
al2.add("Junaid");
//creating arraylist
al.add("Ravi");//adding object in arraylist System.out.println("arraylist: "+al);
System.out.println("linkedlist: "+al2);
}
al.add("Vijay"); }
al.add("Ravi");
arraylist: [Ravi,Vijay,Ravi,Ajay]
al.add("Ajay"); Output
linkedlist: [James,Serena,Swati,Junaid]
Java HashSet class

Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the
AbstractSet class and implements Set interface.
The important points about Java HashSet class are:
HashSet stores the elements by using a mechanism called hashing.
HashSet contains unique elements only.
Methods of Java HashSet class:

Method Description
void clear() It is used to remove all of the elements from this set.
boolean contains(Object o) It is used to return true if this set contains the specified element.
boolean add(Object o) It is used to adds the specified element to this set if it is not already
present.
boolean isEmpty() It is used to return true if this set contains no elements.
boolean remove(Object o) It is used to remove the specified element from this set if it is
present.
Object clone() It is used to return a shallow copy of this HashSet instance: the
elements themselves are not cloned.
Iterator iterator() It is used to return an iterator over the elements in this set.
int size() It is used to return the number of elements in this set.
Java HashSet Example
import java.util.*; //Traversing elements
Iterator<String> itr=set.iterator();
class TestCollection9{ while(itr.hasNext()){
public static void main(String args[]){ System.out.println(itr.next());
}
//Creating HashSet and adding elements }
}
HashSet<String> set=new HashSet<String>();

set.add("Ravi");

set.add("Vijay"); Output
set.add("Ravi");

set.add("Ajay"); Ajay Vijay Ravi


Java HashSet Example: Book
import java.util.*; public class HashSetExample {
public static void main(String[] args) {
class Book { HashSet<Book> set=new HashSet<Book>();
//Creating Books
int id; Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc
String name,author,publisher; Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
int quantity;
//Adding Books to HashSet
public Book(int id, String name, String author, String publisher, set.add(b1);
int quantity) { set.add(b2);
set.add(b3);
this.id = id; //Traversing HashSet
for(Book b:set){
this.name = name; System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantit
y);
this.author = author; }
} 101 Let us C Yashwant Kanetkar BPB 8
this.publisher = publisher; } Output 102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6
this.quantity = quantity;

}
Java TreeSet class

Java TreeSet class implements the Set interface that uses a tree for storage. It inherits
AbstractSet class and implements NavigableSet interface. The objects of TreeSet class are stored
in ascending order.
The important points about Java TreeSet class are:
Contains unique elements only like HashSet.
Access and retrieval times are quiet fast.
Maintains ascending order.
Methods of Java TreeSet class
Method Description

boolean addAll(Collection c) It is used to add all of the elements in the specified collection to this
set.

boolean contains(Object o) It is used to return true if this set contains the specified element.

boolean isEmpty() It is used to return true if this set contains no elements.

boolean remove(Object o) It is used to remove the specified element from this set if it is
present.

void add(Object o) It is used to add the specified element to this set if it is not already
present.

void clear() It is used to remove all of the elements from this set.

Object clone() It is used to return a shallow copy of this TreeSet instance.

Object first() It is used to return the first (lowest) element currently in this sorted
set.

Object last() It is used to return the last (highest) element currently in this
sorted set.

int size() It is used to return the number of elements in this set.


Java TreeSet Example
import java.util.*;
//Traversing elements
class TestCollection11{ Iterator<String> itr=al.iterator();
while(itr.hasNext()){
public static void main(String args[]){
System.out.println(itr.next());
//Creating and adding elements }
}
TreeSet<String> al=new TreeSet<String>(); }
al.add("Ravi");

al.add("Vijay");

al.add("Ravi"); Output
al.add("Ajay");
Ajay Ravi Vijay
Java TreeSet Example: Book
}else if(id<b.id){
import java.util.*;
return -1;
class Book implements Comparable<Book>{ }else{
return 0;
int id; }
}
String name,author,publisher;
}
int quantity;
public class TreeSetExample {
public Book(int id, String name, String author, String publisher, int quantity) { public static void main(String[] args) {
Set<Book> set=new TreeSet<Book>();
this.id = id;
//Creating Books
this.name = name; Book b1=new Book(121,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(233,"Operating System","Galvin","Wiley",6);
this.author = author; Book b3=new Book(101,"Data Communications & Networking","Forouzan","
Mc Graw Hill",4);
this.publisher = publisher;
//Adding Books to TreeSet
this.quantity = quantity; set.add(b1);
set.add(b2);
} set.add(b3);
//Traversing TreeSet
public int compareTo(Book b) { for(Book b:set){
if(id>b.id){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.qua
ntity);
return 1; } 101 Data Communications & Networking Forouzan Mc Graw Hill 4
} Output 121 Let us C Yashwant Kanetkar BPB 8
233 Operating System Galvin Wiley 6
}
Java Queue Interface
Java Queue interface orders the element in FIFO(First In First Out) manner. In FIFO, first element
is removed first and last element is removed at last.

Queue Interface declaration


public interface Queue<E> extends Collection<E>
Methods of Java Queue Interface
Method Description

boolean add(object) It is used to insert the specified element into this queue and return
true upon success.

boolean offer(object) It is used to insert the specified element into this queue.

Object remove() It is used to retrieves and removes the head of this queue.

Object poll() It is used to retrieves and removes the head of this queue, or returns
null if this queue is empty.

Object element() It is used to retrieves, but does not remove, the head of this queue.

Object peek() It is used to retrieves, but does not remove, the head of this queue,
or returns null if this queue is empty.
Java PriorityQueue Example
import java.util.*; System.out.println("iterating the queue elements:");
class TestCollection12{ Iterator itr=queue.iterator();
while(itr.hasNext()){
public static void main(String args[]){
System.out.println(itr.next());
PriorityQueue<String> queue=new PriorityQueue<String>(); }
queue.add("Amit"); queue.remove();
queue.poll();
queue.add("Vijay");
System.out.println("after removing two elements:");
queue.add("Karan"); Iterator<String> itr2=queue.iterator();
queue.add("Jai"); while(itr2.hasNext()){ head:Amit
head:Amit I
queue.add("Rahul"); System.out.println(itr2.next()); terating the queue elements: Amit
} Jai
System.out.println("head:"+queue.element()); Karan
} Vijay
Rahul
System.out.println("head:"+queue.peek()); } Output after removing two elements:
Karan
Rahul
Vijay
Java PriorityQueue Example: Book
import java.util.*;
public class LinkedListExample {
class Book implements Comparable<Book>{ public static void main(String[] args) {
Queue<Book> queue=new PriorityQueue<Book>();
int id; //Creating Books
Book b1=new Book(121,"Let us C","Yashwant Kanetkar","BPB",8);
String name,author,publisher; Book b2=new Book(233,"Operating System","Galvin","Wiley",6);
Book b3=new Book(101,"Data Communications & Networking","Forouzan","Mc Graw Hill
int quantity; ",4);
//Adding Books to the queue
public Book(int id, String name, String author, String publisher, int quantity) {
queue.add(b1);
this.id = id; queue.add(b2);
queue.add(b3);
this.name = name; System.out.println("Traversing the queue elements:");
//Traversing queue elements
this.author = author; for(Book b:queue){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
this.publisher = publisher; }
queue.remove();
this.quantity = quantity; }
System.out.println("After removing one book record:");
public int compareTo(Book b) { for(Book b:queue){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
if(id>b.id){ }
}
return 1; }
Traversing the queue elements:
}else if(id<b.id){ 101 Data Communications & Networking Forouzan Mc Graw Hill 4

return -1;
Output 233 Operating System Galvin Wiley 6
121 Let us C Yashwant Kanetkar BPB 8
After removing one book record:
}else{ 121 Let us C Yashwant Kanetkar BPB 8
233 Operating System Galvin Wiley 6
return 0; } } }
Java HashMap class
Java HashMap class implements the map interface by using a hashtable. It inherits AbstractMap
class and implements Map interface.
The important points about Java HashMap class are:
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
HashMap class Parameters

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


K: It is the type of keys maintained by this map.
V: It is the type of mapped values.
Constructors of Java HashMap class

Constructor Description

HashMap() It is used to construct a default HashMap.


HashMap(Map m) It is used to initializes the hash map by
using the elements of the given Map object
m.
HashMap(int capacity) It is used to initializes the capacity of the
hash map to the given integer value,
capacity.
HashMap(int capacity, float fillRatio) It is used to initialize both the capacity and
fill ratio of the hash map by using its
arguments.
Methods of Java HashMap class

Method Description

void clear() It is used to remove all of the mappings from this map.

boolean containsKey(Object key) It is used to return true if this map contains a mapping for the specified key.

boolean containsValue(Object value) It is used to return true if this map maps one or more keys to the specified value.

boolean isEmpty() It is used to return true if this map contains no key-value mappings.

Object clone() It is used to return a shallow copy of this HashMap instance: the keys and values
themselves are not cloned.

Set entrySet() It is used to return a collection view of the mappings contained in this map.

Set keySet() It is used to return a set view of the keys contained in this map.

Object put(Object key, Object value) It is used to associate the specified value with the specified key in this map.

int size() It is used to return the number of key-value mappings in this map.

Collection values() It is used to return a collection view of the values contained in this map.
Java HashMap Example
import java.util.*;
class TestCollection13{
public static void main(String args[]){
HashMap<Integer,String> hm=new HashMap<Integer,String>();
hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
Output
} 102 Rahul
100 Amit
101 Vijay
Java HashMap Example: remove()
import java.util.*;

public class HashMapExample {

public static void main(String args[]) {

// create and populate hash map

HashMap<Integer, String> map = new HashMap<Integer, String>();

map.put(101,"Let us C");

map.put(102, "Operating System");

map.put(103, "Data Communication and Networking");

System.out.println("Values before remove: "+ map);

// Remove value for key 102


Output
map.remove(102);

System.out.println("Values after remove: "+ map);


Values before remove: {102=Operating System, 103=Data Communication and Networking, 101=Let us C}
} } Values after remove: {103=Data Communication and Networking, 101=Let us C}
Java HashMap Example: Book
import java.util.*; public class MapExample {
public static void main(String[] args) {
class Book { //Creating map of Books
Map<Integer,Book> map=new HashMap<Integer,Book>();
int id; //Creating Books
String name,author,publisher; Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc
int quantity; Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
public Book(int id, String name, String author, String publisher,
//Adding Books to map
int quantity) { map.put(1,b1);
map.put(2,b2);
this.id = id;
map.put(3,b3);
this.name = name;
//Traversing map
this.author = author; for(Map.Entry<Integer, Book> entry:map.entrySet()){
int key=entry.getKey();
this.publisher = publisher; Book b=entry.getValue();
System.out.println(key+" Details:");
this.quantity = quantity;
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.qua
} } ntity); } } }
1 Details: 101 Let us C Yashwant Kanetkar BPB 8
Output 2 Details: 102 Data Communications & Networking Forouzan Mc Graw Hill 4
3 Details: 103 Operating System Galvin Wiley 6
Java LinkedHashMap class
Java LinkedHashMap class is Hash table and Linked list implementation of the Map interface,
with predictable iteration order. It inherits HashMap class and implements the Map interface.
The important points about Java LinkedHashMap class are:
A LinkedHashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
LinkedHashMap class Parameters

Let's see the Parameters for java.util.LinkedHashMap class.


K: It is the type of keys maintained by this map.
V: It is the type of mapped values.
Constructors of Java LinkedHashMap class

Constructor Description

LinkedHashMap() It is used to construct a default


LinkedHashMap.
LinkedHashMap(int capacity) It is used to initialize a LinkedHashMap
with the given capacity.

LinkedHashMap(int capacity, float It is used to initialize both the capacity


fillRatio) and the fillRatio.
LinkedHashMap(Map m) It is used to initialize the LinkedHashMap
with the elements from the given Map
class m.
Methods of Java LinkedHashMap class

Method Description

Object get(Object key) It is used to return the value to which


this map maps the specified key.

void clear() It is used to remove all mappings


from this map.
boolean containsKey(Object key) It is used to return true if this map
maps one or more keys to the
specified value.
Java LinkedHashMap Example
import java.util.*;

class TestCollection14{

public static void main(String args[]){

LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,String>();

hm.put(100,"Amit");

hm.put(101,"Vijay");

hm.put(102,"Rahul");
Output
100 Amit
101 Vijay
for(Map.Entry m:hm.entrySet()){ 102 Rahul

System.out.println(m.getKey()+" "+m.getValue()); } } }
Java LinkedHashMap Example:remove()
import java.util.*;

public class LinkedHashMapExample {

public static void main(String args[]) {

// Create and populate linked hash map

Map<Integer, String> map = new LinkedHashMap<Integer, String>();

map.put(101,"Let us C");

map.put(102, "Operating System");

map.put(103, "Data Communication and Networking");

System.out.println("Values before remove: "+ map);

// Remove value for key 102

map.remove(102); Output
System.out.println("Values after remove: "+ map);

} Values before remove: {101=Let us C, 102=Operating System, 103=Data Communication and Networking}
Values after remove: {101=Let us C, 103=Data Communication and Networking}
}
Java LinkedHashMap Example: Book
import java.util.*; public class MapExample {
public static void main(String[] args) {
class Book { //Creating map of Books
Map<Integer,Book> map=new LinkedHashMap<Integer,Book>();
int id;
//Creating Books
String name,author,publisher; Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc
int quantity; Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
public Book(int id, String name, String author, String publisher, int quantity) { //Adding Books to map
map.put(2,b2);
this.id = id;
map.put(1,b1);
this.name = name; map.put(3,b3);

this.author = author; //Traversing map


for(Map.Entry<Integer, Book> entry:map.entrySet()){
this.publisher = publisher; int key=entry.getKey();
this.quantity = quantity; Book b=entry.getValue();
System.out.println(key+" Details:");
} } 2 Details: 102 Data Communications & Networking Forouzan Mc Graw Hill 4 System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.qua
Output 1 Details: 101 Let us C Yashwant Kanetkar BPB 8
3 Details: 103 Operating System Galvin Wiley 6 ntity); } } }
Java TreeMap class
The important points about Java TreeMap class are:
A TreeMap contains values based on the key. It implements the NavigableMap interface and
extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order.
TreeMap class Parameters

Let's see the Parameters for java.util.TreeMap class.


K: It is the type of keys maintained by this map.
V: It is the type of mapped values.
Constructors of Java TreeMap class

TreeMap() It is used to construct an empty tree map that


will be sorted using the natural order of its key.

TreeMap(Comparator comp) It is used to construct an empty tree-based


map that will be sorted using the comparator
comp.
TreeMap(Map m) It is used to initialize a tree map with the
entries from m, which will be sorted using the
natural order of the keys.
TreeMap(SortedMap sm) It is used to initialize a tree map with the
entries from the SortedMap sm, which will be
sorted in the same order as sm.
Methods of Java TreeMap class
Method Description

boolean containsKey(Object key) It is used to return true if this map contains a mapping for the specified key.

boolean containsValue(Object value) It is used to return true if this map maps one or more keys to the specified value.

Object firstKey() It is used to return the first (lowest) key currently in this sorted map.

Object get(Object key) It is used to return the value to which this map maps the specified key.

Object lastKey() It is used to return the last (highest) key currently in this sorted map.

Object remove(Object key) It is used to remove the mapping for this key from this TreeMap if present.

void putAll(Map map) It is used to copy all of the mappings from the specified map to this map.

Set entrySet() It is used to return a set view of the mappings contained in this map.

int size() It is used to return the number of key-value mappings in this map.

Collection values() It is used to return a collection view of the values contained in this map.
Java TreeMap Example:
import java.util.*;

class TestCollection15{

public static void main(String args[]){

TreeMap<Integer,String> hm=new TreeMap<Integer,String>();

hm.put(100,"Amit");

hm.put(102,"Ravi");

hm.put(101,"Vijay");

hm.put(103,"Rahul");

for(Map.Entry m:hm.entrySet()){

System.out.println(m.getKey()+" "+m.getValue());
100 Amit
} Output 101 Vijay
102 Ravi
} 103 Rahul
}
Java TreeMap Example: remove()
import java.util.*;

public class TreeMapExample {

public static void main(String args[]) {

// Create and populate tree map

Map<Integer, String> map = new TreeMap<Integer, String>();

map.put(102,"Let us C");

map.put(103, "Operating System");

map.put(101, "Data Communication and Networking");

System.out.println("Values before remove: "+ map);

// Remove value for key 102

map.remove(102); Output
System.out.println("Values after remove: "+ map);
Values before remove: {101=Data Communication and Networking, 102=Let us C, 103=Operating System}
} Values after remove: {101=Data Communication and Networking, 103=Operating System}

}
What is difference between HashMap and TreeMap?

HashMap TreeMap

1) HashMap can contain one null key. TreeMap can not contain any null key.

2) HashMap maintains no order. TreeMap maintains ascending order.


Java TreeMap Example: Book
import java.util.*; public class MapExample {
public static void main(String[] args) {
class Book {
//Creating map of Books
int id; Map<Integer,Book> map=new TreeMap<Integer,Book>();
//Creating Books
String name,author,publisher; Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
int quantity;
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc
Graw Hill",4);
public Book(int id, String name, String author, String publisher, int quantity) { Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to map
this.id = id;
map.put(2,b2);
this.name = name; map.put(1,b1);
map.put(3,b3);
this.author = author;
//Traversing map
this.publisher = publisher;
for(Map.Entry<Integer, Book> entry:map.entrySet()){
this.quantity = quantity; int key=entry.getKey();
Book b=entry.getValue();
}
System.out.println(key+" Details:");
1 Details: 101 Let us C Yashwant Kanetkar BPB 8 System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.qua
} Output 2 Details: 102 Data Communications & Networking Forouzan Mc Graw Hill 4
ntity);
3 Details: 103 Operating System Galvin Wiley 6
} } }
Java Hashtable class
Java Hashtable class implements a hashtable, which maps keys to values. It inherits Dictionary
class and implements the Map interface.
The important points about Java Hashtable class are:
A Hashtable is an array of list. Each list is known as a bucket. The position of bucket is identified
by calling the hashcode() method. A Hashtable contains values based on the key.
It contains only unique elements.
It may have not have any null key or value.
It is synchronized.
Hashtable class Parameters

Let's see the Parameters for java.util.Hashtable class.


K: It is the type of keys maintained by this map.
V: It is the type of mapped values.
Constructors of Java Hashtable class

Constructor Description

Hashtable() It is the default constructor of hash table


it instantiates the Hashtable class.

Hashtable(int size) It is used to accept an integer parameter


and creates a hash table that has an
initial size specified by integer value size.

Hashtable(int size, float fillRatio) It is used to create a hash table that has
an initial size specified by size and a fill
ratio specified by fillRatio.
Methods of Java Hashtable class
Method Description

void clear() It is used to reset the hash table.


boolean contains(Object value) This method return true if some value equal to the value exist within the hash
table, else return false.

boolean containsValue(Object value) This method return true if some value equal to the value exists within the hash
table, else return false.

boolean containsKey(Object key) This method return true if some key equal to the key exists within the hash
table, else return false.

boolean isEmpty() This method return true if the hash table is empty; returns false if it contains at
least one key.

void rehash() It is used to increase the size of the hash table and rehashes all of its keys.

Object get(Object key) This method return the object that contains the value associated with the key.

Object remove(Object key) It is used to remove the key and its value. This method return the value
associated with the key.

int size() This method return the number of entries in the hash table.
Java Hashtable Example
import java.util.*;

class TestCollection16{

public static void main(String args[]){

Hashtable<Integer,String> hm=new Hashtable<Integer,String>();

hm.put(100,"Amit");

hm.put(102,"Ravi");

hm.put(101,"Vijay");

hm.put(103,"Rahul");

for(Map.Entry m:hm.entrySet()){

System.out.println(m.getKey()+" "+m.getValue());
Output 103 Rahul
102 Ravi
101 Vijay
} } }
100 Amit
Java Hashtable Example: remove()
import java.util.*;

public class HashtableExample {

public static void main(String args[]) {

// create and populate hash table

Hashtable<Integer, String> map = new Hashtable<Integer, String>();

map.put(102,"Let us C");

map.put(103, "Operating System");

map.put(101, "Data Communication and Networking");

System.out.println("Values before remove: "+ map);


Output
// Remove value for key 102

map.remove(102); Values before remove: {103=Operating System, 102=Let us C, 101=Data Communication and Networking}
Values after remove: {103=Operating System, 101=Data Communication and Networking}
System.out.println("Values after remove: "+ map);

} }
Java Hashtable Example: Book
import java.util.*; public class HashtableExample {
public static void main(String[] args) {
class Book { //Creating map of Books
Map<Integer,Book> map=new Hashtable<Integer,Book>();
int id; //Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
String name,author,publisher; Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4)
;
int quantity; Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to map
public Book(int id, String name, String author, String publisher, int quantity) {
map.put(1,b1);
this.id = id; map.put(2,b2);
map.put(3,b3);
this.name = name; //Traversing map
for(Map.Entry<Integer, Book> entry:map.entrySet()){
this.author = author; int key=entry.getKey();
Book b=entry.getValue();
this.publisher = publisher; System.out.println(key+" Details:");
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
this.quantity = quantity; }
}
} } 3 Details: 103 Operating System Galvin Wiley 6
Output 2 Details: 102 Data Communications & Networking Forouzan Mc Graw Hill 4
} 1 Details: 101 Let us C Yashwant Kanetkar BPB 8
Difference between ArrayList and Vector
ArrayList and Vector both implements List interface and maintains insertion order.
ArrayList Vector

1) ArrayList is not synchronized. Vector is synchronized.


2) ArrayList increments 50% of current array size if Vector increments 100% means doubles the array
number of element exceeds from its capacity. size if total number of element exceeds than its
capacity.
3) ArrayList is not a legacy class, it is introduced in Vector is a legacy class.
JDK 1.2.
4) ArrayList is fast because it is non-synchronized. Vector is slow because it is synchronized i.e. in
multithreading environment, it will hold the other
threads in runnable or non-runnable state until current
thread releases the lock of object.
5) ArrayList uses Iterator interface to traverse the Vector uses Enumeration interface to traverse the
elements. elements. But it can use Iterator also.
Example of Java ArrayList
import java.util.*;

class TestArrayList21{

public static void main(String args[]){

List<String> al=new ArrayList<String>();//creating arraylist

al.add("Sonoo");//adding object in arraylist

al.add("Michael");

al.add("James");

al.add("Andy");

//traversing elements using Iterator


Output
Iterator itr=al.iterator(); Sonoo
Michael
while(itr.hasNext()){ James
Andy
System.out.println(itr.next()); } } }
Example of Java Vector
import java.util.*;

class TestVector1{

public static void main(String args[]){

Vector<String> v=new Vector<String>();//creating vector

v.add("umesh");//method of Collection

v.addElement("irfan");//method of Vector

v.addElement("kumar");

//traversing elements using Enumeration

Enumeration e=v.elements();

while(e.hasMoreElements()){

System.out.println(e.nextElement()); Output
} umesh
irfan
} kumar
}
Java Swing
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written
in java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Difference between AWT and Swing
No. Java AWT Java Swing

1) AWT components are platform-dependent. Java swing components are platform-


independent.

2) AWT components are heavyweight. Swing components are lightweight.

3) AWT doesn't support pluggable look and Swing supports pluggable look and feel.
feel.

4) AWT provides less components than Swing. Swing provides more powerful
componentssuch as tables, lists, scrollpanes,
colorchooser, tabbedpane etc.

5) AWT doesn't follows MVC(Model View Swing follows MVC.


Controller) where model represents data, view
represents presentation and controller acts as
an interface between model and view.
Commonly used Methods of Component class

Method Description

public void add(Component c) add a component on another


component.
public void setSize(int width,int sets size of the component.
height)
public void sets the layout manager for the
setLayout(LayoutManager m) component.
public void setVisible(boolean b) sets the visibility of the
component. It is by default false.
Java Swing Tutorial
import javax.swing.*;

public class FirstSwingExample {

public static void main(String[] args) {

JFrame f=new JFrame();//creating instance of JFrame

JButton b=new JButton("click");//creating instance of JButton

b.setBounds(130,100,100, 40);//x axis, y axis, width, height

f.add(b);//adding button in JFrame

f.setSize(400,500);//400 width and 500 height

f.setLayout(null);//using no layout managers

f.setVisible(true);//making the frame visible } }


Example of Swing by Association inside
constructor
import javax.swing.*; f.add(b);//adding button in JFrame
public class Simple {
f.setSize(400,500);//400 width and 500 height
JFrame f; f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
Simple(){ }

f=new JFrame();//creating instance of JFrame public static void main(String[] args) {


new Simple();
}
}
JButton b=new JButton("click");//creating instance of JButton

b.setBounds(130,100,100, 40);
Simple example of Swing by inheritance
import javax.swing.*;

public class Simple2 extends JFrame{//inheriting JFrame }


public static void main(String[] args) {
JFrame f; new Simple2();
}}
Simple2(){

JButton b=new JButton("click");//create button

b.setBounds(130,100,100, 40);

add(b);//adding button on frame

setSize(400,500);

setLayout(null);

setVisible(true);