0% found this document useful (0 votes)
39 views137 pages

Java Document 2

The document explains the use of 'this' and 'super' keywords in Java, detailing their roles in referencing current class objects and superclass objects, respectively. It also covers the concept of interfaces, abstract classes, enums, and packages, highlighting their definitions, usage, and differences. Additionally, it introduces wrapper classes and the purpose of APIs in software development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views137 pages

Java Document 2

The document explains the use of 'this' and 'super' keywords in Java, detailing their roles in referencing current class objects and superclass objects, respectively. It also covers the concept of interfaces, abstract classes, enums, and packages, highlighting their definitions, usage, and differences. Additionally, it introduces wrapper classes and the purpose of APIs in software development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 137

this keyword

=============
 A "this" keyword is a java keyword which is used to refer current class object reference.
 We can utilize this keyword in following ways.
1) To refer current class variables
2) To refer current class methods
3) To refer current class constructors

1) To refer current class variables


------------------------------------
class A
{
int i=10;
int j=20;

A(int i,int j)
{
System.out.println(i+" "+j); // 100 200
System.out.println(this.i+" "+this.j); // 10 20
}
}
class Test
{
public static void main(String[] args)
{
A a =new A(100,200);
}
}
2) To refer current class methods
-----------------------------------
class A
{
public void m1()
{
System.out.println("M1-Method");
this.m2();
}
public void m2()
{
System.out.println("M2-Method");
}
}
class Test
{
public static void main(String[] args)
{
A a = new A();
a.m1();
}
}
3) To refer current class constructors
---------------------------------------
class A
{
A()
{
System.out.println("0-arg const");
}
A(int i)
{
this();
System.out.println("int-arg const");
}
A(double d)
{
this(10);
System.out.println("double-arg const");
}
}
class Test
{
public static void main(String[] args)
{
A a = new A(10.5d);
}
}
super keyword
=============
 A "super" keyword is a java keyword which is used to refer super class object reference.
 We can utilize super keyword in following ways.
1) To refer super class variables
2) To refer super class methods
3) To refer super class constructors
1) To refer super class variables
----------------------------------
class A
{
int i=10;
int j=20;
}
class B extends A
{
int i=100;
int j=200;
B(int i,int j)
{
System.out.println(this.i+" "+this.j); // 100 200
System.out.println(super.i+" "+super.j); //10 20
System.out.println(i+" "+j); //1000 2000
}
}
class Test
{
public static void main(String[] args)
{
B b=new B(1000,2000);
}
}
2) To refer super class methods
--------------------------------
class A
{
public void m1()
{
System.out.println("M1-Method");
}
}
class B extends A
{
public void m2()
{
super.m1();
System.out.println("M2-Method");
}
}
class Test
{
public static void main(String[] args)
{
B b=new B();
b.m2();
}
}
3) To refer super class constructors
-------------------------------------
class A
{
A()
{
System.out.println("A-const");
}
}
class B extends A
{
B()
{
super();
System.out.println("B-const");
}
}
class Test
{
public static void main(String[] args)
{
B b=new B();
}
}

ex:
---
class A
{
A(int i)
{
System.out.println("A-const");
}
}
class B extends A
{
B()
{
super(10);
System.out.println("B-const");
}
}
class Test
{
public static void main(String[] args)
{
B b=new B();
}
}
Interface
==========
 Interface is a collection of zero or more abstract methods.
 Abstract methods are incomplete method because they end with semicolon and do not have any
body.
ex:
public abstract void m1();
By default every abstract method is a public and abstract.
ex:
void m1();
 It is not possible to create object for interfaces.
 To write the implementation of abstract methods we will use implementation class.
 It is possible to create object for implementation class because it contains method with body.
 Interface contains only constants i.e public static final.
 If we know only service requirement specification then we need to use interface.
Diagram: java31.1
syntax:
------
interface <interface_name>
{
-
- // abstract methods
- // constants
-
}

ex:
---
interface A
{
public abstract void m1();
}
class B implements A
{
public void m1()
{
System.out.println("M1-Method");
}
}
class Test
{
public static void main(String[] args)
{
A a = new B();
a.m1();
}
}
If interface contains four methods then we need to override all methods otherwise we will get compile
time error.
ex:
---
interface A
{
public abstract void see();
public void show();
abstract void view();
void display();
}
class B implements A
{
@Override
public void see()
{
System.out.println("See Method");
}
@Override
public void show()
{
System.out.println("Show Method");
}
@Override
public void view()
{
System.out.println("view Method");
}
@Override
public void display()
{
System.out.println("display Method");
}
}
class Test
{
public static void main(String[] args)
{
A a = new B();
a.see();
a.show();
a.view();
a.display();
}
}
Note:
-----
In Java, the annotation @override is used in method overriding, which is a core concept of object-oriented
programming.

ex:
--
interface A
{
public abstract void m1();
}

class Test
{
public static void main(String[] args)
{
//Anonymous inner class
A a=new A()
{
public void m1()
{
System.out.println("M1-Method");
}
};
a.m1();
}
}
> In java, a class can't extend more then one class simultenously.
> But interface can extends more then one interface simultenously.
ex:
---
interface A
{
void m1();
}
interface B
{
void m2();
}
interface C extends A,B
{
void m3();
}
class D implements C
{
public void m1()
{
System.out.println("M1-Method");
}
public void m2()
{
System.out.println("M2-Method");
}
public void m3()
{
System.out.println("M3-Method");
}
}
class Test
{
public static void main(String[] args)
{
C c = new D();
c.m1();
c.m2();
c.m3();
}
}
A class can implements more then one interface.
ex
---
interface Father
{
float HT=6.2f;
void height();
}
interface Mother
{
float HT=5.8f;
void height();
}
class Child implements Father,Mother
{
public void height()
{
float height=(Father.HT+Mother.HT)/2;
System.out.println("Child Height : "+height);
}
}
class Test
{
public static void main(String[] args)
{
Child c=new Child();
c.height();
}
}
Note:
-----
 According Java 8 version, Interface is a collection of abstract methods ,default methods and static
methods.

Marker interface
=================
 Interface which does not have any methods and constants is called marker interface.
 In general, empty interface is called marker interface.
 Using marker interface we will get some ability to do.
 We have following list of marker interface.
ex:
Serializable
Cloneable
Remote
and etc.
Serializable
=============
 It is an interface which is present in java.io package.
 A class that implements this interface can be serialized, meaning it's objects can be convert to
byte stream for storage and transmission.
ex:
class Person implements java.io.Serializable
{
private String name;
private int age;

public Person(String name,int age)


{
this.name=name;
this.age=age;
}

@Override
public String toString()
{
return "Person : ["+name+","+age+"]";
}
}
Abstract class
===============
 Abstract class is a collection of zero or more abstract methods and concrete methods.
 A "abstract" keyword is applicable for methods and classes but not for variables.
 It is not possible to create object for abstract class.
 By default every abstract method is a public and abstract.
ex:
void m1();

A concrete method is a non-abstract method.


ex:
void m1()
{
}
 To write the implementation of abstract methods we will use sub classes.
 Abstract class contains instance variables.
syntax:
------
abstract class <class_name>
{
-
- //abstract methods
- //concrete methods
- //instance variables
-
}
If we know partial implementation then we need to use abstract class.
ex:
---
abstract class Person
{
//abstract method
public abstract void hostel();
//concrete method
public void course()
{
System.out.println("Java-Course");
}
}
class Student extends Person
{
public void hostel()
{
System.out.println("Ameerpet-Hostel");
}
}
class Test
{
public static void main(String[] args)
{
Student s=new Student();
s.hostel();
s.course();
}
}
ex:
---
abstract class Plan
{
//instance variable
protected double rate;

//abstract method
public abstract void getRate();

//concrete method
public void calculateBillAmt(int units)
{
System.out.println("Total Units :"+units);
System.out.println("Total Bill :"+(units*rate));
}
}
class DomesticPlan extends Plan
{
public void getRate()
{
rate=2.5d;
}
}
class CommercialPlan extends Plan
{
public void getRate()
{
rate=5.0d;
}
}
class Test
{
public static void main(String[] args)
{
DomesticPlan dp=new DomesticPlan();
dp.getRate();
dp.calculateBillAmt(250);

CommercialPlan cp=new CommercialPlan();


cp.getRate();
cp.calculateBillAmt(250);
}
}
Q) What is the difference between interface and abstract class?
interface abstract class
------------------ ------------------
To declare interface we will use interface To declare abstract class we will use abstract
keyword. keyword.

It is a collection of abstract methods, It is a collection of abstract methods and


default methods and static methods. concrete methods.

It contains constants. It contains instance variables.

We can achieve multiple inheritance. We can't achieve multiple inheritance.

It does not allow constructor. It allows constructor.

We can't declare blocks. We can declare blocks.

If we know only specification then we need If we know partial implementation then we need to
to use interface. use abstract class.
Enum
=====
 Enum concept introduced in Java 1.5.
 Enum is a group of named constants.
 Using enum we can create our own datatype called enumerated datatype.
 When compare to old language enum , java enum is more powerful.
 To a declare a enum we will use enum keyword.
ex:
enum <type_name>
{
VAL1,VAL2,....,VALN
}

ex:
enum Months
{
JAN,FEB,MAR
}
Internal implementation of enum
-------------------------------
 Every enum internally consider as class concept and it extends with java.lang.Enum class.
 Every enum constant is a reference variable of enum type.
ex:

enum Months public final class Months extends java.lang.Enum


{ {
JAN,FEB,MAR ===> public static final Months JAN=new Months();
} public static final Months FEB=new Months();
public static final Months MAR=new Months();
}

Declaration and usage of enum


------------------------------
enum Months
{
JAN,FEB,MAR
}
class Test
{
public static void main(String[] args)
{
Months m = Months.JAN;
System.out.println(m);// JAN
}
}
From Java 1.5 version onwards it is possible to pass enum in a switch case.
ex:
---
enum Months
{
JAN,FEB,MAR
}
class Test
{
public static void main(String[] args)
{
Months m = Months.FEB;
switch(m)
{
case JAN: System.out.println("January"); break;
case FEB: System.out.println("February"); break;
case MAR: System.out.println("March"); break;
}
}
}
java.lang.Enum
---------------
 The power to enum will be inherited from java.lang.Enum class.
 It contains following two methods.
1) values()
----------
This static method is used to return group of constants from enum.
2) ordinal()
----------
It is used to return ordinal number of enum constant.
ex:
---
enum Months
{
JAN,FEB,MAR
}
class Test
{
public static void main(String[] args)
{
Months[] m=Months.values();

for(Months m1:m)
{
System.out.println(m1+" ----------- "+m1.ordinal());
}
}
}
When compare to old language enum , java enum is more powerful because in addition to constants we
can declare variables , methods and constructors.
ex:
---
enum Drinks
{
COKE,PEPSI,CAMPA;

Drinks()
{
System.out.println("constructor");
}
}
class Test
{
public static void main(String[] args)
{
Drinks d=Drinks.PEPSI;
}
}
ex
---
enum Week
{
MON,TUE,WED,THU,FRI,SAT,SUN;

static int i=10;

public static void main(String[] args)


{
System.out.println(i);
}
}
API
=====
 API stands for Application Programming Interface.
 It is a base for the programmer to develop software applications.
 It is a collection of packages.
 It is divided into three types.

1) predefined API
-----------------
Built-In API is called predefined API.
ex:
https://docs.oracle.com/javase/8/docs/api/
2) Userdefined API
------------------
API which is created by the user based on the application requirement.
3) Third party API
----------------
API which is given by third party vendor.
ex:
JavaZoom API
iText API
and etc.
Packages
=========
 A package is a collection of classes , interfaces , enums and annotations.
 Here enum is a special class and annotation is a special interface.
 In general, a package is a collection of classes and interface.
 A package is also known as folder or a directory.
 In java packages are divided into two types.
1) Predefined packages
2) Userdefined packages
1) Predefined packages
-------------------
Built-In packages are called predefined packages.
ex:
java.lang
java.io
java.util
java.util.stream
java.sql
javax.servlet
and etc.
2) Userdefined packages
------------------------
 A package which is created by the user based on the application requirement is called userdefined
package.
 To declare a userdefined package we need to use "package" keyword.
 It is always recommanded to declare a package name in the reverse order of url.
syntax:
package <package_name>;
ex:
package com.google.www;
ex:
---
package com.ihub.www;
import java.util.Calendar;
class Test
{
public static void main(String[] args)
{
Calendar c=Calendar.getInstance();
int h=c.get(Calendar.HOUR_OF_DAY);

if(h<12)
System.out.println("Good Morning");
else if(h<16)
System.out.println("Good Afternoon");
else if(h<20)
System.out.println("Good Evening");
else
System.out.println("Good Night");
}
}
We can compile above program by using below command.
ex:
current directory
|
javac -d . Test.java
|
destination folder

We can run above program by using below command.


ex:
java com.ihub.www.Test
|
packagename
Wrapper classes
===============
The main objective of wrapper classes are.
1) To wrap primitive to wrapper objects and vice versa.
2) To defined several utility methods.
ex:
primitive type wrapper class
-------------- -------------
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
constructor
-------------
Every wrapper class contains following two constructors. One will take corresponding primitive as an
argument and another will take corresponding String as an argument.
ex:
wrapper class constructor
----------- -----------
Byte byte or String
Short short or String
Integer int or String
Long long or String
Float float or String
Double double or String
Boolean boolean or String
Character char
ex:
---
class Test
{
public static void main(String[] args)
{
Integer i1=new Integer(10);
System.out.println(i1); // 10

Integer i2=new Integer("20");


System.out.println(i2); // 20
}
}
ex
----
class Test
{
public static void main(String[] args)
{
Boolean b1=new Boolean(true);
System.out.println(b1); //true

Boolean b2=new Boolean("false");


System.out.println(b2); //false
}
}

ex:
---
class Test
{
public static void main(String[] args)
{
Character c=new Character('a');
System.out.println(c);
}
}
Utility methods
==============
1) valueOf()
-------------
It is similar to constructor.
It is used to convert primitive type to wrapper object.
ex:
class Test
{
public static void main(String[] args)
{
Integer i1=Integer.valueOf(10);
System.out.println(i1);//10

Long l1=Long.valueOf("20");
System.out.println(l1);
}
}
2) xxxValue() method
---------------------
It is used to convert wrapper object to primitive type .
ex:

class Test
{
public static void main(String[] args)
{
Integer i=new Integer(10);

byte b=i.byteValue();
System.out.println(b);//10

short s=i.shortValue();
System.out.println(s);//10
}
}
3) parseXxx()
------------
It is used to convert String to primitive type.
ex:
class Test
{
public static void main(String[] args)
{
String str="12";

int i=Integer.parseInt(str);
System.out.println(i); // 12

long l=Long.parseLong(str);
System.out.println(l); // 12

float f=Float.parseFloat(str);
System.out.println(f); // 12.0
}
}
4) toString()
------------
It is used to convert wrapper object to string type.
ex:
---
class Test
{
public static void main(String[] args)
{
Integer i1=new Integer(10);

String str = i1.toString();

System.out.println(str); // 10
}
}
Interview Question
------------------
Q) Write a java program to perform sum of two binary numbers?
input: 1010
0101
output: 1111
ex:
--
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first binary number : ");
String binary1=sc.next(); // 1010
System.out.println("Enter the second binary number : ");
String binary2=sc.next(); // 0101
//convert binary to decimal
int a = Integer.parseInt(binary1,2);
int b = Integer.parseInt(binary2,2);
int c = a+b;
//convert decimal to binary
String result=Integer.toBinaryString(c);
System.out.println(result);
}
}
Inner classes
==============
Sometimes we will declare a class inside another class such concept is called inner class.
Ex:
class Outer
{
class Inner
{
-
-
-
}
}
Inner classes introduced as a part of event handling to remove GUI bugs.
But due to powerful features and benefits of inner classes. Programmers started to use inner classes in
regular programming.
In inner classes we can't declare static members.
Accessing inner class data from static area of outer class
--------------------------------------------------------
class Outer
{
class Inner
{
public void m1()
{
System.out.println("M1-Method");
}
}
public static void main(String[] args)
{
Outer o=new Outer();
Outer.Inner i=o.new Inner();
i.m1();
}
}

If we compile above program two .class file will generated i.e Outer.class and Outer$Inner.class.

ex:
---
class Outer
{
class Inner
{
public void m1()
{
System.out.println("M1-Method");
}
}
public static void main(String[] args)
{
Outer.Inner i=new Outer().new Inner();
i.m1();
}
}
ex:
---
class Outer
{
class Inner
{
public void m1()
{
System.out.println("M1-Method");
}
}

public static void main(String[] args)


{
new Outer().new Inner().m1();
}
}
ex:
----
class Outer
{
class Inner
{
public static void m1()
{
System.out.println("M1-Method");
}
}
public static void main(String[] args)
{
new Outer().new Inner().m1();
}
}

o/p:
C.T.E : Illegal static declaration
ex:
class Outer
{
class Inner
{
static int i=10;

public void m1()


{
System.out.println(i);
}
}

public static void main(String[] args)


{
new Outer().new Inner().m1();
}
}

o/p:
C.T.E : Illegal static declaration
Accessing inner class data from non-static area of outer class
------------------------------------------------------------
class Outer
{
class Inner
{
public void m1()
{
System.out.println("M1-Method");
}
}
public void m2()
{
Inner i=new Inner();
i.m1();
}
public static void main(String[] args)
{
Outer o=new Outer();
o.m2();
}
}
Note:
-----
We use inner classes to logically group classes and interfaces in one place to be more readable and
maintainable.
Anonymous inner class
======================
A class which does not have any name is called anonymous.
The main objective of anonymous inner class is just for instance use.
ex:
interface A
{
void m1();
}
class Test
{
public static void main(String[] args)
{
//Anonymous inner class
A a = new A()
{
public void m1()
{
System.out.println("M1 Method");
}
};
a.m1();
}
}
Types of objects
==================
We have two types of objects in java.
1) Immutable object
2) Mutable object

1) Immutable object
--------------------
Immutable object does not allow to modify object state.
After object creation we can't perform any changes. If we perform any changes then for every change a
new object will be created such type of object is called immutable object.
ex:
wrapper classes and String
2) Mutable object
------------------
Mutable object allows to modify object state.
After object creation we can perform any changes. All the required changes will perform in a same object
such type of object is called mutable object.
ex:
StringBuffer and StringBuilder

String
======
A String is a collection of characters which is enclosed in a double quotation.
case1:
------
Once if we create a String object we can't perform any changes. If we perform any changes then for every
change a new object will be created such behaviour is called immutability of an object.
class Test
{
public static void main(String[] args)
{
String s1=new String("ihub");

s1.concat("talent");

System.out.println(s1); //ihub
}
}
Diagram: java33.1

case2:
-------
Q) What is the difference between == and .equals() method?
==
---
It is used to compare primitive types and object types.
It is used for reference or address comparision.
ex:
class Test
{
public static void main(String[] args)
{
String s1=new String("ihub");

String s2=new String("ihub");

System.out.println(s1==s2); // false
}
}

.equals()
----------
It is used to compare object types only.
It is used for content comparision.
It is a case sensitive.
ex:
class Test
{
public static void main(String[] args)
{
String s1=new String("ihub");
String s2=new String("ihub");
System.out.println(s1.equals(s2)); // true
}
}
case3:
-----
Whenever we create a String object. Two objects will be created one is on heap and another is on SCP
(String Constant Pool) area.But 's' always points to heap area object.
Diagram: java33.2

 Object creation in SCP area is always optional.First JVM will check is there any object is created
with same content or not.If it is created then JVM simply refers to that object.If it is not created
then JVM create a new object.Hence there is a no chance of having duplicate objects in SCP area.
 Even though SCP area object do not have reference, garbage collector can't access them.
 SCP objects will destroy automatically whenever JVM shutdowns or terminated.
Diagram: java33.3

Interning of String object


==========================
With the help of heap object reference if we need corresponding SCP object reference then we need to use
intern() method.

Diagram: java33.4

String important methods


=========================
Q) Write a java program to display length of the string?
class Test
{
public static void main(String[] args)
{
String str="ihub";
System.out.println(str.length());//4
}}
Q) Write a java program to convert string to upper case ?
class Test
{
public static void main(String[] args)
{
String str="ihub";
System.out.println(str.toUpperCase());//IHUB
}
}
Q) Write a java program to convert string to lower case ?
class Test
{
public static void main(String[] args)
{
String str="IHUB";
System.out.println(str.toLowerCase());//ihub
}
}
Q) Write a java program to compare two strings?
class Test
{
public static void main(String[] args)
{
String str1="ihub";
String str2="IHUB";
if(str1.equals(str2))
System.out.println("Both are equal");
else
System.out.println("Both are not equal");
}
}

approach2
-----------
class Test
{
public static void main(String[] args)
{
String str1="ihub";
String str2="IHUB";

if(str1.equalsIgnoreCase(str2))
System.out.println("Both are equal");
else
System.out.println("Both are not equal");
}
}
Q) Write a java program to read any character from string based on the index?
class Test
{
public static void main(String[] args)
{
String str="ihubtalent";
System.out.println(str.charAt(5));//a
}
}
Q) Write a java program to concatinate two strings?
class Test
{
public static void main(String[] args)
{
String str="ihub";
str=str.concat("talent");
System.out.println(str);//ihubtalent
}
}
Q) Write a java program to get the index value of a character in a given string?
class Test
{
public static void main(String[] args)
{
String str="qualitythought";
System.out.println(str.indexOf('t'));//5
System.out.println(str.lastIndexOf('t'));//13

}
}

Q) Write a java program to check given word present in a string or not?


class Test
{
public static void main(String[] args)
{
String str="this is java class";
String word="java";
if(str.contains(word))
System.out.println("It is present");
else
System.out.println("It is not present");
}
}
Q) Write a java to remove special characters from given string?
input:
I_hub@Ta#len$t12
output:
IhubTalent12
class Test
{
public static void main(String[] args)
{
String str="I_hub@Ta#len$t12";
str=str.replaceAll("[^A-Za-z0-9]","");
System.out.println(str);
}
}
Q) Write a java program to remove the spaces from given string?
Input: I hub Tal ent
Output: IhubTalent
ex:
class Test
{
public static void main(String[] args)
{
String str="I hub Tal ent";
str=str.replaceAll("\\s","");
System.out.println(str);
}
}
Q) Write a java program to concatinate two strings?
Input:
ihub12
talent8
Output:
ihubtalent20
ex:
---
class Test
{
public static void main(String[] args)
{
String s1="ihub12";
String s2="talent8";

String word1=s1.replaceAll("[^A-Za-z]","");
int num1=Integer.parseInt(s1.replaceAll("[^0-9]",""));

String word2=s2.replaceAll("[^A-Za-z]","");
int num2=Integer.parseInt(s2.replaceAll("[^0-9]",""));

String word=word1+word2;
int num = num1+num2;

System.out.println(word+num);

}
}
Q) Write a java program to display the string in a given format?
input: NEX123
output: Number of Digits : 3
Sum of digits : 6
It is a even number
ex:
---
class Test
{
public static void main(String[] args)
{
String str="NEX123";

str=str.replaceAll("[^0-9]","");

//number of digits
System.out.println("Number of Digits :"+str.length());

//sum of digits
int sum=0;
for(int i=0;i<str.length();i++)
{
int n=Character.getNumericValue(str.charAt(i));
sum+=n;
}
System.out.println("Sum of digits :"+sum);

//even logic
if(sum%2==0)
System.out.println("It is even number");
else
System.out.println("It is odd number");
}
}
Q) Write a java program to perform right rotation of a given string?
Input: str = ihubtalent
cnt = 4
Output: talentihub
ex:
---
class Test
{
public static void main(String[] args)
{
String str="ihubtalent";

int cnt=4;

String word1=str.substring(cnt,str.length());

String word2=str.substring(0,cnt);

System.out.println(word1+word2);
}
}
Q) Write a java program to insert a word in a given index of a string?
Input: str = ihubtalent
word = for
index = 4
Output: ihubfortalent
ex:
class Test
{
public static void main(String[] args)
{
String str="ihubtalent";

String word="for";

int index= 4;

String word1=str.substring(0,index); // ihub


String word2=str.substring(index,str.length()); // talent

str = word1+word+word2;
System.out.println(str);
}
}
Q) Write a java program to display the string in sorting order of alphabets?
Input: daebcf
output: abcdef
ex:
---
import java.util.Arrays;
class Test
{
public static void main(String[] args)
{
String str="daebcf";

char[] carr=str.toCharArray();

Arrays.sort(carr);

//reading the characters from char array


for(char ch:carr)
{
System.out.print(ch);
}
}
}
Q) Write a java program to display reverse of a string?
input: hello
output: olleh
ex:\
---
class Test
{
public static void main(String[] args)
{
String str="hello";

//reading reverse
String rev="";

for(int i=str.length()-1;i>=0;i--)
{
rev+=str.charAt(i);
}

System.out.println(rev);
}
}
Q) Write a java program to check given string is palindrome or not?
input: racar
output: It is a palindrome string
ex:
class Test
{
public static void main(String[] args)
{
String str="racar";

//reading reverse
String rev="";

for(int i=str.length()-1;i>=0;i--)
{
rev+=str.charAt(i);
}

if(str.equals(rev))
System.out.println("It is a palindrome string");
else
System.out.println("It is not a palindrome string");
}
}
Q) Write a java program to display reverse of a sentence?
input: this is java class
output: class java is this
ex:
class Test
{
public static void main(String[] args)
{
String str="this is java class";

String[] sarr=str.split(" "); // this is java class


for(int i=sarr.length-1;i>=0;i--)
{
System.out.print(sarr[i]+" ");
}
}
}
Q) Write a java program to display reverse of a word in a sentence?
input: this is java class
output: siht si avaj ssalc
ex:
class Test
{
public static void main(String[] args)
{
String str="this is java class";

String[] sarr=str.split(" "); // this is java class

//reading the data from string array


for(String s:sarr)
{
//convert the string to char array
char[] carr=s.toCharArray(); // t h i s

//reading reverse
for(int i=carr.length-1;i>=0;i--)
{
System.out.print(carr[i]);
}

//space
System.out.print(" ");
}

}
}
Q) Write a java program to display the string in a given format?
input: XYZ
Output:XY
XZ
YX
YZ
ZX
ZY
ex:
class Test
{
public static void main(String[] args)
{
String str="XYZ";
for(int i=0;i<str.length();i++)
{
for(int j=0;j<str.length();j++)
{
if(str.charAt(i)!=str.charAt(j))
{
System.out.println(str.charAt(i)+""+str.charAt(j));
}
}
}
}
}
Q) Write a java program to display duplicate and unique characters from given string?
Input: massissippi
Output: Duplicate characters : sip
unique characters : masip
ex:
class Test
{
public static void main(String[] args)
{
String str="massissippi";

String duplicate="";
String unique="";

for(int i=0;i<str.length();i++)
{
String current=Character.toString(str.charAt(i));

if(unique.contains(current))
{
if(!duplicate.contains(current))
{
duplicate+=current;
continue;
}
else
{
continue;
}
}
unique+=current;
}
System.out.println("Duplicate characters : "+duplicate);
System.out.println("Unique characters : "+unique);
}
}
Q) Write a java program to display vowels from given string?
input: umbrella
Output: uea
Ex:
class Test
{
public static void main(String[] args)
{
String str="umbrella";

for(int i=0;i<str.length();i++)
{
char ch=str.charAt(i);

if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u')


{
System.out.print(ch+" ");
}
}
}
}
Q) Write a java program display the string starting with initcap?
input: This is Java student Class
Output: This Java Class
ex:
class Test
{
public static void main(String[] args)
{
String str="This is Java student Class";

String[] sarr=str.split(" "); // This is Java student Class

//reading the data from string array


for(String s:sarr)
{
if(s.charAt(0)>='A' && s.charAt(0)<='Z')
{
System.out.print(s+" ");
}
}
}
}
Q) Write a java program to display palindrome string?
Input: racar is madam for student
output: racar madam
ex:
class Test
{
public static void main(String[] args)
{
String str="racar is madam for student";

String[] sarr=str.split(" "); // racar is madam for student

//reading the data from string array


for(String s:sarr)
{
String rev="";

//reading reverse
for(int i=s.length()-1;i>=0;i--)
{
rev+=s.charAt(i);
}

if(s.equals(rev))
System.out.print(s+" ");
}
}
}
Assignment
==========
Q) Write a java program count number of lowercase letters, uppercase letters, words and spaces in
a given string?
input: This Is Java Class34
Output: uppercase letters : 4
lowercase letters : 11
Digits : 2
Words : 4
Spaces : 3
Q) Write a java program to find out most repeating character in a given string?
input:
ihubtalentinstitute
Output:
t is repeating for 5 times
ex:
---
class Test
{
public static void main(String[] args)
{
String str="ihubtalentinstitute";

char ch=' ';


int maxCount=0;

for(int i=0;i<str.length();i++)
{
int cnt=0;

for(int j=0;j<str.length();j++)
{
if(str.charAt(i)==str.charAt(j))
{
cnt++;
}
}

if(maxCount<cnt)
{
maxCount=cnt;
ch=str.charAt(i);
}
}

System.out.println(ch+" is repeating for "+maxCount+" times");


}
}
Q) Write a java program to display given string is Anagram or not?
Input: silent
listen
Output: It is a Anagram string
ex:
---
import java.util.Arrays;
class Test
{
public static void main(String[] args)
{
String str1="silent";
String str2="listen";
char[] carr1=str1.toCharArray();
char[] carr2=str2.toCharArray();

Arrays.sort(carr1); // e i l n s t
Arrays.sort(carr2); // e i l n s t

boolean flag=true;
for(int i=0;i<carr1.length && i<carr2.length;i++)
{
if(carr1[i]!=carr2[i])
{
flag=false;
break;
}
}
if(flag)
System.out.println("It is a Anagram string");
else
System.out.println("It is not a Anagram string");
}
}
Q) Write a java program to display the string in a given format?
input: A1B2C3D4
Output: ABBCCCDDDD
ex
---
class Test
{
public static void main(String[] args)
{
String str="A1B2C3D4";

for(int i=0;i<str.length();i++)
{
if(Character.isAlphabetic(str.charAt(i)))
{
System.out.print(str.charAt(i));
}
else
{
int n=Character.getNumericValue(str.charAt(i));

for(int k=1;k<n;k++)
{
System.out.print(str.charAt(i-1));
}
}
}
}
}
Q) Write a java program to find out encoding of a given string?
Input: 1106
Output: AAJF
Ex:
class Test
{
public static void main(String[] args)
{
String str="1106";

for(int i=0;i<str.length();i++)
{
int n=Character.getNumericValue(str.charAt(i));

if(n>0)
{
System.out.print((char)('A'+ n-1));
}
else
{
int k=Integer.parseInt(str.substring(i-1,i+1));
System.out.print((char)('A'+k-1));
}
}
}
}
Q) Write a java program to display permutation of a given string?
input: ABC
output:
ABC
ACB
BAC
BCA
CBA
CAB
ex:
class Test
{
public static void main(String[] args)
{
String str="ABC";
isPermutation(str.toCharArray(),0);
}
public static void isPermutation(char[] arr,int fi)
{
if(fi==arr.length-1)
{
System.out.println(arr);
return;
}

for(int i=fi;i<arr.length;i++)
{
swapping(arr,fi,i);
isPermutation(arr,fi+1);
swapping(arr,fi,i);
}
}
public static void swapping(char[] arr,int fi,int i)
{
char temp=arr[fi];
arr[fi]=arr[i];
arr[i]=temp;
}
}
StringBuffer
=============
1) If our content change frequently then it is never recommanded to go with String because for every
change a new object will be created.
2) To overcome this limitation Sun Micro System introduced StringBuffer concept.
3) In StringBuffer all the required changes will be done in one/same object.
4) StringBuffer is a mutable object.
constructors
------------
1) StringBuffer sb=new StringBuffer()
-------------------------------------
1) It will create a empty StringBuffer object with default initial capacity of 16.
2) If capacity reaches to maximum capacity then StringBuffer object is created with new capacity
with below formulea.
ex:
capacity = current_capacity + 1 * 2;
ex:
---
class Test
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//16

sb.append("abcdefghijklmnop");
System.out.println(sb.capacity());//16

sb.append("qr");
System.out.println(sb.capacity());//16+1*2=34
}
}
2) StringBuffer sb=new StringBuffer(int capacity)
-------------------------------------
It will create StringBuffer object with specified initial capacity.
ex:
class Test
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer(19);
System.out.println(sb.capacity());//19
}
}
3) StringBuffer sb=new StringBuffer(String s)
-------------------------------------
It will create StringBuffer object which can hold the string.
Here capacity will be created with below formulea.
ex:
capacity = s.length() + 16;
class Test
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer("ihub");
System.out.println(sb.capacity());//4+16=20
}
}
Q) Write a java program to display reverse of a given string?
input: hello
output: olleh
ex:
class Test
{
public static void main(String[] args)
{
String str="hello";

StringBuffer sb=new StringBuffer(str);

String rev=sb.reverse().toString();

System.out.println(rev);
}
}
Q) Write a java program to check given string is palindrome or not?
input: racar
output: It is a palindrome string
ex:
class Test
{
public static void main(String[] args)
{
String str="racar";

StringBuffer sb=new StringBuffer(str);

String rev=sb.reverse().toString();

if(str.equals(rev))
System.out.println("It is a palindrome string");
else
System.out.println("It is not a palindrome string");
}
}
Q) Write a java program to multiply two arrays?
Input: 3 4 6
13
Output: 4498 (346*13)

ex
---
class Test
{
public static void main(String[] args)
{
int[] arr1={3,4,6};
int[] arr2={1,3};
int a=Integer.parseInt(arrayToString(arr1));
int b=Integer.parseInt(arrayToString(arr2));
System.out.println(a*b);
}
public static String arrayToString(int[] arr)
{
StringBuffer sb=new StringBuffer();
for(int i:arr)
{
sb.append(i);
}
return sb.toString();
}
}
Q) Write a java program to display the string in a given format?
Input: ABBCCCDDDD
Output: A1B2C3D4
ex:
class Test
{
public static void main(String[] args)
{
String str="ABBCCCDDDD";

StringBuffer sb=new StringBuffer();

int count=1;

for(int i=0;i<str.length();i++)
{
if(i<str.length()-1 && str.charAt(i) == str.charAt(i+1))
{
count++;
}
else
{
sb.append(str.charAt(i)).append(count);
count=1;
}
}

System.out.println(sb.toString());
}
}
Q) Write a java program to count number of occurance of 2's?
input: 22
output: 6 (2,12,20,21,22)
ex
--
class Test
{
public static void main(String[] args)
{
int num=22;

StringBuffer sb=new StringBuffer();

for(int i=1;i<=num;i++)
{
sb.append(i);
}
int count=0;
//reading the data from stringbuffer
for(int i=0;i<sb.length();i++)
{
int n=Character.getNumericValue(sb.charAt(i));
if(n==2)
{
count++;
}
}

System.out.println(count);
}
}
StringBuilder
==============
 StringBuilder is exactly same as StringBuffer with following differences.

StringBuffer StringBuilder
--------------- --------------
All the methods present in StringBuffer are No method present in StringBuidler is synchronized.
synchronized.

At a time only one thread is allowed to operate Multiple threads are allowed to operate on
on StringBuffer object. Hence StringBuffer is StringBuilder object. Hence StringBuilder is not
thread safe. thread safe.

Waiting time of a thread will increase There is no waiting threads relatively performance
relatively performance is low. is high.

It is introduced in 1.0v. It is introduced in 1.5v.

Q) Write a java program to display reverse of a given number?


import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number :");
int n=sc.nextInt();
//convert number to string and store in StringBuilder
StringBuilder sb=new StringBuilder(Integer.toString(n));

String rev=sb.reverse().toString();

System.out.println(rev);
}
}
Note:
-----
1) If our content not change frequently then it is recommanded to use String.
2) If our content change frequently where thread safety is required then we need to use StringBuffer.
3) If our content change frequently where thread safety is not required then we need to use
StringBuilder.
StringTokenizer
================
1) It is a class which is present in java.util package.
2) It is used to tokenize the string for processing.
3) We can create StringTokenizer object as follow.
ex:
StringTokenizer st=new StringTokenizer(String str,RegularExpression regex);

StringTokenizer class contains following methods.


ex:
public boolean hasMoreTokens()
public String nextToken()
public boolean hasMoreElements()
public Object nextElement()
public int countTokens()

ex
---
import java.util.StringTokenizer;
class Test
{
public static void main(String[] args)
{
StringTokenizer st=new StringTokenizer("this is java class");

System.out.println(st.countTokens());

}
}
Note:
space is a default regular expression.
ex:
---
import java.util.StringTokenizer;
class Test
{
public static void main(String[] args)
{
StringTokenizer st=new StringTokenizer("this is java class");

while(st.hasMoreTokens())
{
String s=st.nextToken();
System.out.println(s);
}

}
}
ex:
---
import java.util.StringTokenizer;
class Test
{
public static void main(String[] args)
{
StringTokenizer st=new StringTokenizer("this is java class"," ");

while(st.hasMoreElements())
{
String s=(String)st.nextElement();
System.out.println(s);
}

}
}
ex:
---
import java.util.StringTokenizer;
class Test
{
public static void main(String[] args)
{
StringTokenizer st=new StringTokenizer("9,99,999",",");

while(st.hasMoreElements())
{
String s=(String)st.nextElement();
System.out.println(s);
}

}
}
Exception Handling
==================
Q) What is the difference between Exception and Error?
Exception
---------
Exception is a problem for which we can provide solution programmatically.
Exception will occur due to syntax errors.
ex:
FileNotFoundException
ArithmeticException
IllegalArgumentException
Error
------
Error is a problem for which we can't provide solution programmatically.
Error will occur to lack of system resources.
ex:
OutOfMemoryError
StackOverFlowError
LinkageError
Q) Types of Errors in java?
We have three types of errors.
1) Logical Error
2) Compile time Error
3) Runtime Error (exception)

 As a part of java application development it is a responsibility of a programmer to provide


smooth termination for every java program.
 We have two types of terminations.
1) Smooth termination / Graceful termination
2) Abnormal termination

1) Smooth termination
----------------------
> During the program execution suppose if we are not getting any interruption in the middle of the
program such type of termination is called smooth termination.
ex:

class Test
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}

2) Abnormal termination
-------------------------
 During the program execution suppose if we are getting some interruption in the middle of the
program such type of termination is called abnormal termination.

ex:
class Test
{
public static void main(String[] args)
{
System.out.println(10/0); // R.E ArithmeticException:
}
}

 If any exception raised in our program we must and should handle that exception otherwise our
program will terminates abnormally.
 Here exception will display name of the exception, description the exception and line number of
the exception.

Exception
==========
1) Exception is a unwanted , unexpected event which disturbs normal flow of our program.
2) Exception always raised at runtime so they are also known as runtime events.
3) The main objective of exception handling is to provide graceful termination.
4) In java, exceptions are divided into two types.
1) Predefined exceptions
2) Userdefined exceptions

1) Predefined exceptions
-----------------------
 Built-In exceptions are called predefined exceptions.
 They are classified into two types.

Diagram: java36.1

i) Checked exceptions
---------------------
Exceptions which are checked by the compiler at the time of compilation are called checked exceptions.
ex:
IOException
InterruptedException
FileNotFoundException
ii) Unchecked exceptions
------------------------
Exceptions which are checked by the JVM at the time of runtime are called unchecked exceptions.
ex:
ArithmeticException
IllegalArgumentException
ClassCastException

If any checked exception raised in our program we must and should handle that exception by using try
and catch block.

try block
=========
 It is a block which contains risky code.
 It is associate with catch block.
 If any exception raised in try block then try block won't be executed.
 It is used to throw the exception to catch block.

catch block
===========
 It is a block which contains error handing code.
 It is always associate with try block.
 It is used to catch the exception which is thrown by try block.
 If there is no exception in try block then catch block won't be executed.
 A catch block will take exception name as a parameter and that name must match with exception
class name.
syntax:
------
try
{
-
- //risky code
-
}
catch(Exception e)
{
-
- //error handling code
-
}
ex:
---
class Test
{
public static void main(String[] args)
{
try
{
System.out.println("try-block");
}
catch (Exception e)
{
System.out.println("catch-block");
}
}
}
o/p:
try-block
ex:
---
class Test
{
public static void main(String[] args)
{
try
{
System.out.println(10/0);
}
catch (ArithmeticException ae)
{
System.out.println("catch-block");
}
}
}
o/p:
catch-block
ex
---
class Test
{
public static void main(String[] args)
{
try
{
System.out.println("stmt1");
System.out.println(10/0);
System.out.println("stmt2");
}
catch (ArithmeticException ae)
{
System.out.println("catch-block");
}
}
}
output:
stmt1
catch-block
A try with multiple catch blocks
================================
 A try block can have multiple catch blocks.
 If a try block contains multiple catch blocks then order of catch block is very important. It should
be from child to parent but not from parent to child.
ex:
class Test
{
public static void main(String[] args)
{
try
{
System.out.println(10/0);
}
catch (ArithmeticException ae)
{
System.out.println("from AE");
}
catch (RuntimeException re)
{
System.out.println("from RE");
}
catch (Exception e)
{
System.out.println("from E");
}
}
}
ex:
--
class Test
{
public static void main(String[] args)
{
try
{
int[] arr=null;
System.out.println(arr[0]);
}
catch (ArithmeticException ae)
{
System.out.println("from AE");
}
catch (RuntimeException re)
{
System.out.println("from RE");
}
catch (Exception e)
{
System.out.println("from E");
}
}
}
ex:
--
import java.io.File;
class Test
{
public static void main(String[] args)
{
try
{
File f=new File("C:\\abc.txt");
f.createNewFile();
}
catch (ArithmeticException ae)
{
System.out.println("from AE");
}
catch (RuntimeException re)
{
System.out.println("from RE");
}
catch (Exception e)
{
System.out.println("from E");
}
}
}
Various methods to display exception details
============================================
Throwable defines following three methods to display exception details.
1) printStackTrace()
-------------------
It will display name of the exception , description of the exception and line number of the exception.

2) toString()
-----------
It will display name of the exception and description of the exception.

3) getMessage()
------------
It will display description of the exception.
ex:
---
class Test
{
public static void main(String[] args)
{
try
{
System.out.println(10/0);
}
catch (ArithmeticException ae)
{
ae.printStackTrace();

System.out.println("-----------------");

System.out.println(ae.toString());

System.out.println("-----------------");

System.out.println(ae.getMessage());
}
}
}
Q) Can we handle multiple exceptions in a single catch block?

 Yes, we can handle multiple exceptions using single catch block.


ex:
class Test
{
public static void main(String[] args)
{
try
{
System.out.println(10/0);
}
catch (NullPointerException | ArithmeticException | IllegalArgumentException e)
{
e.printStackTrace();
}
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
try
{
int[] arr=null;
System.out.println(arr[0]);
}
catch (NullPointerException | ArithmeticException | IllegalArgumentException e)
{
e.printStackTrace();
}
}
}
ex
---
class Test
{
public static void main(String[] args)
{
try
{
Thread.currentThread().setPriority(11);
}
catch (NullPointerException | ArithmeticException | IllegalArgumentException e)
{
e.printStackTrace();
}
}
}
finally block
==============
 It is never recommanded to maintain cleanup code in try block because if any exception raised in
try block then try block won't be executed.
 It is never recommanded to maintain cleanup code in catch block because if there is no exception
in try block then catch block won't be executed.
 We need a place where we can maintain cleanup code and it should execute irrespective of
exception raised or not. Such block is called finally block.
 Finally block always associate with try and catch block.
syntax:
----
try
{
-
- // risky code
-
}
catch(Exception e)
{
-
- // error handling code
-
}
finally
{
-
- // cleanup code
-
}
ex:
---
class Test
{
public static void main(String[] args)
{
try
{
System.out.println("try-block");
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
System.out.println("finally-block");
}
}
}
o/p:
try-block
finally-block
ex:
---
class Test
{
public static void main(String[] args)
{
try
{
System.out.println(10/0);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
System.out.println("finally-block");
}
}
}
o/p:
java.lang.ArithmeticException: / by zero
at Test.main(Test.java:7)
finally-block
Ex:
---
class Test
{
public static void main(String[] args)
{
try
{
System.out.println("stmt1");
System.out.println(10/0);
System.out.println("stmt2");
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
System.out.println("finally-block");
}
}
}
output:
stmt1
java.lang.ArithmeticException: / by zero
at Test.main(Test.java:8)
finally-block

A try with finally combination is valid in java.


ex:
class Test
{
public static void main(String[] args)
{
try
{
System.out.println("try-block");
}
finally
{
System.out.println("finally-block");
}
}
}
ex:
---
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=null;
String name=null;
try
{
sc=new Scanner(System.in);

System.out.println("Enter the name :");


name=sc.next();

System.out.println("Welcome :"+name);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
sc.close();
}
}
}
Q) What is the difference between final, finally and finalize method?
final
----
 final is a modifier which is applicable for variables, methods and classes.
 If we declare any variable as final then reassignment of that variable is not possible.
 If we declare any method as final then overriding of that method is not possible.
 If we declare any class as final then creating child class is not possible.
finally
--------
 It is a block which contains cleanup code and it should execute irrespective of exception raised or
not.
finalize
---------
 It is a method called by garbage collector just before destroying an object for cleanup activity.

try with resources


===================
 A "try-with-resources" introduced in Java 7.
 A "try-with-resources" is a try statement that declares one or more resources.
 A resource is as an object that must be closed after finishing the program.
ex:
---
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
try(Scanner sc=new Scanner(System.in);)
{
System.out.println("Enter the name :");
String name=sc.next();
System.out.println("Welcome :"+name);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
throw statement
================
 Sometimes we will create exception object explicitly and handover to JVM manually by using
throw statement.
ex:
throw new ArithmeticException("Don't divide number by zero");

Diagram: java37.1

throws statement
================
 If any checked exception raised in our program we must and should handle that exception by
using try and catch block or by using throws statement.
ex:
---
class Test
{
public static void main(String[] args)
{
try
{
Thread.sleep(3000);
System.out.println("Welcome to Java");
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
}
}
ex:
---
class Test
{
public static void main(String[] args)throws InterruptedException
{
Thread.sleep(5000);
System.out.println("Welcome to Java");
}
}
Ex:
----
class Test
{
//static block
static
{
System.out.println("static-block");
}

//instance block
{
System.out.println("instance-block");
}

public static void main(String[] args)throws ClassNotFoundException


{
Class.forName("Test");
}
}
2) Userdefined exceptions
==========================
 Exceptions which are created by the user based on the application requirements are called
userdefined exceptions or customized exceptions.
ex:
NoInterestInJavaException
NoPracticeException
NoJobException
and etc.
ex:
---
import java.util.Scanner;

class NotEligibleException extends RuntimeException


{
NotEligibleException(String str)
{
super(str);
}
}
class EligibleException extends RuntimeException
{
EligibleException(String str)
{
super(str);
}
}
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the age :");
int age=sc.nextInt();
if(age<18)
throw new NotEligibleException("U r not eligible to vote");
else
throw new EligibleException("U r eligible to vote");
}
}
Garbage Collector
=================
 Garbage collector is a deamon thread which is used to destroy unused or useless objects in java.
 There are two ways to call garbage collector in java.
1) System.gc()
2) Runtime.getRuntime().gc()
ex:
---
class Test
{
//instance variable
int i=10;
public static void main(String[] args)
{
Test t=new Test();
System.out.println(t.i);

t=null;
System.gc();
}
public void finalize()
{
System.out.println("finalize-method");
}
}
ex:
---
class Test
{
//instance variable
int i=10;

public static void main(String[] args)


{
Test t=new Test();
System.out.println(t.i);

t=null;
Runtime.getRuntime().gc();
}
public void finalize()
{
System.out.println("finalize-method");
}
}
Singleton class
===============
 A class which allows us to create only one object is called singleton class.
 Singleton is a design pattern which allows us to create a single instance.
 To create a singleton class we required private constructor and static method.
ex:
class Singleton
{
static Singleton single=null;

//private constructor
private Singleton()
{
}

//static method
public static Singleton getInstance()
{
if(single==null)
{
single=new Singleton();
}
return single;
}
}
class Test
{
public static void main(String[] args)
{
Singleton s1=Singleton.getInstance();
System.out.println(s1.hashCode());

Singleton s2=Singleton.getInstance();
System.out.println(s2.hashCode());
}
}
Serialization vs Deserialization
================================
Serialization
-------------
 The process of storing/writing object data into a file is called serialization.
 In general, serialization is a process of converting object state to file state.
 To perform serialization we need to use FileOutputStream and ObjectOutputStream class.
Diagram: java38.1
Note:
-----
 We can perform serialization only for Serializable object.
 To create a Serializable object a class must implements java.io.Serializable interface.
ex:
import java.io.*;
class Person implements Serializable
{
private String name;
private int age;

public Person(String name,int age)


{
this.name=name;
this.age=age;
}
@Override
public String toString()
{
return "Person : [name:"+name+",age:"+age+"]";
}
}
class Test
{
public static void main(String[] args)
{
Person p=new Person("Alan",29);

//serialization

try(ObjectOutputStream ostream=new ObjectOutputStream(new


FileOutputStream("D:\\hemanth.txt"));)
{
ostream.writeObject(p);

System.out.println("Serialization Done");
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
Deserialization
-------------
 The process of taking the data from a file and representing an object is called Deserialization.
 In general, Deserialization is a process of converting file state to object state.
 To perform deserialization we need to use FileInputStream and ObjectInputStream class.
Diagram: java38.2

import java.io.*;
class Person implements Serializable
{
private String name;
private int age;

public Person(String name,int age)


{
this.name=name;
this.age=age;
}
@Override
public String toString()
{
return "Person : [name:"+name+",age:"+age+"]";
}
}
class Test
{
public static void main(String[] args)
{

//serialization
try(ObjectInputStream istream=new ObjectInputStream(new
FileInputStream("D:\\hemanth.txt"));)
{
Person p=(Person)istream.readObject();

System.out.println(p);
}
catch (ClassNotFoundException | IOException e)
{
e.printStackTrace();
}
}
}
java.io package
================
File
=======
File f=new File("abc.txt");

 File will check is there any abc.txt file already created or not.
 If it is available it simply refers to that file.If it is not created then it won't create any new file.
ex:
---
import java.io.*;
class Test
{
public static void main(String[] args)
{
File f=new File("abc.txt");
System.out.println(f.exists());//false
}
}
A File object can be used to create a physical file.
ex:
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
File f=new File("abc.txt");
System.out.println(f.exists());//false

f.createNewFile();
System.out.println(f.exists());//true

}
}
A File object can be used to create a directory also.
ex:
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
File f=new File("bhaskar123");
System.out.println(f.exists());//false

f.mkdir();
System.out.println(f.exists());//true
}
}
Q)Write a java program to Create a "cricket123" folder and inside that folder create "abc.txt"
file?
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
File f1=new File("cricket123");
f1.mkdir();

File f2=new File("cricket123","abc.txt");


f2.createNewFile();

System.out.println("Please check the location");

}
}
FileWriter
==========
FileWriter is used to write character oriented data into a file.

constructor
--------------
FileWriter fw=new FileWriter(String s);
FileWriter fw=new FileWriter(File f);

ex:
FileWriter fw=new FileWriter("aaa.txt");
or

File f=new File("aaa.txt");


FileWriter fw=new FileWriter(f);

If file does not exist then FileWriter will create a physical file.
Methods
-----------
1)write(int ch)
-----------------
> It will insert single character into a file.
2)write(char[] ch)
-----------------
>It will insert array of characters into a file.
3)write(String s)
-------------------
It will insert String into a file.
4)flush()
----------
It gives guaranttee that last character of a file is also inserted.
5)close()
-----------
It is used to close the FileWriter object.
ex:
-----
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
FileWriter fw=new FileWriter("aaa.txt");

fw.write(98);// b
fw.write("\n");

char[] ch={'a','b','c'};
fw.write(ch);
fw.write("\n");

fw.write("bhaskar\nsolution");
fw.flush();
fw.close();
System.out.println("Please check the location");
}
}
ex:
-----
import java.io.*;
class Test
{
public static void main(String[] args) {
FileWriter fw=null;
try
{
fw=new FileWriter("aaa.txt");
fw.write(98);// b
fw.write("\n");

char[] ch={'a','b','c'};
fw.write(ch);
fw.write("\n");

fw.write("bhaskar\nsolution");
fw.flush();
fw.close();
System.out.println("Please check the location");
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
ex:
-----
import java.io.*;
class Test
{
public static void main(String[] args) {

try(FileWriter fw=new FileWriter("aaa.txt");)


{

fw.write(98);// b
fw.write("\n");

char[] ch={'a','b','c'};
fw.write(ch);
fw.write("\n");

fw.write("bhaskar\nsolution");
fw.flush();
fw.close();
System.out.println("Please check the location");
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
FileReader
==================
 It is used to read character oriented data from a file.

constructor
--------------
FileReader fr=new FileReader(String s);
FileReader fr=new FileReader(File f);

ex:
FileReader fr=new FileReader("aaa.txt");
or
File f=new File("aaa.txt");
FileReader fr=new FileReader(f);

Methods
----------
1)read()
--------
 It will read next character from a file and return unicode value.
 If next character is not available then it will return -1.
2)read(char[] ch)
----------------
 It will read collection of characters from a file.
3)close()
---------
 It is used to close FileReader object.

ex:1
-------
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
FileReader fr=new FileReader("aaa.txt");

int i=fr.read();
while(i!=-1)
{
System.out.print((char)i);
i=fr.read();
}
fr.close();
}
}
ex:2
----------
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
FileReader fr=new FileReader("aaa.txt");

char[] carr=new char[255];

//load the data from file to char array


fr.read(carr);

//reading the data from char array


for(char c:carr)
{
System.out.print(c);
}

fr.close();

}
}
Usage of FileWriter and FileReader is not recommanded to use
==============================================================
 While inserting the data by using FileWriter ,we need to insert line seperator(\n) which is very
headache for the programmer.
 While reading the data by using FileReader object ,we need to read character by character which
is not convenient to the programmer.
 To overcome this limitation Sun micro system introduced BufferedWriter and BufferedReader.

BufferedWriter
=================
 It is used to insert character oriented data into a file.
constructor
-----------
BufferedWriter bw=new BufferedWriter(Writer w);
BufferedWriter bw=new BufferedWriter(Writer w,int buffersize);

BufferedWriter object does not communicate with files directly.


It will take the support of some writer objects.

ex:
FileWriter fw=new FileWriter("bbb.txt");
BufferedWriter bw=new BufferedWriter(fw);

or

BufferedWriter bw=new BufferedWriter(new FileWriter("bbb.txt"));

Methods
---------
1)write(int ch)
-----------------
It will insert single character into a file.
2)write(char[] ch)
-----------------
It will insert array of characters into a file.
3)write(String s)
-------------------
It will insert String into a file.
4)flush()
----------
It gives guaranttee that last character of a file is also inserted.
5)close()
-----------
It is used to close the BufferedWriter object.
6)newLine()
----------
It will insert new line into a file.
ex:
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{

BufferedWriter bw=new BufferedWriter(new FileWriter("bbb.txt"));


bw.write(98);//b
bw.newLine();

char[] ch={'a','b','c'};
bw.write(ch);
bw.newLine();

bw.write("bhaskar");
bw.newLine();

bw.flush();
bw.close();
System.out.println("Please check the location");
}
}
BufferedReader
=================
 It is enhanced reader to read character oriented data from a file.

constructor
------------
BufferedReader br=new BufferedReader(Reader r);
BufferedReader br=new BufferedReader(Reader r,int buffersize);

BufferedReader object can't communicate with files directly.IT will take support of some reader objects.
ex:
FileReader fr=new FileReader("bbb.txt");
BufferedReader br=new BufferedReader(fr);

or

BufferedReader br=new BufferedReader(new FileReader("bbb.txt"));

 The main advantage of BufferedReader over FileReader is we can read character line by line
instead of character by character.
methods
---------
1)read()
--------
It will read next character from a file and return unicode value.
If next character is not available then it will return -1.
2)read(char[] ch)
----------------
It will read collection of characters from a file.
3)close()
---------
It is used to close BufferedReader object.
4)nextLine()
------------
It is used to read next line from the file. If next line is
not available then it will return null.
ex:
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
BufferedReader br=new BufferedReader(new FileReader("bbb.txt"));

String line=br.readLine();
while(line!=null)
{
System.out.println(line);
line=br.readLine();
}

br.close();
}
}

PrintWriter
===============
 It is enhanced write to write character oriented data into a file.

constructor
-----------
PrintWriter pw=new PrintWriter(String s);
PrintWriter pw=new PrintWriter(File f);
PrintWriter pw=new PrintWriter(Writer w);

PrintWriter can communicate with files directly and it will take the support of some writer objects.

ex:
PrintWriter pw=new PrintWriter("ccc.txt");
or
PrintWriter pw=new PrintWriter(new File("ccc.txt"));
or
PrintWriter pw=new PrintWriter(new FileWriter("ccc.txt"));

 The main advantage of PrintWriter over FileWriter and BufferedWriter is we can insert any type
of data.
 Assume if we want insert primitive values then PrintWriter is best choice.
methods
------------
write(int ch)
write(char[] ch)
write(String s)
flush()
close()

writeln(int i)
writeln(float f)
writeln(double d)
writeln(String s)
writeln(char c)
writeln(boolean b)

write(int i)
write(float f)
write(double d)
write(String s)
write(char c)
write(boolean b)

ex:
------

import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
PrintWriter pw=new PrintWriter("ccc.txt");

pw.write(100);// d
pw.println(100);// 100
pw.print('a');
pw.println(true);
pw.println("hi");
pw.println(10.5d);

pw.flush();
pw.close();
System.out.println("Please check the location");
}
}
various ways to provide input values from the keyboard
======================================================
 There are various ways to provide input values from keyboard.
1)Command line argument
2)BufferedReader class
3)Console class
4)Scanner class

1)Command line argument


-------------------------
 In command line argument we need to pass our inputs at runtime.
ex:
class Test
{
public static void main(String[] args)
{
String name=args[0];
System.out.println("Welcome : "+name);
}
}
o/p:
javac Test.java
java Test Alan

2)BufferedReader class
--------------------------
 BufferedReader class present in java.io package.
 BufferedReader class will take InputStreamReader object as a parameter which is embedded with
System.in.
ex:
BufferedReader br=
new BufferedReader
(new InputStreamReader(System.in));

 To read input values from console we need to readLine() method.


ex:
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter the Name :");


String name=br.readLine();

System.out.println("Welcome : "+name);
}
}

3)Console class
================
 Console class present in java.io package.
 We can create Console class object by using console() method of System class.
ex:
Console c=System.console();
 To read inputs from console we need to use readLine() method.
ex:
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
Console c=System.console();

System.out.println("Enter the Name :");


String name=c.readLine();
System.out.println("Welcome : "+name);

}
}

4)Scanner class
==================
 Scanner class present java.util package.
 We can create Scanner object class as follow.
ex:
Scanner sc=new Scanner(System.in);

 We can read inputs from the console by using following methods.


ex:
next()
nextLine()
nextInt()
nextFloat()
nextDouble()
next().charAt(0);
and etc.
ex:
import java.util.*;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the No :");


int no=sc.nextInt();

System.out.println("Enter the Name :");


String name=sc.next();

System.out.println("Enter the Fee :");


double fee=sc.nextDouble();

System.out.println(no+" "+name+" "+fee);


}
}
Generics
=========
1) Generics refer to the ability to use a type as a parameter to methods and classes.
2) Every array consider as typesafe.
3) It means we can give guarantee that what type of elements are present in array.
4) If requirement is there to hold string values then it is recommanded to use String[] array.If we are
trying to insert any other element then we will get compile time error.

ex:
String[] sarr=new String[10];
sarr[0]="hi";
sarr[1]="bye";
sarr[2]=10; // invalid

>Collections are not consider as typesafe.


>It means we can't give guarantee that what type of elements are present in Collections.
>If requirement is there to hold string values then it is never recommanded to use ArrayList. If we are
trying to insert any other elements then our program may get failure at runtime.

ex:
ArrayList al=new ArrayList();
al.add("hi");
al.add("bye");
al.add(new Integer(10));
-
-
String val1=(String)al.get(0);
String val2=(String)al.get(1);
String val3=(String)al.get(2); // invalid

>At the time of retrieving the data from array we don't need to perform typecasting.
ex:
int[] arr=new int[10];
arr[0]=10;
arr[1]=20;
-
-
int val=arr[0];

>At the time of retrieving the data from Collection, compulsary we need to perform typecasting.
ex:
ArrayList al=new ArrayList();
al.add("Hi");
al.add("Bye");
-
-
String val=(String)al.get(0);
> To overcome this limitation Sun Micro System introduced Generics concept in 1.5v.
>The main objective of Generics are

1) To make Collections as typesafe.


2) To avoid typecasting problem.
java.util package
==================
Q) What is the difference between Arrays and Collections?
Arrays Collections
---------- --------------
It is a collection of homogeneous data It is a collection of homogeneous and hetrogeneous
elements. data elements.

Arrays are fixed in size. Collections are growable in nature.

Performance point of view arrays are Memory point of view Collections are recommanded
recommanded to use. to use.

It can hold primitive types and object types. It can hold only object types.

It is typesafe by default. It is not typesafe by default.

Arrays are not implemented based on data Collections are implemented based on data structure
structure concept.Hence we can't expect concept. Hence we can expect ready made methods.
any ready made methods.So for every logic
we need to write the code explicitly.

Collection Framework
====================
>The Java collections framework provides a set of interfaces and classes to implement various data
structures and algorithms for storing, managing, and manipulating groups of objects. It is part of the
java.util package and is essential for building robust and efficient Java applications.

Core Interfaces
---------------
 The framework is built around a set of core interfaces:
Collection:
------------
>Base interface for most of the framework.
>Sub-interfaces: List, Set, Queue.
List:
--------
>An ordered collection (sequence) that allows duplicate elements.
>Classes: ArrayList, LinkedList, Vector.
Set:
-----
>A collection that does not allow duplicate elements.
>Classes: HashSet, LinkedHashSet, TreeSet.
Queue:
-------
>Used for holding elements prior to processing (FIFO).
>Classes: PriorityQueue, LinkedList.
Map (Not a part of Collection):
-----------------------------------
>Represents a collection of key-value pairs.
>Classes: HashMap, TreeMap, LinkedHashMap.
Important Classes:
==================
ArrayList:
------------
>A resizable array implementation of List.
>Best for frequent read operations.
LinkedList:
----------------
>Implements both List and Deque interfaces.
>Best for frequent insertions and deletions.
HashSet:
----------
>Implements Set using a hash table.
>Offers constant-time performance for basic operations.
TreeSet:
-------------
>Implements Set and ensures elements are sorted.
>Based on a Red-Black tree.
HashMap:
-----------
>A hash table-based implementation of Map.
>Allows one null key and multiple null values.
TreeMap:
----------
>A Map that maintains key-value pairs in sorted order.

Collection
===========
>Collection is an interface which is present in java.util package.
>It is a root interface for entire Collection Framework.
>If we want to represent group of individual objects in a single entity then we need to use Collection.
>Collection interface contains some common methods which are available for entire Collection objects.

ex:
cmd> javap java.util.Collection
ex:
public abstract int size();
public abstract boolean isEmpty();
public abstract boolean contains(java.lang.Object);
public abstract java.util.Iterator<E> iterator();
public abstract java.lang.Object[] toArray();
public abstract <T> T[] toArray(T[]);
public default <T> T[] toArray(java.util.function.IntFunction<T[]>);
public abstract boolean add(E);
public abstract boolean remove(java.lang.Object);
public abstract boolean containsAll(java.util.Collection<?>);
public abstract boolean addAll(java.util.Collection<? extends E>);
public abstract boolean removeAll(java.util.Collection<?>);
public default boolean removeIf(java.util.function.Predicate<? super E>);
public abstract boolean retainAll(java.util.Collection<?>);
public abstract void clear();
public abstract boolean equals(java.lang.Object);
public abstract int hashCode();
public default java.util.Spliterator<E> spliterator();
public default java.util.stream.Stream<E> stream();
public default java.util.stream.Stream<E> parallelStream();

List
=====
>It is a child interface of Collection of interface.
> It allows duplicate elements and maintains the order in which elements are inserted.

Diagram: java39.1

ArrayList
-------------
>ArrayList is a class in Java's Collections Framework that provides a dynamic array for storing elements.
>Duplicate objects are allowed.
>Insertion order is preserved.
>Hetrogeneous objects are allowed.
>Null insertion is possible.
>It implements Serializable, Cloneable and RandomAccess interface.

ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("one");
al.add("two");
al.add("three");
System.out.println(al);//[one,two,three]

al.add("one");
System.out.println(al); //[one,two,three,one]

al.add(10);
System.out.println(al); //[one,two,three,one,10]
al.add(null);
System.out.println(al); // [one,two,three,one,10,null]
}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList<String> al=new ArrayList<String>();
al.add("one");
al.add("two");
al.add("three");
System.out.println(al);//[one,two,three]

al.add("one");
System.out.println(al); //[one,two,three,one]

al.add(null);
System.out.println(al); // [one,two,three,one,null]
}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList<String> al=new ArrayList<String>();
al.add("one");
al.add("two");
al.add("three");
System.out.println(al);//[one,two,three]

al.add(1,"raja");
System.out.println(al);//[one,raja,two,three]

System.out.println(al.isEmpty());//false

System.out.println(al.contains("two")); // true

al.remove("raja");
System.out.println(al);//[one,two,three]

al.clear();
System.out.println(al);//[]
}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
List<String> list=new ArrayList();
list.add("one");
list.add("two");
list.add("three");
System.out.println(list);//[one,two,three]

for(int i=0;i<list.size();i++)
{
String s=list.get(i);
System.out.println(s);
}
}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(4,8,1,3,9,6);
System.out.println(list);
}
}
Ex:
-----
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList<String> javaCourse=new ArrayList<String>();
javaCourse.add("html");
javaCourse.add("java");
javaCourse.add("css");
javaCourse.add("oracle");
javaCourse.add("springboot");
System.out.println(javaCourse);

ArrayList<String> pythonCourse=new ArrayList<String>();


pythonCourse.add("html");
pythonCourse.add("python");
pythonCourse.add("css");
pythonCourse.add("oracle");
pythonCourse.add("django");
System.out.println(pythonCourse);

javaCourse.retainAll(pythonCourse);

System.out.println(javaCourse);

}
}

>LinkedList is a class in Java's Collections Framework that implements the List, Deque, and Queue
interfaces.
>It provides a doubly-linked list data structure, making it efficient for certain operations like insertion and
deletion compared to ArrayList.
>Duplicate objects are allowed.
>Insertion order is preserved.
>Hetrogeneous objects are allowed.
>Null insertion is possible
>It implements Serializable, Cloneable and Deque interface.
>A LinkedList contains following methods.

ex:
public E getFirst();
public E getLast();
public E removeFirst();
public E removeLast();
public void addFirst(E);
public void addLast(E);

ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
LinkedList ll=new LinkedList();
ll.add("one");
ll.add("two");
ll.add("three");
System.out.println(ll); //[one,two,three]

ll.add("one");
System.out.println(ll);//[one,two,three,one]

ll.add(10);
System.out.println(ll);//[one,two,three,one,10]

ll.add(null);
System.out.println(ll);//[one,two,three,one,10,null]
}
}

ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
LinkedList<String> ll=new LinkedList<String>();
ll.add("one");
ll.add("two");
ll.add("three");
System.out.println(ll); //[one,two,three]

ll.addFirst("gogo");
ll.addLast("jojo");
System.out.println(ll);//[gogo,one,two,three,jojo]

System.out.println(ll.getFirst()); //gogo
System.out.println(ll.getLast()); //jojo

ll.removeFirst();
ll.removeLast();

System.out.println(ll); //[one,two,three]

}
}

ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
LinkedList<String> ll1=new LinkedList<String>();
ll1.add("one");
ll1.add("two");
ll1.add("three");
System.out.println(ll1); //[one,two,three]

LinkedList<String> ll2=new LinkedList<String>();


ll2.add("raja");
System.out.println(ll2);//[raja]

ll2.addAll(ll1);
System.out.println(ll2);//[raja,one,two,three]
System.out.println(ll2.containsAll(ll1)); // true

ll2.removeAll(ll1);
System.out.println(ll2); //[raja]
}
}
Q) What is the difference between ArrayList and LinkedList ?
ArrayList LinkedList
------------ ---------------
ArrayList internally uses a dynamic array to LinkedList internally uses a doubly linked list
store the elements. to store the elements.

ArrayList is better for storing and accessing LinkedList is better for manipulating data.
data.

The memory location for the elements of The location for the elements of a linked list
an ArrayList is contiguous. is not contagious.

When an ArrayList is initialized, a default There is no case of default capacity in a


capacity of 10 is assigned to the ArrayList. LinkedList

Vector
=======
>The underlying data structure is resizable array or growable array.
>Duplicate objects are allowed.
>Insertion order is preserved.
>Hetrogeneous objects are allowed.
>Null insertion is possible.
>It implements Serializable, Cloneable and RandomAccess interface.
>In Vector, all methods are synchronized.
>Vector class contains following methods.
ex:
public synchronized void addElement(E);
public synchronized void removeElementAt(int);
public synchronized E firstElement();
public synchronized E lastElement();
public synchronized void removeAllElements();
public synchronized void insertElementAt(E, int);
and etc.
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
Vector<Integer> v=new Vector<Integer>();
System.out.println(v.capacity());
for(int i=1;i<=10;i++)
{
v.addElement(i);
}
System.out.println(v);//[1,2,3,4,5,6,7,8,9,10]
System.out.println(v.firstElement());//1
System.out.println(v.lastElement());//10

v.removeElementAt(5);
System.out.println(v);//[1,2,3,4,5,7,8,9,10]

v.insertElementAt(6,5);
System.out.println(v);//[1,2,3,4,5,6,7,8,9,10]

v.removeAllElements();
System.out.println(v); //[]
}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
Vector<Integer> v=new Vector<Integer>();
System.out.println(v.capacity());
for(int i=1;i<=10;i++)
{
v.add(i);
}
System.out.println(v);//[1,2,3,4,5,6,7,8,9,10]
System.out.println(v.get(0));//1
System.out.println(v.get(v.size()-1));//10

v.remove(5);
System.out.println(v);//[1,2,3,4,5,7,8,9,10]

v.add(5,6);
System.out.println(v);//[1,2,3,4,5,6,7,8,9,10]

v.clear();
System.out.println(v); //[]
}
}
Q) What is the difference between ArrayList and Vector?
ArrayList Vector
----------- ------------
Methods are not synchronized. Methods are synchronized.

At a time multiple threads are allowed to At a time only one thread is allowed to operate
operate on ArrayList object.Hence ArrayList on Vector object.Hence Vector is thread safe.
is not thread safe.

Relatively performance is high because there Relatively performance is low because there is a
is no waiting threads. waiting threads.

It is a non-legacy class. It is a legacy class.

It is introduced in 1.2v. It is introduced in 1.0v.

Stack
=====
>It is a child class of Vector class.
>If we depends upon Last In First Out order(LIFO) then we need to use Stack.

constructor
-----------

Stack s=new Stack();


Methods
-------
1) push(Object o):- It is used to push the element to the stack.
2) pop() :- It is used to pop the element from stack.
3) peek() :- It returns toppest element of a stack.
4) isEmpty() :- It is used to check stack is empty or not.
5) search(E) :- It returns offset value if element is found otherwise it will return -1.

ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
Stack<String> s=new Stack<String>();
s.push("A");
s.push("B");
s.push("C");
System.out.println(s);//[A,B,C]

s.pop();
System.out.println(s);//[A,B]
System.out.println(s.peek());//B
System.out.println(s.isEmpty());//false
System.out.println(s.search("Z")); // -1
System.out.println(s.search("A")); // 2
}
}
Q) Write a java program to check given string is balanced or not?
input: {[()]}
Output: It is a balanced string

ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
String str="{[()]}";
if(isBalanced(str.toCharArray()))
System.out.println("It is a balanced string");
else
System.out.println("It is not a balanced string");
}
public static boolean isBalanced(char[] carr)
{
Stack<Character> stack=new Stack<Character>();

for(char ch:carr)
{
if(ch=='{'|| ch=='[' || ch=='(')
{
stack.push(ch);
}
else if(ch==')' && !stack.isEmpty() && stack.peek()=='(')
{
stack.pop();
}
else if(ch==']' && !stack.isEmpty() && stack.peek()=='[')
{
stack.pop();
}
else if(ch=='}' && !stack.isEmpty() && stack.peek()=='{')
{
stack.pop();
}
else
{
return false;
}

}
return stack.isEmpty();
}
}
Set
====
1)It is a child interface of Collection interface.
2)If we want to represent group of individual objects in a single entity where duplicates are not allowed
and order is not preserved then we need to use Set interface.

Diagram: java40.1

HashSet
=======
1)The underlying data structure is Hashtable.
2)Duplicate objects are not allowed.
3)Insertion order is not preserved because it takes hash code of an object.
4)Hetrogeneous objects are allowed.
5)Null insertion is possible.
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
HashSet hs=new HashSet();
hs.add("six");
hs.add("nine");
hs.add("three");
hs.add("one");
System.out.println(hs);//[nine, six, one, three]

hs.add("six");
System.out.println(hs);//[nine, six, one, three]

hs.add(10);
System.out.println(hs);//[nine, six, one, 10, three]

hs.add(null);
System.out.println(hs);//[null, nine, six, one, 10, three]
}
}
linkedHashSet
==============
1)It is a child class of HashSet class.
2)LinkedHashSet is exactly same as HashSet class with following differences.

HashSet LinkedHashSet
----------------- --------------
1)The underlying data structure is Hashtable. 1)The underlying data structure is Hashtable and
LinkedList.
2)Insertion order is not preserved. 2)Insertion order is preserved.
3)It is introduced in 1.2v. 3)It is introduced in 1.4v.
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
LinkedHashSet lhs=new LinkedHashSet();
lhs.add("six");
lhs.add("nine");
lhs.add("three");
lhs.add("one");
System.out.println(lhs);//[six,nine,three,one]

lhs.add("six");
System.out.println(lhs);//[six,nine,three,one]

lhs.add(10);
System.out.println(lhs);//[six,nine,three,one,10]

lhs.add(null);
System.out.println(lhs);//[six,nine,three,one,10,null]
}
}
TreeSet
========
1)The underlying data structure is Balanced Tree.
2)Duplicate objects are not allowed.
3)Insertion order is not preserved because it takes sorting order.
4)Hetrogeneous objects are not allowed.
5)If we insert hetrogeneos object then we will get ClassCastException.
5)Null insertion is not possible.
6)If we insert null then we will get NullPointerException.

ex:
---

import java.util.*;
class Test
{
public static void main(String[] args)
{
TreeSet ts=new TreeSet();
ts.add(10);
ts.add(1);
ts.add(5);
ts.add(3);
System.out.println(ts);//[1,3,5,10]

ts.add(1);
System.out.println(ts);//[1,3,5,10]

//ts.add("hi");
//System.out.println(ts);// R.E ClassCastException

//ts.add(null);
//System.out.println(ts);// R.E NullPointerException
}
}

Q) What is the difference between Comparable and Comparator interface?


Comparable
----------
>Comparable is an interface which is present in java.lang package.
>Comparable interface contains only one method i.e compareTo() method.
>If we depends upon default natural sorting order then we need to use Comparable interface.

ex:
obj1.compareTo(obj2)

It returns -ve if obj1 comes before obj2.


It returns +ve if obj1 comes after obj2.
It returns 0 if both objects are same.
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("A".compareTo("Z")); // -25
System.out.println("Z".compareTo("A")); // +25
System.out.println("K".compareTo("K")); // 0
}
}
Comparator
-----------
>Comparator is an interface which is present in java.util package.
>Comparator interface contains following two methods i.e compare() method and equals() method.
>If we depends upon customized sorting order then we need to use Comparator interface.
ex:
public int compare(Object obj1,Object obj2)
It returns +ve if obj1 comes before obj2.
It returns -ve if obj1 comes after obj2.
It returns 0 if both objects are same.

>Implementation of compare() method is mandatory.


>But implementation of equals() method is optional because it is present in Object class which is
available to the class through inheritance.
ex:
import java.util.*;
class Test
{
public static void main(String[] args)
{
TreeSet<Integer> ts=new TreeSet<Integer>(new MyComparator());
ts.add(10);
ts.add(1);
ts.add(5);
ts.add(3);
System.out.println(ts);//[10, 5, 3, 1]

}
}
class MyComparator implements Comparator
{
public int compare(Object obj1,Object obj2)
{
Integer i1=(Integer)obj1;
Integer i2=(Integer)obj2;
if(i1<i2)
return 1;
else if(i1>i2)
return -1;
else
return 0;
}
}

ex:
--
import java.util.*;
class Test
{
public static void main(String[] args)
{
TreeSet<Integer> ts=new TreeSet<Integer>(new MyComparator());
ts.add(10);
ts.add(1);
ts.add(5);
ts.add(3);
System.out.println(ts);//[1, 3, 5, 10]
}
}
class MyComparator implements Comparator
{
public int compare(Object obj1,Object obj2)
{
Integer i1=(Integer)obj1;
Integer i2=(Integer)obj2;
if(i1<i2)
return -1;
else if(i1>i2)
return 1;
else
return 0;
}
}
Q) Write a java program to compare two dates?
import java.time.*;
class Test
{
public static void main(String[] args)
{
LocalDate date1=LocalDate.of(2024,12,13);
LocalDate date2=LocalDate.now();

if(date1.compareTo(date2)>0)
System.out.println("Date1 is greatest");
else if(date1.compareTo(date2)<0)
System.out.println("Date2 is greatest");
else
System.out.println("Both are same");
}
}
Q) Write a java program to display distinct elements from given array?
Input: 1 2 2 3 3 3 4 4 4 4
Output: 1 2 3 4
ex:
------
import java.util.*;
class Test
{
public static void main(String[] args)
{
int[] arr={1,2,2,3,3,3,4,4,4,4};
Set<Integer> set=new LinkedHashSet<Integer>();
for(int i:arr)
{
set.add(i);
}
//for each loop
for(int i:set)
{
System.out.print(i+" ");
}

}
}
Map
=====
>In Java, a Map is a part of the java.util package and represents a collection of key-value pairs.
>Keys must be unique, but values can be duplicated.
>Each key and value pair is called one-entry.
>Diagram: java41.1

HashMap
---------
>Implements the Map interface using a hash table.
>Duplicate keys are not allowed but values can be duplicate.
>Insertion order is not preserved because it takes hash code of the key.
>Hetrogeneous objects are allowed for both key and value.
>Null insertion is possible for both key and values.
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
HashMap hm=new HashMap();
hm.put("one","raja");
hm.put("six","alan");
hm.put("nine","kelvin");
hm.put("five","brook");
System.out.println(hm);//{nine=kelvin, six=alan, one=raja, five=brook}

hm.put("one","gogo");
System.out.println(hm);//{nine=kelvin, six=alan, one=gogo, five=brook}

hm.put(1,100);
System.out.println(hm);//{nine=kelvin, 1=100, six=alan, one=gogo, five=brook}

hm.put(null,null);
System.out.println(hm);//{null=null, nine=kelvin, 1=100, six=alan, one=gogo,
five=brook}
}
}
ex:
--
import java.util.*;
class Test
{
public static void main(String[] args)
{
HashMap<String,String> hm=new HashMap<String,String>();
hm.put("one","raja");
hm.put("six","alan");
hm.put("nine","kelvin");
hm.put("five","brook");

Set s=hm.keySet();
System.out.println(s);//[nine, six, one, five]

Collection c = hm.values();
System.out.println(c);//[kelvin, alan, raja, brook]

Set s1=hm.entrySet();
System.out.println(s1); //[nine=kelvin, six=alan, one=raja, five=brook]
}
}
LinkedHashMap
-------------
>It is a child class of HashMap class.
>LinkedHashMap is exactly same as HashMap class with following differences.

HashMap LinkedHashMap
----------- -------------
>The underlying data structure is Hashtable. >The underlying data structure is Hashtable and
LinkedList.
>Insertion order is not preserved. >Insertion order is preserved.
>It is introduced in 1.2v. >It is introduced in 1.4v.
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
LinkedHashMap lhm=new LinkedHashMap();
lhm.put("one","raja");
lhm.put("six","alan");
lhm.put("nine","kelvin");
lhm.put("five","brook");
System.out.println(lhm);//{one=raja, six=alan, nine=kelvin, five=brook}
lhm.put("one","gogo");
System.out.println(lhm);//{one=gogo, six=alan, nine=kelvin, five=brook}

lhm.put(1,100);
System.out.println(lhm);//{one=gogo, six=alan, nine=kelvin, five=brook, 1=100}

lhm.put(null,null);
System.out.println(lhm);//{one=gogo, six=alan, nine=kelvin, five=brook, 1=100,
null=null}
}
}
ex:
--
import java.util.*;
class Test
{
public static void main(String[] args)
{
Map<String,String> map=new LinkedHashMap<String,String>();
map.put("one","raja");
map.put("six","alan");
map.put("nine","kelvin");
map.put("five","brook");

for(Map.Entry<String,String> entry: map.entrySet())


{
System.out.println(entry.getKey()+"="+entry.getValue());
}

}
}
Q) Write a java program to display occurance of a given string?
Input: this is is java java class
Output: this=1 is=2 java=2 class=1

ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
String str="this is is java java class";

String[] sarr=str.split(" ");

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

for(String s:sarr)
{
if(map.get(s)!=null)
{
map.put(s,map.get(s)+1);
}
else
{
map.put(s,1);
}
}

System.out.println(map);
}
}
Q) Write a java program to display occurance of characters in a given string?
Input: java
Output: j=1 a=2 v=1
ex:
import java.util.*;
class Test
{
public static void main(String[] args)
{
String str="java";

char[] carr=str.toCharArray();

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

for(char c:carr)
{
if(map.get(c)!=null)
{
map.put(c,map.get(c)+1);
}
else
{
map.put(c,1);
}
}

System.out.println(map);
}
}
Q) Write a java program to display lucky number from given array?
Input: 2 6 6 7 7 7 3 3 4 4 4 4
Output: 4

Input: 1 2 2 3 3 3 4 4 4 4
Output: 4

ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
int[] arr={1,2,2,3,3,3,4,4,4,4};

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

for(int i:arr)
{
if(map.containsKey(i)!=false)
{
map.put(i,map.get(i)+1);
}
else
{
map.put(i,1);
}
}

int x=0;
int max=-1;

for(Map.Entry<Integer,Integer> entry:map.entrySet())
{
if(entry.getKey() == entry.getValue())
{
x = entry.getKey();

max = Math.max(max,x);
}
}

System.out.println(max);
}
}
TreeMap
==========
>The underlying data structure is RED BLACK TREE.
>Duplicate keys are not allowed but values can be duplicate.
>Insertion order is not preserved because it takes sorting order of the key.
>If we depend upon default natural sorting order then keys can be homogeneous and comparable.
>If we depend upon customized sorting order then keys can be hetrogeneous and non-comparable.
>Key can't be null but value can be null.
ex:
--
import java.util.*;
class Test
{
public static void main(String[] args)
{
TreeMap<Integer,String> tm=new TreeMap<Integer,String>();
tm.put(1,"one");
tm.put(10,"ten");
tm.put(5,"five");
System.out.println(tm);//{1=one, 5=five, 10=ten}

tm.put(1,"gogo");
System.out.println(tm);//{1=gogo, 5=five, 10=ten}

tm.put(4,null);
System.out.println(tm);//{1=gogo, 4=null, 5=five, 10=ten}

tm.put(null,"four");
System.out.println(tm);// R.E NullPointerException
}
}
Hashtable
===========
>The underlying data structure is Hashtable.
>Duplicate keys are not allowed but values can be duplicate.
>Insertion order is not preserved because it takes descending order of the key.
>Both key and value can be hetrogeneous.
>Both key and value can't be null.
ex:
---

import java.util.*;
class Test
{
public static void main(String[] args)
{
Hashtable<Integer,String> ht=new Hashtable<Integer,String>();
ht.put(1,"one");
ht.put(10,"ten");
ht.put(5,"five");
System.out.println(ht);//{10=ten, 5=five, 1=one}

ht.put(1,"gogo");
System.out.println(ht);//{10=ten, 5=five, 1=gogo}

//ht.put(4,null);
//System.out.println(ht);//R.E NullPointerException

//ht.put(null,"four");
//System.out.println(ht);// R.E NullPointerException

}
}
Q) Types of data structures in java?
Diagram: java42.1

Types of cursors in java


=========================
 Cursor is used to retrieve the objects one by one from Collections.
 We have three types of cursors.
1) Enumeration
2) Iterator
3) ListIterator
1) Enumeration
---------------
 Enumeration is used to retrieve the objects one by one from legacy Collection objects.
 We can create Enumeration object as follow.
ex:
Enumeration e=v.elements();
 Enumeration interface contains following two methods.
ex:
public boolean hasMoreElements()
public Object nextElement()
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
Vector v=new Vector();
for(int i=1;i<=10;i++)
{
v.add(i);
}

Enumeration e=v.elements();
while(e.hasMoreElements())
{
Integer i =(Integer)e.nextElement();
System.out.println(i);
}
}
}
Limitations:
> Enumreation is used read objects only from legacy Collection objects.Hence it is not a universal cursor.
> Using Enumeration we can perform read operation but not remove operation.
> To overcome this limitations, Sun Micro System introduced Iterator.

2) Iterator
--------------
 It is used to read the objects one by one from any Collection object.Hence it is a universal cursor.
 Using Iterator we can perform read and remove operations.
We can create Iterator object as follow.
ex:
Iterator itr=al.iterator();

 Iterator interface contains following three methods.


ex:
public boolean hasNext()
public Object next()
public void remove()
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
for(int i=1;i<=10;i++)
{
al.add(i);
}

Iterator itr=al.iterator();
while(itr.hasNext())
{
Integer i=(Integer)itr.next();
if(i%2==0)
System.out.println(i);
else
itr.remove();
}

System.out.println(al);//[2,4,6,8,10]
}
}
Limitations:
-----------------
> Using Enumeration and Iterator we can read objects only in forward direction but not in backward
direction.Hence they are not bi-directional cursors.
> Using Iterator we can perform read and remove operation but not adding and replacement of new
objects.
> To overcome this above limitations , Sun Micro System introduced ListIterator.
3) ListIterator
--------------
 It is a child interface of Iterator interface.
 ListIterator is used to read objects one by one from List Collection objects only.
 Using ListIterator we can perform read, remove, adding and replacement of new objects.
 We can create ListIterator object as follow.
ex:
ListIterator litr=al.listIterator();

 ListIterator interface contains following nine methods.


ex:
public boolean hasNext()
public Object next()
public boolean hasPrevious()
public Object previous()
public void nextIndex()
public void previousIndex()
public void remove()
public void set(Object o)
public void add(Object o)
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("venki");
al.add("chiru");
al.add("bala");
al.add("nag");

ListIterator litr=al.listIterator();
while(litr.hasNext())
{
String s = (String) litr.next();
System.out.println(s);
}

}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("venki");
al.add("chiru");
al.add("bala");
al.add("nag");

ListIterator litr=al.listIterator();
while(litr.hasNext())
{
String s = (String) litr.next();

if(s.equals("bala"))
{
litr.remove();
}
}

System.out.println(al);//[venki,chiru,nag]

}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("venki");
al.add("chiru");
al.add("bala");
al.add("nag");

ListIterator litr=al.listIterator();
while(litr.hasNext())
{
String s = (String) litr.next();

if(s.equals("chiru"))
{
litr.add("pawan");
}
}

System.out.println(al);//[venki,chiru,pawan, bala,nag]

}
}

ex
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("venki");
al.add("chiru");
al.add("bala");
al.add("nag");

ListIterator litr=al.listIterator();
while(litr.hasNext())
{
String s = (String) litr.next();

if(s.equals("bala"))
{
litr.set("ntr");
}
}

System.out.println(al);//[venki,chiru,ntr,nag]

}
}

Requirement
===========
import java.util.*;
interface IEmployee
{
public void addEmployee();
public List<Employee> getAllEmployees();
}

class Employee
{
private int empId;
private String empName;
private double empSal;

//parameterized constructor
Employee(int empId,String empName,double empSal)
{
this.empId=empId;
this.empName=empName;
this.empSal=empSal;
}
public int getEmpId()
{
return empId;
}
public String getEmpName()
{
return empName;
}
public double getEmpSal()
{
return empSal;
}
}
class EmployeeImpl implements IEmployee
{
List<Employee> list=new ArrayList<Employee>();

public void addEmployee()


{
list.add(new Employee(101,"Alan",1000d));
list.add(new Employee(102,"Jose",2000d));
list.add(new Employee(103,"Mark",3000d));
list.add(new Employee(104,"Lisa",4000d));
}

public List<Employee> getAllEmployees()


{
return list;
}
}

class Test
{
public static void main(String[] args)
{
IEmployee e=new EmployeeImpl();

e.addEmployee();

List<Employee> list=e.getAllEmployees();

Iterator itr=list.iterator();
while(itr.hasNext())
{
Employee e1=(Employee)itr.next();
System.out.println(e1.getEmpId()+" "+e1.getEmpName()+" "+e1.getEmpSal());
}

}
}

Interview Question
==================
Q) Write a java program to display the output in a given format?
Input: abc.txt
Output: txt

ex:
--
class Test
{
public static void main(String[] args)
{
String fileName="abc.txt";

int index=fileName.lastIndexOf('.');

System.out.println(fileName.substring(index+1));
}
}

Multithreading
==============
Q) What is the difference between Thread and Process?
Thread
-------
A thread is a light weight sub process.
We can run multiple threads concurently.
One thread can communicate with another thread.
ex:
A class is one thread
A block is one thread
A constructor is one thread
Process
-------
A process is a collection of threads.
We can run multiple processes concurently.
One process can't communication with another process.
ex:
Typing the notes in editor is one process
Taking a class using zoom meeting is one process
Download a file from internet is one process

Q) What is multitasking?
> Executing several task simultenously such concept is called multitasking.
> We have two types of multitasking.

1) Thread based multitasking


--------------------------
 Executing several task simultenously where each task is a same part of a program such type of
multitasking is called thread based multitasking.
 It is best suitable for programmatic level.
2) Process based multitasking
-------------------------------
 Executing several task simultenously where each task is a independent process such type of
multitasking is called process based multitasking.
 It is best suitable for OS level.

Q) What is multithreading?

 Executing several threads simultenously such concept is called multithreading.


 In multithreading only 10% of work should be done by a programmer and 90% of work will be
done by a JAVA API.
 The main important application area of multithreading are
1) To implements multimedia graphics.
2) To develop video games.
3) To develop animations.
Ways to start a thread in java
==============================
There are two ways to start a thread in java.
1) By extending Thread class
2) By implementing Runnable interface

1) By extending Thread class


----------------------------
class MyThread extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("Child-Thread");
}
}
}
class Test
{
public static void main(String[] args)
{
//instantitate a thread
MyThread t=new MyThread();

//start a thread
t.start();

for(int i=1;i<=5;i++)
{
System.out.println("Parent-Thread");
}
}
}
case1: Thread Schedular
------------------------
 If multiple threads are waiting for execution which thread has to be execute will decided by the
thread schedular.
 What algorithm, behaviour or mechanism used by thread schedular is depends upon JVM vendor.
 Hence we can't expect any execution order or exact output in multithreading.

case2: Difference between t.start() and t.run() method


-------------------------------------------------------
If we invoke t.start() method, a new thread will be created which is responsible to execute run() method
automatically.
ex:

class MyThread extends Thread


{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("Child-Thread");
}
}
}
class Test
{
public static void main(String[] args)
{
//instantitate a thread
MyThread t=new MyThread();

//start a thread
t.start();

for(int i=1;i<=5;i++)
{
System.out.println("Parent-Thread");
}
}
}
If we invoke t.run() method, no new thread will be created but run() method will execute just like normal
method.
ex:
--
class MyThread extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("Child-Thread");
}
}
}
class Test
{
public static void main(String[] args)
{
//instantitate a thread
MyThread t=new MyThread();

// no new thread
t.run();

for(int i=1;i<=5;i++)
{
System.out.println("Parent-Thread");
}
}
}
case3: If we won't override run() method
------------------------------------------
 If we won't override run() method then Thread class run() method will execute automatically.
 Thread class run() method is a empty implementation.Hence we won't get any output from child
thread.
ex:
---
class MyThread extends Thread
{

}
class Test
{
public static void main(String[] args)
{
//instantitate a thread
MyThread t=new MyThread();

//start a thread
t.start();

for(int i=1;i<=5;i++)
{
System.out.println("Parent-Thread");
}
}
}
case4: If we overload run() method
-------------------------------------
If we overload run() method then Thread class start() method always execute run() method with zero
parameter only.
ex:
--
class MyThread extends Thread
{
public void run()
{
System.out.println("0-arg method");
}
public void run(int i)
{
System.out.println("int-arg method");
}
}
class Test
{
public static void main(String[] args)
{
//instantitate a thread
MyThread t=new MyThread();

//start a thread
t.start();

for(int i=1;i<=5;i++)
{
System.out.println("Parent-Thread");
}
}
}
case5: Life cycle of a thread
-----------------------------
Diagram: java42.2

 Once if we create a thread then our thread will be in new or born state.
 Once if we call t.start() method then our thread enters to ready or runnable state.
 If thread schedular allocates to CPU then our thread goes to running state.
 Once the run() method execution is completed then our thread enters to dead state.

2) By implementing Runnable interface


======================================
class MyRunnable implements Runnable
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("Child-Thread");
}
}
}
class Test
{
public static void main(String[] args)
{
MyRunnable r=new MyRunnable();

Thread t=new Thread(r); // r is a targatable interface

t.start();

for(int i=1;i<=5;i++)
{
System.out.println("Parent-Thread");
}
}
}

Daemon Thread
===============
 In Java, a daemon thread is a low-priority thread that runs in the background to perform some
task such as garbage collection , monitoring and etc.
 Daemon thread is also known as service provider thread which provides services to user threads.
 A life of daemon thread is depends upon user threads. It means when user threads died then
daemon thread die automatically.
 There are many daemon threads are running internally.
ex:
Garbage Collector
ActionListener
Finalizer
Signal dispatches
and etc.
ex:
---
class MyThread extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println(Thread.currentThread().isDaemon());
System.out.println("Child-Thread");
}
}
}
class Test
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.setDaemon(true);
t.start();
for(int i=1;i<=5;i++)
{
System.out.println("Parent-Thread");
}
}
}
Setting and Getting Name a thread
=================================
 In java, every thread has a name implicitly provided by the JVM or explicitly provided by the
programmer.
 We have following methods to set and get thread names.
 ex:
public final void setName(String name)
public final string getName()
ex:
---
class MyThread extends Thread
{

}
class Test
{
public static void main(String[] args)
{
System.out.println(Thread.currentThread().getName()); // main

MyThread t=new MyThread();


System.out.println(t.getName());// Thread-0

Thread.currentThread().setName("Parent-Thread");
System.out.println(Thread.currentThread().getName()); //Parent-Thread

t.setName("Child-Thread");
System.out.println(t.getName());//Child-Thread
}
}

Thread priority
===============
 In java, every thread has a priority implicitly provided by the JVM or explicitly provided by the
programmer.
 The valid range of thread priority is 1 to 10. Where 1 is a least priority and 10 is a highest
priority.
 If we take more then 10 priority then we will get IllegalArgumentException.
 A Thread class defines following standard constants as thread priorities.
ex:
Thread.MAX_PRIORITY - 10
Thread.NORM_PRIORITY - 5
Thread.MIN_PRIORITY - 1

 We don't have such constants like LOW_PRIORITY and HIGH_PRIORITY.


 A thread schedular uses thread priority while allocating to CPU.
 A thread which is having highest priority will be executed first.
 If multiple threads having same priority then we can't expect any execution order.
 We have following methods to set and get thread priorities.
ex:
public final void setPriority(int priority)
public final int getPriority()
ex
---
class MyThread extends Thread
{

}
class Test
{
public static void main(String[] args)
{
System.out.println(Thread.currentThread().getPriority());//5

MyThread t=new MyThread();


System.out.println(t.getPriority());// 5

Thread.currentThread().setPriority(9);
System.out.println(Thread.currentThread().getPriority());// 9

t.setPriority(4);
System.out.println(t.getPriority());//4
}
}

Various ways to prevent a thread from execution


===============================================
There are three ways to prevent(stop) a thread from execution.
1) yield()
2) join()
3) sleep()

1) yield()
----------
 It pause the current execution thread and gives the change to other threads having same priority.
 If there is no waiting threads or low priority threads then same thread will continue it's execution.
 If multiple threads having same priority then we can't expect any execution order.
 A thread which is yielded when it will get a chance for execution is depends upon mercy of
thread schedular.
ex:
public static native void yield()
Diagram: java43.1

class MyThread extends Thread


{
public void run()
{
for(int i=1;i<=5;i++)
{
Thread.currentThread().yield();
System.out.println("Child-Thread");
}
}
}
class Test
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.start();
for(int i=1;i<=5;i++)
{
System.out.println("Parent-Thread");
}
}
}

2) join()
------------
 If a thread wants to wait untill the completion of some other threads then we need to use join()
method.
 A join() method throws one checked exception called InterruptedException so we must and
should handle that exception by using try and catch block or by using throws statement.
ex:
public final void join()throws InterruptedException
public final void join(long ms)throws InterruptedException
public final void join(long ms,int ns)throws InterruptedException

Diagram: java43.2
ex
--
class MyThread extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("Child-Thread");
}
}
}
class Test
{
public static void main(String[] args)throws InterruptedException
{
MyThread t=new MyThread();
t.start();
t.join();
for(int i=1;i<=5;i++)
{
System.out.println("Parent-Thread");
}
}
}

3) sleep()
----------
 If a thread don't want to perform any operations on perticular amount of time then we need to use
sleep() method.
 A sleep() method will throw one checked exception called InterruptedException so we must and
should handle that exception by using try and catch block or by using throw statement.
ex:
public static native void sleep()throws InterruptedException
public static native void sleep(long ms)throws InterruptedException
public static native void sleep(long ms,int ns)throws InterruptedException

Diagram: java43.3
class MyThread extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("Child-Thread");
try
{
Thread.sleep(2000);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
}
class Test
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.start();
for(int i=1;i<=5;i++)
{
System.out.println("Parent-Thread");
}
}
}

Problems without synchronization


==============================
When we don't have synchronization then we will face following problems.
1) Thread interference
2) Data inconsistency problem
ex:
--
class Table
{
void printTable(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(2000);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(10);
}
}
class Test
{
public static void main(String[] args)
{
Table obj=new Table();

MyThread1 t1=new MyThread1(obj);


MyThread2 t2=new MyThread2(obj);

t1.start();
t2.start();
}
}

synchronization
================
 A synchronized keyword is applicable for methods and blocks.
 A synchronization is allowed one thread to execute given object.Hence we achieve thread safety.
 The main advantage of synchronization is we solve data inconsistence problem.
 The main disadvantage of synchronization is ,it will increase waiting time of a thread which
reduce the performance of the system.
 If there is no specific requirement then it is never recommanded to use synchronization concept.
 synchronization internally uses lock mechanism.
 Whenever a thread wants to access object , first it has to acquire lock of an object and thread will
release the lock when it completes it's task.
 When a thread wants to execute synchronized method.It automatically gets the lock of an object.
 When one thread is executing synchronized method then other threads are not allowed to execute
other synchronized methods in a same object concurently.But other threads are allowed to
execute non-synchronized method concurently.
ex:
class Table
{
synchronized void printTable(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(2000);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}

class MyThread2 extends Thread


{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(10);
}
}

class Test
{
public static void main(String[] args)
{
Table obj=new Table();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);

t1.start();
t2.start();
}
}

synchronized block
====================
 If we want to perform synchronization on specific resource of a program then we need to use
synchronization.
ex:
If we have 100 lines of code and if we want to perform synchronization only for
10 lines then we need to use synchronized block.

 If we keep all the logic in synchronized block then it will act as a synchronized method.
ex:
class Table
{
void printTable(int n)
{
synchronized(this)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(2000);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}//sync
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}

class MyThread2 extends Thread


{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(10);
}
}

class Test
{
public static void main(String[] args)
{
Table obj=new Table();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);

t1.start();
t2.start();
}
}

3)Static synchronization
=====================
 In static synchronization the lock will be on class but not on object.
 If we declare any static method as synchronized then it is called static synchronization method.
ex:
class Table
{
static synchronized void printTable(int n)
{

for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(2000);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}

}
}
class MyThread1 extends Thread
{

public void run()


{
Table.printTable(5);
}
}

class MyThread2 extends Thread


{

public void run()


{
Table.printTable(10);
}
}

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

MyThread1 t1=new MyThread1();


MyThread2 t2=new MyThread2();

t1.start();
t2.start();
}
}
Inter-Thread Communication
===========================
 Two threads can communication by using wait(), notify() and notifyAll() method.
 A thread which is waiting for notification has to call wait() method and a thread which is giving
notification has to call notify() or notifyAll() method.
 A wait(), notify() and notifyAll() methods of Object class but not Thread class.
 To invoke wait(), notify() and notifyAll() method compulsory we required synchronized area
othewise we will get IllegalStateMonitorException.
 A thread which calls wait() method on a current object then it will release the lock of that object
immediately and it goes waiting state.
 A thread which calls notify() And notifyAll() method on a current object then it will release the
lock of that object but not immediately.
 Except wait(), notify() and notifyAll() method there is no way to release the lock.
ex:
---
class MyThread extends Thread
{
int total=0;

public void run()


{
synchronized(this)
{
System.out.println("Child started Calculation");

for(int i=1;i<=10;i++)
{
total+=i;
}

System.out.println("Child Giving notification");


this.notify();
}
}
}
class Test
{
public static void main(String[] args)throws InterruptedException
{
MyThread t=new MyThread();
t.start();

synchronized(t)
{
System.out.println("Main method is waiting");
t.wait();
System.out.println("Main method got notification");
System.out.println(t.total);//55
}
}
}
DeadLock
=========
Deadlock will occur in a situation where one thread is waiting for object lock which is acquired by
another thread and that thread is waiting for object lock is which acquired by first thread. Here both the
threads are ready to release lock but nobody will release. This situation is called DeadLock.

Diagram: java44.1

class Test
{
public static void main(String[] args)
{
final String res1="hi";
final String res2="bye";

//Anonymous inner class


Thread t1=new Thread()
{
public void run()
{
synchronized(res1)
{
System.out.println("Thread1: Locking Resource1");
synchronized(res2)
{
System.out.println("Thread1: Locking Resource2");
}
}
}
};

//Anonymous inner class


Thread t2=new Thread()
{
public void run()
{
synchronized(res2)
{
System.out.println("Thread2: Locking Resource2");
synchronized(res1)
{
System.out.println("Thread2: Locking Resource1");
}
}
}
};

t1.start();
t2.start();
}
}
Q) What are the disadvantages of Multithreading?

1) Thread starvation
2) DeadLock
3) Debugging

Java 8 Features
===============
Functional interface
=====================
 Interface which contains only one abstract method is called functional interface.
 It can have any number of default methods and static methods.
 It is also known as Single Abstract Method interface or SAM interface.
 The main objective of functional interface to achieve functional programming.
ex:
a=f1()
{
}

f1(f2(){})
{
}

@FunctionalInterface annotation is used to use declare functional interface.


@FunctionalInterface annotation is optional to declare.
ex:
---
@FunctionalInterface
interface A
{
public abstract void m1();
}
class B implements A
{
public void m1()
{
System.out.println("M1-Method");
}
}
class Test
{
public static void main(String[] args)
{
A a=new B();
a.m1();
}
}

ex:
---
@FunctionalInterface
interface A
{
public abstract void m1();
}
class Test
{
public static void main(String[] args)
{
//Anonymous inner class
A a=new A()
{
public void m1()
{
System.out.println("M1-Method");
}
};
a.m1();
}
}

Lamda Expression
=================
 Lamda expression introduced in Java 8.
 Lamda expression is used to concise(reduce) the code.
 Lamda expression consider as method not a class.
 We can use lamda expression when we have functional interface.
 The main objective of lamda expression is to achieve functional programming.
 Lamda expression does not allow name, returntype and modifier.
ex:
Java Method
-----------
public void m1()
{
System.out.println("Hello World");
}

Lamda Expression
---------------
()->
{
System.out.println("Hello World");
};

ex:
---
@FunctionalInterface
interface A
{
public abstract void m1();
}
class Test
{
public static void main(String[] args)
{
A a=()->
{
System.out.println("M1-Method");
};
a.m1();
}
}

ex:
---
@FunctionalInterface
interface A
{
public abstract void m1(int i,int j);
}
class Test
{
public static void main(String[] args)
{
A a=(int i,int j)->
{
System.out.println(i+j);
};
a.m1(10,20);
}
}
ex:
---
@FunctionalInterface
interface A
{
public abstract int m1(int i,int j);
}
class Test
{
public static void main(String[] args)
{
A a=(int i,int j)->
{
return i+j;
};
System.out.println(a.m1(20,30));
}
}
Default methods of an interface
================================
 Default methods in interface introduced in Java 8.
 Java provides facility to declare methods in interface and tagged with default keyword are called
default methods.
 A default method is a non-abstract method.
 A default method can be override.
syntax:
-------
default returntype method_name()
{
-
- //code to be execute
-
}
ex:
---
@FunctionalInterface
interface A
{
//abstract method
public abstract void m1();

//default method
default void m2()
{
System.out.println("M2-Method");
}
}
class B implements A
{
public void m1()
{
System.out.println("M1-Method");
}
}
class Test
{
public static void main(String[] args)
{
A a=new B();
a.m1();
a.m2();
}
}
ex:
---
@FunctionalInterface
interface A
{
//abstract method
public abstract void m1();

//default method
default void m2()
{
System.out.println("M2-Method");
}
}
class B implements A
{
public void m1()
{
System.out.println("M1-Method");
}
//override
public void m2()
{
System.out.println("Override M2-Method");
}
}
class Test
{
public static void main(String[] args)
{
A a=new B();
a.m1();
a.m2();
}
}

 We can achieve multiple inheritance in java by using default methods of an interface.

ex:
---
interface Right
{
default void m1()
{
System.out.println("Right - M1-Method");
}
}
interface Left
{
default void m1()
{
System.out.println("Left - M1-Method");
}
}
class Middle implements Right,Left
{
public void m1()
{
System.out.println("Middle - M1-Method");
}
}
class Test
{
public static void main(String[] args)
{
Middle m=new Middle();
m.m1();
}
}

ex:
---
interface Right
{
default void m1()
{
System.out.println("Right - M1-Method");
}
}
interface Left
{
default void m1()
{
System.out.println("Left - M1-Method");
}
}
class Middle implements Right,Left
{
public void m1()
{
Right.super.m1();
Left.super.m1();
}
}
class Test
{
public static void main(String[] args)
{
Middle m=new Middle();
m.m1();
}
}
Static methods of an interface
================================
 Static methods in interface introduced in Java 8.
 Java provides facility to declare methods in interface and tagged with static keyword are called
static methods.
 A static method is a non-abstract method.
 A static method can't be override.
ex:
--
interface A
{
static void m1()
{
System.out.println("M1-Method");
}
}
class Test
{
public static void main(String[] args)
{
A.m1();
}
}

Q) When do we get NullPointerException in java?

 We will get NullPointerException when our code attempts to read object reference which has not
been initialized.
ex:
Test t=null;
System.out.println(t.i); // R.E NullPointerException
ex:
Test t=null;
t.methodOne(); // R.E NullPointerException
Ex:
int[] arr=null;
System.out.println(arr[0]); // R.E NullPointerException
ex:
List<Integer> list=null;
list.add(10); // R.E NullPointerException
ex:
Test t=null;
synchronized(t)
{
-
-
-
}
// R.E NullPointerException
 To avoid NullPointerException we need to perform following things.
1) Initialize objects before using them.
2) Perform null checks before dereferencing objects.
3) Using Optional which is having the capability to perform null checks gracefully.

1) Initialize objects before using them


----------------------------------------
ex:
Test t=new Test();
System.out.println(t.i);
ex:
Test t=new Test();
t.methodOne();
ex:
int[] arr=new int[3];
System.out.println(arr[0]); // 0
ex:
List<Integer> list=new ArrayList<Integer>;
list.add(10);
ex:
Test t=new Test();
synchronized(t)
{
-
-
-
}
2) Perform null checks before dereferencing objects
----------------------------------------------------
class Test
{
public static void main(String[] args)
{
Test t=null;

if(t==null)
{
t=new Test();
}

t.methodOne();
}
public void methodOne()
{
System.out.println("MethodOne");
}
}
Optional
===========
 Optional class introduced in Java 8.
 It is a final class which is present in java.util package.
 The main objective of Optional class is to handle null checks.
 There are three ways to create object for Optional class.

1) By using empty() method


-------------------------
It create an empty Optional.
ex:
Optional<Object> optional=Optional.empty();
2) By using of() method
------------------------
It creates Optional with non-null value and throws NullPointerException if value not found.
ex:
Optional<Object> optional=Optional.of();

3) By using ofNullable() method


---------------------------
It creates Optional which contains a value or to be empty if value not found.
ex:
Optional<Object> optional=Optional.ofNullable();
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
Optional<Object> optional=Optional.empty();
System.out.println(optional);//Optional.empty
}

}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
String str="ihub";

Optional<String> optional=Optional.of(str);
System.out.println(optional);//Optional[ihub]
}

}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
String str=null;

Optional<String> optional=Optional.of(str);
System.out.println(optional); // R.E NullPointerException
}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
String str="ihub";

Optional<String> optional=Optional.of(str);
System.out.println(optional); //Optional[ihub]

System.out.println(optional.get()); // ihub

System.out.println(optional.isPresent());//true
}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
String str="ihub";

Optional<String> optional=Optional.ofNullable(str);
System.out.println(optional); //Optional[ihub]

System.out.println(optional.get()); // ihub

System.out.println(optional.isPresent());//true
}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
String str="ihub";

Optional<String> optional=Optional.ofNullable(str);
System.out.println(optional.orElse("Value is Null")); // ihub

}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
String str=null;

Optional<String> optional=Optional.ofNullable(str);

System.out.println(optional.orElse("Value is Null")); // Value is Null

}
}
ex:
---
import java.util.*;
class Test
{
int i=10;

public static void main(String[] args)


{
Test t=null;

Optional<Object> optional=Optional.ofNullable(t);

if(!optional.isPresent())
{
t=new Test();
}

System.out.println(t.i);//10

}
}
Stream API
==========
 Stream API introduced in java 8.
 Stream API present in java.util.stream package.
 It allows functional-style programming on collections of data(objects).
 It is used to process sequence of objects and makes our code more readable and concise.
 In short, Stream API is used to perform bulk operations on Collections.
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{

//It create mutable list object


List<Integer> list=new ArrayList<Integer>();
list.add(1);
list.add(5);
list.add(6);
System.out.println(list);
}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{

//It create immutable list object

List<Integer> list=List.of(3,4,1,9);
System.out.println(list);//[3, 4, 1, 9]

list.add(10); // R.E UnsupportedOperationException


}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{

//It create immutable list object

List<Integer> list=Arrays.asList(3,4,1,9);
System.out.println(list);//[3, 4, 1, 9]

list.add(10); // R.E UnsupportedOperationException


}
}
ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{

List<Integer> list=List.of(6,2,9,1,3,5,4);

List<Integer> newList=list.stream().filter(i->i>5).collect(Collectors.toList());

System.out.println(newList);//[6,9]

}
}
ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{

List<Integer> list=List.of(6,2,9,1,3,5,4);

List<Integer> newList=list.stream().filter(i->i%2==0).collect(Collectors.toList());

System.out.println(newList);//[6, 2, 4]

}
}
ex;
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{

List<Integer> list=List.of(6,2,9,1,3,5,4);

List<Integer> newList=list.stream().map(i->i+10).collect(Collectors.toList());

System.out.println(newList);//[16, 12, 19, 11, 13, 15, 14]

}
}
ex;
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{

List<Integer> list=List.of(6,2,9,1,3,5,4);

long odd=list.stream().filter(i->i%2!=0).count();

System.out.println(odd);//4

}
}
ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{

List<Integer> list=List.of(6,2,9,1,3,5,4);

List<Integer> newList=list.stream().sorted().collect(Collectors.toList());

System.out.println(newList);//[1, 2, 3, 4, 5, 6, 9]

}
}
ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{

List<Integer> list=List.of(6,2,9,1,3,5,4);

List<Integer>
newList=list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());

System.out.println(newList);//[9, 6, 5, 4, 3, 2, 1]

}
}
ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{

List<Integer> list=List.of(6,2,9,1,3,5,4);

int minimum=list.stream().min((i1,i2)->i1.compareTo(i2)).get();

System.out.println(minimum);//1

}
}

ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{

List<Integer> list=List.of(6,2,9,1,3,5,4);

int maximum=list.stream().max((i1,i2)->i1.compareTo(i2)).get();

System.out.println(maximum);//9

}
}

ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
String[] sarr={"Alan","Jose","Kelvin","Mark"};

List<String> list=List.of(sarr);

List<String> newList=list.stream().filter(i-> i.startsWith("J")).collect(Collectors.toList());

System.out.println(newList);//9

}
}
forEach() method
=================
> forEach() method introduced in Java 8.
>It is used to iterate the objects/elements from Collections.
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
String[] sarr={"Alan","Jose","Kelvin","Mark"};

List<String> list=List.of(sarr);

list.forEach(element -> System.out.print(element+" "));

}
}

ex:
---

import java.util.*;
class Test
{
public static void main(String[] args)
{
Map<String,Integer> map=Map.of("one",1,"two",2,"three",3);
map.forEach((key,value)-> System.out.print(key+"="+value+" "));
}
}
Method Reference(::)
====================
 Method reference introduced in java 8.
 It is a special type of lamda expression.
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
String[] sarr={"Alan","Jose","Kelvin","Mark"};

List<String> list=List.of(sarr);

list.forEach(System.out::println);

}
}
ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
Map<String,Integer> map=Map.of("one",1,"two",2,"three",3);

map.forEach(Test::getKeyValue);
}
public static void getKeyValue(String key,Integer value)
{
System.out.println(key+"="+value);
}
}
Interview Question
==================
Q) Write a java program to display employee records in sorting order of employee id?

import java.util.*;
import java.util.stream.*;
class Employee
{
private int empId;
private String empName;
private double empSal;

Employee(int empId,String empName,double empSal)


{
this.empId=empId;
this.empName=empName;
this.empSal=empSal;
}
public int getEmpId()
{
return empId;
}
public String getEmpName()
{
return empName;
}
public double getEmpSal()
{
return empSal;
}
}
class Test
{
public static void main(String[] args)
{
List<Employee> list=new ArrayList<Employee>();
list.add(new Employee(104,"Jack",4000));
list.add(new Employee(102,"Brook",2000));
list.add(new Employee(103,"Mark",3000));
list.add(new Employee(101,"Alan",1000));

List<Employee>
newList=list.stream().sorted(Comparator.comparingInt(Employee::getEmpId)).collect(Collectors.toList())
;

newList.forEach(employee -> System.out.println(employee.getEmpId()+"


"+employee.getEmpName()+" "+employee.getEmpSal()));
}
}

Q) Write a java program to display employee records in sorting order of employee name?

import java.util.*;
import java.util.stream.*;
class Employee
{
private int empId;
private String empName;
private double empSal;

Employee(int empId,String empName,double empSal)


{
this.empId=empId;
this.empName=empName;
this.empSal=empSal;
}
public int getEmpId()
{
return empId;
}
public String getEmpName()
{
return empName;
}
public double getEmpSal()
{
return empSal;
}
}
class Test
{
public static void main(String[] args)
{
List<Employee> list=new ArrayList<Employee>();
list.add(new Employee(104,"Jack",4000));
list.add(new Employee(102,"Brook",2000));
list.add(new Employee(103,"Mark",3000));
list.add(new Employee(101,"Alan",1000));

List<Employee>
newList=list.stream().sorted(Comparator.comparing(Employee::getEmpName)).collect(Collectors.toList(
));

newList.forEach(employee -> System.out.println(employee.getEmpId()+"


"+employee.getEmpName()+" "+employee.getEmpSal()));
}
}

You might also like