0% found this document useful (0 votes)
19 views

Java Notes

Uploaded by

jimpakchimpak007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Java Notes

Uploaded by

jimpakchimpak007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 388

Naming Conventions in Java

===========================================
In java, uppercase letters will consider as different and lowercase letters consider as different.Hence we
consider java is a case sensitive programming language.
As java is a case sensitive, we must and should follow naming conventions for following things.
ex:
classes
interfaces
variables
methods
keywords
packages
constants
classes
--------
In java, a class name must and should starts with uppercase letter and if it contains multiple words then each
inner word must starts with initcap.
ex:
Predefined classes Userdefined classes
----------------- -------------------
System Test
Date ExampleApp
StringBuffer EmployeeInfo
FileWriter Department
and etvkjkmc. and etc.
interfaces
----------
In java, an interface name must and should starts with uppercase letter and if it contains multiple words then
each inner word starts with initcap.
ex:

predefined interfaces userdefined interfaces


----------------- ---------------------
Runnable ITest
Serializable IDemoApp
Cloneable IEmployeeDetails
ListIterator IStudentInfo
and etc. and etc
variables
----------
In java, a variable name must and should starts with lowercase letter and if it contains multiple words then
each inner word must starts with initcap.
ex:
predefined variables userdefined variables
----------------------- ---------------------
length a
err studNo
out employeeName
in deptNumber
and etc. and etc.
methods
--------
In java, a method name must and should starts with lowercase letter and if it contains multiple words then
each inner word must starts with initcap.
ex: predefined methods userdefined methods
------------------- -------------------
getPriority() getDetails()
hashCode() setAmount()
toString() calculateBillAmt()
setName() setStudentInfo()
and etc. and etc.

keywords
----------
In java, all keywords we need to declare under lowercase letters.
ex: predefined keywords
------------------
if, else, while, do , public , static , void , for and etc.
packages
---------
In java, all packages we need to declare under lowercase letters only.
ex:
predefined packages userdefined packages
---------------- --------------------
java.lang com.ihub.www
java.io com.google.www
java.util and etc.
java.util.stream
java.text
java.time
and etc.
constants
----------
In java, all constants we need to declare under uppercase letters only.
ex: predefined constants userdefined constants
--------------- -------------------
MAX_PRIORITY LIMIT
MIN_PRIORITY N=10
NORM_PRIORITY
MAX_VALUE
MIN_VALUE
and etc.
Assignment
===========
1) class : QualityThought
2) interface : IQualityThought
3) variable : qualityThought
4) method : qualityThought()
5) package : com.qualitythought.www
6) constant : QUALITY_THOUGHT
Interview Questions
===================
Q) What is package?
A package is a collection of classes and interfaces.
Q) Which package consider as a default package in java?
java.lang package
Diagram: java1.1
History of Java
======================
In 1990, Sun Micro System company took one project to develop a software called consumer electronic device
which can be controlled by a remote like setup box. That time project was called Stealth project and later it is
renamed to Green project.
James Gosling, Mike sheradin and Patrick Naughton were there to develop the project and they have met in a
place called Aspan/Colarado to start the work with Graphic System.James Gosling decided to use C and C++
languages to develop the project.But the problem what they have faced is C and C++ languages are system
dependent.Then James Gosling decided why don't we create our own programming language which is system
independent.
In 1991, they have developed a programming language called and OAK.OAK means strength , itself is a
coffee seed name and it is a national tree for many countries like Germany,France, USA and etc.
Later in 1995, they have renamed OAK to Java.Java is a Island of an Indonasia where first coffee of seed was
produced and during the development of project they were consuming lot of coffee's.Hence the symbol of java
is a cup of coffee with saucer.

Identifiers
===========
A name in java is called identifier.
It can be class name, variable name, method name or label name.
ex:
class Test
{
public static void main(String[] args)
{
int x = 10;
System.out.println(x);
}
}
Here Test, main , args, x , String , System are identifiers.
Rules to declare an identifiers
-------------------------------
Rule1:
-----
Identifier will accept following characters.
ex:
A-Z
a-z
0-9
_
$
Rule2:
-----
If we take other characters then we will get compile time error.
ex:
int emp_id; //valid
int emp#id; //invalid
int emp$alary; //valid
Rule3:
-----
Identifier must and should starts with alphabet,underscore or dollar symbol
but not with digit.
ex:
int emp123; //valid
int _emp; //valid
int $emp; //valid
int 1abcd; //invalid
Rule4:
-----
Every identifier is a case sensitive.
ex:
int number;
int NUMBER;
int NuMbEr;
Rule5:
-----
We can't take reserved words as an identifiers.
ex:
int if;
int else;
int do;
int for;

Rule6:
------
There is no length limit for an identifier but is not recommanded to take more then
15 characters.
Interview Questions
===================
Q) Who is the creator of Java ?
James Gosling
Q) In which year java was developed ?
In 1995
Q) Java originally known as ___ ?
OAK
Q) Is java platform independent or not ?
Java is a platform independent
Diagram: java2.1

Q) Is JVM platform dependent or indepenent?


It is a platform dependent.
Diagram: java2.2
Java
======
Version : Java 11
JDK : JDK 11
Creator : James Gosling
Vendor : Oracle Corporation
Open source : Open source
Website : www.oracle.com/in/java
Download link :
https://drive.google.com/file/d/1GtRLHXK4y3s97BH2UcYiJPNBaROR1DBV/view?usp=drive_link
Steps to setup environmental variables
=======================================
step1:
------
Make sure JDK 11 installed successfully.
step2:
-------
Copy "lib" directory from "Java_Home" folder.
ex:
C:\Program Files\Java\jdk-11\lib
step3:
-----
Paste "lib" directory in environment variables.
ex:
right click to This PC --> properties --> Advanced system settings -->
Environmental variables -->

user variables --> click to new button.

variable Name : CLASSPATH


variable value : C:\Program Files\Java\jdk-11\lib; --> click to Ok

system variables --> click to new button.

variable Name : path


variable value : C:\Program Files\Java\jdk-11\bin; --> ok --> ok --> ok.
step4:
------
Check the environmental setup done perfectly or not.
ex: cmd> javap
cmd> java -version

Steps to develop first java application


=====================================
step1:
----- Make sure JDK 11 installed successfully.
step2:
----- Make sure environmental setup done perfectly.
step3:
----- Create a "javaprog" folder inside 'E' drive.
step4:
----- Open the notepad and write Hello World program
ex:
class Test
{
public static void main(String[] args)
{
System.out.println("Hello World");
}

}
step5:
------ Save java program with same name as class name inside "javaprog" folder.
step6:
----- Open the command prompt from "javaprog" location.
step7:
------ Compile the java program by using below command.
ex:
javaprog> javac Test.java
|
filename
step8:
------
Run the java program by using below command.
ex: javaprog> java Test
z |
classname
Reserved words
===============
There are some identifiers which are reserved to associate some functionality or meaning such type of
identifiers are called reserved words.
Java supports 53 reserved words.
In java , reserved words are divided into two types.
Diagram: java3.1

Used keywords with respect to class


------------------------------------
import
package
enum
interface
class
extends
implements

Used keywords with respect to object


-------------------------------
new
instanceof
thisl
super
Used keywords with respect to datatypes
--------------------------------------
byte
short
int
long
float
double
boolean
char

Used keywords with respect to flow control


------------------------------------------
if
else
do
while
break
continue
for
switch
case
Used keywords with respect to modifiers
----------------------------------
default
public
private
protected
final
static
abstract
synchronized
strictfp
transient
volatile
native
Used keywords with respect to return type
----------------------
void
Used keywords with respect to exception handling
----------------------
try
catch
throw
throws
finally
assert

Internal Architecture of JVM


=========================================
Diagram: java4.1

jdkcode instructions in .class file.


JVM will invoke one module called classloader/subsystem to load all the byte code instructions from .class
file.That work of classloader is to check these byte code instructions are proper or not. If they are not proper
then it will refuse the execution. If they are proper then it will allocate the memory.
We have five types of memories in java.
1) Method Area
----------------
It contains code of a class, code of a variable and code of a method.
2) Heap
--------
Our object creations will store in heap area.
3) Java Stack
-------------
Java methods will store in method area but to execute those methods we required some
memory and that memory will be allocated in java stack.
4) PC register
----------------
It is a program counter register which is used to track the address of an instructions.
5) Native Method Stack
----------------------
Java methods will execute in method area.
Similarly native methods will execute in native method stack.
But we can't execute native methods directly. We required a program called Native method interface.
Execution engine
----------------
Whenever JVM loads byte code instructions from .class file , it will uses interpreter and JIT compiler.
Interpreter is used to execute our program line by line procedure.
JIT compiler is used to increase the execution speed of our program.
Finally, our JVM converts byte code to machine code .
Interview Questions
===================
Q) What is native method in java?
A method which is developed by using some other language is called native method.
Q) How many memories are there in java?
We have five memories in java.
1) Method Area
2) Heap
3) Java Stack
4) PC Register
5) Native Method Stack
Q) What is JIT compiler?
It is a part of a JVM which is used to increase the execution speed of our program.
Q) How many classloaders are there in java?
We have three predefined classloaders in java.
1) Bootstrap classloader
2) Extension classloader
3) Application/System classloader
Q) What is JVM?
JVM is an interpreter which is used to execute our program line by line procedure and converts byte cod to
machine code.
Q) Features of Java ?
We have following important features in java.
1) Simple
2) Object oriented
3) Platform independent
4) Portable
5) Architecture Neutral
6) Robust
7) Multithreaded
8) Distributed
and etc.

Datatypes
================
Datatype describes what type of value we want to store inside a variable.
Datatype also tells how much memory has to be created for a variable.
In java , datatypes are divided into two types.
Diagram: java5.1
Byte
-----
It is smallest datatype in java.
Size : 1 byte (8 bits)
Range : -128 to 127 (-2^7 to 2^7-1)
ex:
1) byte b=10;
System.out.println(b); // 10
2) byte b=130;
System.out.println(b); // C.T.E
3) byte b=10.5;
System.out.println(b); // C.T.E
short
------
It is rarely used datatype in java.
Size : 2 bytes (16 bits)
Range : -32768 to 32767 (-2^15 to 2^15-1)
ex:
1) byte b=10;
short s=b;
System.out.println(s); //10
2) short s=10.5;
System.out.println(s); // C.T.E
3) short s=true;
System.out.println(s); // C.T.E
int
----
It is widely used datatype in java.
Size : 4 bytes (32 bits)
Range : -2147483648 to 2147483647 (-2^31 to 2^31-1)
ex:
1) int i="hi";
System.out.println(i); // C.T.E
2) int i=false;
System.out.println(i); // C.T.E
3) int i='a';
System.out.println(i); // 97
Note:
-----
In java for every character we have universal unicode value.
ex:
A ---- 65
a ---- 97
long
-----
If int datatype is not enough to large value then we need to use long datatype.
Size : 8 bytes (64 bits)
Range : (-2^63 to 2^63-1)
ex:
1) long l="true";
System.out.println(l); // C.T.E
2) long l='A';
System.out.println(l); // 65
3) long l=false;
System.out.println(l); // C.T.E
4) long l=10.5;
System.out.println(l); // C.T.E

float double
----------- ------------
If we need 4 to 6 decimal point of accuracy If we need 14 to 16 decimal point of accuracy
then we need to use float. then we need to use double.
Size : 4 bytes (32 bits) Size : 8 bytes (64 bits)
Range : -3.4e38 to 3.4e38 Range : -1.7e308 to 1.7e308
To declare a float value we need to To declare a double value we need to suffix
suffix with 'f' or 'F'. with 'd' or 'D'.
ex: ex:
10.5f 10.5d
ex:

1) float f=10.5f;
System.out.println(f); // 10.5
2) float f=10;
System.out.println(f); // 10.0
3) float f='a';
System.out.println(f); // 97.0
4) float f="hi";
System.out.println(f); // C.T.E
5) float f=true;
System.out.println(f); // C.T.E
ex:
1) double d=10.5d;
System.out.println(d); // 10.5
2) double d=10;
System.out.println(d); // 10.0
3) double d='a';
System.out.println(d); // 97.0
4) double d="hi"
System.out.println(d); // C.T.E
5) double d=true;
System.out.println(d); // C.T.E
boolean
--------
It is used to represent boolean values either true or false.
Size : (Not Applicable) (1-bit)
Range : (Not Applicable)
ex:
1) boolean b="true";
System.out.println(b); // C.T.E
2) boolean b=TRUE;
System.out.println(b); // C.T.E
3) boolean b=true;
System.out.println(b); // true
char
-----
It is a single character which is enclosed in a single quotation.
Size : 2 bytes (16 bits)
Range : 0 to 65535
ex:
1) char ch='a';
System.out.println(ch); // a
2) char ch=65;
System.out.println(ch); // A
3) char ch="d";
System.out.println(ch); // C.T.E
Diagram: java5.2

h
Q) Write a java program to display range of int datatype?
int range : -2147483648 to 2147483647
ex:
class Test
{
public static void main(String[] args)
{
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.MAX_VALUE);
}
}

Types of variables
==============================
A name which is given to a memory location is called variable.
Purpose of variable is used to store the data.
In java, we have two types of variables.
1) Primitive variables
--------------------
Primitive variables are used to represent primitive values.
2) Reference variables
-----------------------
Reference variables are used to represent object reference.
ex:
Student s=new Student();
|
reference variable
Based on the position and execution these variables are divided into three types.
1) Instance variables / Non-static variables
2) Static variables / Global variables
3) Local variables / Temperory variables / Automatic variables
1) Instance variables
-----------------------
A value of a variable which is varied(changes) from object to object is called instance variable.
Instance variable will be created at the time of object creation and it will destroy at the time of object
destruction.Hence scope of instance variable is same as scope of an object.
Instance variable will store in heap area as a part of an object.
Instance variable must and should declare immediately after the class but not inside methods,blocks and
constructors.
Instance variables we can access directly from instance but we can't access from static area.
To access instance variable from static area we need to create object reference.
ex:1
-----
class Test
{
//instance variableh
int i=10;
public static void main(String[] args)
{
System.out.println(i);
}
}
o/p:
C.T.E : non-static variable i cannot be referenced from a static context
ex:2
-----
class Test
{
//instance variable
int i=10;
public static void main(String[] args)
{
Test t=new Test();
System.out.println(t.i);//10
}
}
Note:
-----
If we won't initialize any value to instance variable then JVM will initialize default values.
ex:3
----
class Test
{
//instance variable
boolean b;

public static void main(String[] args)


{
Test t=new Test();
System.out.println(t.b);//false
}
}
ex:4
----
class Test
{
//instance variable
int i=10;
public static void main(String[] args)
{
Test t1=new Test();
Test t2=new Test();
System.out.println(t1.i);//10
System.out.println(t2.i);//10
t1.i=20;
System.out.println(t1.i);//20
System.out.println(t2.i);//10

}
}
ex:5
-----
class Test
{
public static void main(String[] args)
{
Test t=new Test();
t.m1();
}
//non-static method
public void m1()
{
System.out.println("instance-method");
}
}
2) Static variables
--------------------
A value of a variable which is not varied from object to object is called static variable.
Static variable will be created at the time of classloading and it will destroy at the time of classunloading.Hence
scope of static variable is same as scope of a .class file.
Static variable will store in Method area.
Static variable must and should declare immediately after the class using static keyword but not inside
methods, blocks and constructors.

Static variable we can access directly from instance area and static area.
Static variable we can access by using object reference and class name.
ex:1
-----
class Test
{
//static variable
static int i=10;
public static void main(String[] args)
{
System.out.println(i);//10
Test t=new Test();
System.out.println(t.i);//10
System.out.println(Test.i);//10
}
}
Note:
-----
If we won't initialize any value to static variable then JVM will initialize default values.
ex:2
----
class Test
{
//static variable
static String s;
public static void main(String[] args)
{
System.out.println(s);//null
Test t=new Test();
System.out.println(t.s);//null
System.out.println(Test.s);//null
}
}

ex:3
----
class Test
{
//static variable
static int i=10;
public static void main(String[] args)
{
Test t1=new Test();
Test t2=new Test();
System.out.println(t1.i);//10
System.out.println(t2.i);//10
t1.i=20;
System.out.println(t1.i);//20
System.out.println(t2.i);//20
}
}

ex:4
-----
class Test
{
public static void main(String[] args)
{
m1();
Test t=new Test();
t.m1();
Test.m1();
}
//static method
public static void m1()
{
System.out.println("static-method");
}
}

3) Local variables
==================
To meet temperory requirements a programmer will declare some variables inside methods, blocks and
constructors. Such type of variables are called local variables.
Local variable will be created at the time of execution block and it will destroy when execution block is
executed.Hence scope of local variable is same as scope of an execution block where it is declare.
Local variable will store in java stack.
ex:1
---
class Test
{
public static void main(String[] args)
{
//local variable
int i=10;
System.out.println(i); //10
}
}
Note:
----
If we won't initialize any value to local variable then JVM will not initialize default values.
ex:2
---
class Test
{
public static void main(String[] args)
{
//local variable
int i;
System.out.println(i);
}
}
o/p:
C.T.E :variable i might not have been initialized
A local variable will accept only one modifier i.e final.
ex:3
----
class Test
{
public static void main(String[] args)
{
//local variable
final int i=10;
System.out.println(i);//10 m
}
}
Interview Questions
===================
Q) Is java purely object oriented or not?
No, java will not consider as purely object oriented programming language because java does not supports
many OOPS concepts like multiple inheritance, operator overloading and more ever we depends upon
primitive datatypes which are non-objects.
Q) What is literal?
A value which is assign to a variable is called literal.
A value which is not change during the program execution is called literal.
ex:
int i = 10;
| | |___ value of a variable / Literal
| |________ variable / identifier
|____________ Datatype / Keyword

Fully Qualified Name


====================
Fully qualified name means we need to declare class name or interface name along with package name.
ex:
java.util.Date (C)
java.io.Serializable (I)
Fully qualified name is used to improve readability of our code.
ex:
---
class Test
{
public static void main(String[] args)
{
java.util.Date d=new java.util.Date();
System.out.println(d);
}
}

Import Statements
==================
Whenever we use import statements we should not use fully qualified name.
Using short name also we can achieve.
We have three types of import statements in java.
1) Explicit class import
2) Implicit class import
3) Static import

1) Explicit class import


------------------------
This type of import statement is highly recommanded to use because it will improve readability of our code.
ex:
---
import java.time.LocalDate;
import java.time.LocalTime;
class Test
{
public static void main(String[] args)
{
LocalDate date=LocalDate.now();
System.out.println(date);
LocalTime time=LocalTime.now();
System.out.println(time);
}
}

2) Implicit class import


-------------------------
This type of import statement is not recommanded to use because it will reduce readability of our code.
ex:
---
import java.time.*;
class Test
{
public static void main(String[] args)
{
LocalDate date=LocalDate.now();
System.out.println(date);
LocalTime time=LocalTime.now();
System.out.println(time);
}
}

3) Static import
----------------
Using static import we can access static members directly.
Often use of static import makes our program complex and unreadable.
ex:1
-----
import static java.lang.System.*;
class Test
{
public static void main(String[] args)
{
out.println("stmt1");
out.println("stmt2");
out.println("stmt3");
}
}
ex:
---
import static java.lang.System.*;
class Test
{
public static void main(String[] args)
{
out.println("stmt1");
exit(0);
out.println("stmt2");
}
}

Editplus Editorn
===============
Download link: https://www.editplus.com/download.html

Basic Java Programs


===================
Q) Write a java program to perform sum of two numbers?
import java.util.Scanner;
class Example1
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first number :");
int a=sc.nextInt();
System.out.println("Enter the second number :");
int b=sc.nextInt();
//logic
int c = a + b;
System.out.println("sum of two numbers is ="+c);
}
}
Q) Write a java program to perform sum of two numbers without using third variable?
import java.util.Scanner;
class Example2
{
public static void main(String[] args)
{kmh9pk
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first number :");
int a=sc.nextInt();
System.out.println("Enter the second number :");
int b=sc.nextInt();
System.out.println("sum of two numbers is ="+(a+b));
}
}
Q) Write a java program to find out square of a given number?
input:
5

output:
25
ex:
import java.util.Scanner;
class Example3
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number :");
int n=sc.nextInt();
//logic
int square=n*n;
System.out.println("Square of a given number is ="+square);
}
}
Q) Write a java program to find out cube of a given number?
input:
5
output:
125
import java.util.Scanner;
class Example4
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number :");
int n=sc.nextInt();
//logic
int cube=n*n*n;
System.out.println("Cube of a given number is ="+cube);
}
}
Q) Write a java program to find out area of a circle?
import java.util.Scanner;
class Example5
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the radius :");
int r=sc.nextInt();
//logic
float area=3.14f*r*r;
System.out.println("Area of a circle is ="+area);
}
}
Q) Write a java program to find out perimeter of a circle?
import java.util.Scanner;
class Example6
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the radius :");
int r=sc.nextInt();
//logic
float perimeter=2*3.14f*r;
System.out.println("Perimeter of a circle is ="+perimeter);
}
}
Q) Write a java program to display swapping of two numbers?
import java.util.Scanner;
class Example7
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first number :");
int a=sc.nextInt();//10
System.out.println("Enter the second number :");
int b=sc.nextInt();//20
System.out.println("Before swapping a="+a+" and b="+b);
//logic
int temp=a;
a=b;
b=temp;
System.out.println("After swapping a="+a+" and b="+b);
}
}
Q) Write a java program to perform swapping of two numbers without using third variable?
import java.util.Scanner;
class Example7
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first number :");
int a=sc.nextInt();//10
System.out.println("Enter the second number :");
int b=sc.nextInt();//20
System.out.println("Before swapping a="+a+" and b="+b);
//logic
a=a+b;
b=a-b;
a=a-b;

System.out.println("After swapping a="+a+" and b="+b);


}
}
Q) Write a java program to accept one salary then find out 10% of TDS?
import java.util.Scanner;
class Example8
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the salary :");
int salary=sc.nextInt();//
float tds=(float)salary*10/100;
System.out.println("10 percent of TDS is ="+tds);
}
}
Assignment
-----------
Q) Write a java program to convert CGPA to percentage?
Q) Write a java program to find out area of a circle ?
Q) Write a java program to accept six marks of a student then find out total and average?

Typecasting in java
===================
The process of converting from one datatype to another datatype is called typecasting.
In java, typecasting can be done in two ways.
1) Implicit typecasting
2) Explicit typecasting

1) Implicit typecasting
-----------------------
If we want to store small value into a bigger variable then we need to use implicit typecasting.
A compiler is responsible to perform implicit typecasting.
There is no possibility to loss the information.
It is also known as Widening or Upcasting.
We can perform implicit typecasting as follow.
ex:
byte ---> short
--->
int ---> long ---> float ---> double
--->
char
ex:
---
class Test
{
public static void main(String[] args)
{
byte b=10;
int i=b;
System.out.println(i); // 10
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
char ch='a';
long l=ch;
System.out.println(l); // 97
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;
double d=i;
System.out.println(d); // 10.0
}
}l

2) Explicit typecasting
-----------------------
If we want to store bigger value into a smaller variable then we need to use explicit typecasting.
A programmer is responsible to perform explicit typecasting.
There is a possibility to loss the information.
It is also known as Narrowing or Downcasting.
We can perform explicit typecasting as follow.
ex:
byte <--- short
<---
int <--- long <--- float <--- double
<---
char
ex:
---
class Test
{
public static void main(String[] args)
{
double d=10.56d;
int i=(int)d;
System.out.println(i); //10
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=65;
char ch=(char)i;
iSystem.out.println(ch); //A
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=130;
byte b=(byte)i;
System.out.println(b); // -126
}
}

Types of blocks in Java


===================================
A block is a set of statements which is enclosed in a curly braces i.e {}.
In java, we have three types of blocks.
1) Instance block
2) Static block
3) Local block

1) Instance block
-------------------------------------
Instance block is used to initialize the values to instance variables.
Instance block must and should declare immediately after the class but not inside methods and constructors.f
Instance block will execute at the time of object creation.
We can declare instance block as follow.
syntax:
------
//instance block
{
-
- //set of statements
-
}
ex:
---
class Test
{
//instance block
{
System.out.println("instance-block");
}

public static void main(String[] args)


{
System.out.println("main-method");
}
}
o/p:
main-method
ex:
----
class Test
{
//instance block
{
System.out.println("instance-block");
}

public static void main(String[] args)


{
System.out.println("main-method");
Test t=new Test();
}
}
o/p:
main-method
instance-block
ex:
---
class Test
{
//instance block
{
System.out.println("instance-block");
}

public static void main(String[] args)


{
Test t1=new Test();
System.out.println("main-method");
Test t2=new Test();
}
}
o/p:

instance-block
main-method
instance-block

ex:
---
class Test
{
//instance variable
int i;
//instance block
{
i=100;
}
public static void main(String[] args)
{
Test t=new Test();
System.out.println(t.i); //100
}
}
2) Static block
----------------
Static block is used to initialize the static variables.
Static block must and should declare immediately after the class using static keyword but not inside methods
and constructors.
Static block will execute the time of classloading.
We can declare static block as follow.
syntax:
-------
//static block
static
{
-
- //set of statements
-
}

ex:
----
class Test
{
//static block
static
{
System.out.println("static-block");
}
public static void main(String[] args)
{
System.out.println("main-method");
}
}

o/p:
static-block
main-method
ex:
---
class Test
{
//instance block
{
System.out.println("instance-block");
}
//static block
static
{
System.out.println("static-block");
}
public static void main(String[] args)
{
Test t=new Test();
System.out.println("main-method");
}
}
o/p:

static-block
instance-block
main-method

ex:
----
class Test
{
//static variable
static int i;

//static block
static
{
i=200;
}

public static void main(String[] args)


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

3) Local block
--------------
Local block is used to initialize the local variables.
Local block will execute just like normal statement.
Local block must and should declare inside methods and constructors.
We can declare local block as follow.
syntaX:
------
//local block
{
-
- //set of statements
-
}
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");
//local block
{
System.out.println("stmt2");
}
System.out.println("stmt3");
}
}
o/p:
stmt1
stmt2
stmt3

ex:
---
class Test
{
public static void main(String[] args)
{
//local variable
int i;

//local block
{
i=300;
}

System.out.println(i); //300
}
}

Interview Question
==================
Q) Can we execute java program without main method?
Yes , till 1.6 version it is possible to execute java program without main method using static block. But from 1.7
version onwards it is not possible to execute java program without main method.

ex:
---
class Test
{
static
{
System.out.println("Hello World");
System.exit(0);
}
}

Operators
==========
Operator is a symbol which is used to perform some operations on operands.
ex:
c=a+b;
Here = and + are operators
Here a,b and c are operands
It can be arithmetic operation, logical operation, bitwise operation and etc.
We have following list of operators in java.
1) Assignment operators
2) Ternary/Conditional operators
3) Logical operators
4) Bitwise operators
5) Arithmetic operators
6) Relational operators
7) Shift operators
8) Unary operators

1) Assignment operators
-----------------------
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;
i=20;
i=30;
System.out.println(i); // 30
}
}
Note:
-----
Variable reinitialization is possible in java.
ex:
---
class Test
{
public static void main(String[] args)
{
final int i=10;
i=20;
i=30;
System.out.println(i); // C.T.E
}
}
o/p:
C.T.E : cannot assign a value to final variable
ex
---
class Test
{
public static void main(String[] args)
{
int i=1,2,3,4,5;
System.out.println(i); //C.T.E
}
}
o/p:
C.T.E : Identifier expected
ex:
---
class Test
{
public static void main(String[] args)
{
int i,j;
i=j=1,2;
System.out.println(i+" "+j); // C.T.E
}
}
o/p:
C.T.E : semicolon expected
ex:
---
class Test
{
//global variable
static int i=10;
public static void main(String[] args)
{
//local variable
int i=20;
System.out.println(i); // 20
}
}
Note:
----
Here priority goes to local variable.
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;
i+=4; // i = i + 4
System.out.println(i); //14
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;
i-=45; // i = i - 45
System.out.println(i); // -35
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;
i*=6;
System.out.println(i); // 60
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;
i/=4;
System.out.println(i); // 2
int j=10;
j/=20;
System.out.println(j); // 0
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;
i%=4;
System.out.println(i); // 2
int j=10;
j%=20;
System.out.println(j); // 10
}
}

2) Ternary/Conditional operators
-------------------------------
syntax:
------
(condition)?value1:value2;
ex:
---
class Test
{
public static void main(String[] args)
{
int i=(true)?1:0;
System.out.println(i);//1
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
String s=(false)?"It is true":"It is false";
System.out.println(s);//It is false
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
boolean b=(5>2)?true:false;
System.out.println(b);//
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
char ch=(5>20)?'t':'f';
System.out.println(ch);// f
}
}
Q) Write a java program to find out greatest of two numbers?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the first number :");


int a=sc.nextInt(); // 20
System.out.println("Enter the second number :");
int b=sc.nextInt(); // 30
int max=(a>b)?a:b;
System.out.println("Greatest of two numbers is ="+max);
}
}
Q) Write a java program to find out greatest of three numbers?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the first number :");


int a=sc.nextInt(); // 20

System.out.println("Enter the second number :");


int b=sc.nextInt(); // 30

System.out.println("Enter the third number :");


int c=sc.nextInt(); // 6

int max=(a>b)?((a>c)?a:c):((b>c)?b:c);

System.out.println("Greatest of three numbers is ="+max);


}
}

3) Logical operators
---------------------
Logical AND operator (&&)
-------------------------
Logical AND operator deals with boolean values either true or false.
Truth table
-----------
T T =T
T F =F
F T =F
F F =F
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println(true && true); //true
System.out.println(true && false);//false
System.out.println(false && true);//false
System.out.println(false && false); //false
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
boolean b= (5>2) && (6<10);

System.out.println(b); // true
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
boolean b= (5>20) && (6<1);
System.out.println(b); // false
}
}
Logical OR operator (||)
------------------------
Logical OR operator deals with boolean values either true or false.
truth table
-----------
T T =T
T F =T
F T =T
F F =F
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println(true || true); //true
System.out.println(true || false); //true
System.out.println(false || true); //true
System.out.println(false || false); //false
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
boolean b=(5>2) || (6<1);

System.out.println(b); // true
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
boolean b=(5>10) || (7<3);
System.out.println(b); // false
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
boolean b = (5>2) && (6<3) || (67>5);
System.out.println(b);// true
}
}
Logical NOT operator (!)
------------------------
Logical NOT operator deals with boolean values either true or false.
ex:
---
class Test d
{
public static void main(String[] args)
{
boolean b = !(5>2);
System.out.println(b);//false
}
}

ex:
---
class Test
{
public static void main(String[] args)
{
boolean b = !(5>20);
System.out.println(b);//true
}
}
How to convert decimal to binary number
========================================

10 - decimal number
1010 - binary number

2|10
--- 0
2|5
--- 1
2|2
--- 0 ^
1 |
-----------------
1010
How to convert binary to decimal number
========================================

1010 - binary number


10 - decimal number

1010
<----

0*1 + 1*2 + 0*4 + 1*8

0 + 2 + 0 + 8 = 10

4) Bitwise operators
=====================
Bitwise AND operator (&)
-------------------------
Bitwise AND operator deals with binary numbers.
Truth table
-----------
T T =T
T F =F
F T =F
F F =F
ex:
---
class Test
{
public static void main(String[] args)
{
int a=10, b=15;
int c = a & b;
System.out.println(c); //10
}
}
/*
10 - 1010
15 - 1111
----------
& - 1010
<---
0*1 + 1*2 + 0*4 + 1*8
0 + 2 + 0 + 8 =10
*/
ex:
---
class Test
{
public static void main(String[] args)
{
int a=10, b=5;
int c = a & b;
System.out.println(c); //0
}
}
/*
10 - 1010
5 - 0101
----------
& - 000

*/
Bitwise OR operator (|)
------------------------
Bitwise OR operator deals with binary numbers.
Truth table
------------
T T =T
T F =T
F T =T
F F =F
ex:
---
class Test
{
public static void main(String[] args)
{
int a=10, b=5;
int c = a | b;
System.out.println(c); // 15
}
}
/*
10 - 1010
5 - 0101
----------
| - 1111
<---
1*1 + 1*2 + 1*4 + 1*8
1 + 2 + 4 + 8 = 15
*/
Bitwise XOR operator (^)
-----------------------
Bitwise XOR operator deals with binary numbers.
Truth table
-----------
T T =F
T F =T
F T =T
F F =F
ex:
---
class Test
{
public static void main(String[] args)
{
int a=10, b=15;
int c = a ^ b;
System.out.println(c); // 5
}
}
/*
10 - 1010
15 - 1111
----------
^ - 0101
<---
1*1 + 0*2 + 1*4 + 0*8
1+0+4+0=5
*/
Bitwise NOT operator (~)
------------------------
ex:
---
class Test
{
public static void main(String[] args)
{
int i= ~10;
System.out.println(i); // -11
}
}
ex:
----
class Test
{
public static void main(String[] args)
{
int i= ~24;
System.out.println(i); // -25
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i= ~(-10);
. System.out.println(i); // 9
}
}

5) Arithmetic operators
=======================
% - modules
/ - division
* - multiplication
+ - addition
- - subtraction
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 5+6%3+7*2+10%30+7/2+8+10/40+6-20;
System.out.println(i); // 26
}
}
/*
5 + 6%3 + 7*2 + 10%30 + 7/2 + 8 + 10/40 + 6 - 20
5 + 0 + 14 + 10 + 3 + 8 + 0 + 6 - 20
46 - 20
26
*/

6) Relational operators
-----------------------
class Test
{
public static void main(String[] args)
{
System.out.println(10 > 20); // false
System.out.println(10 >= 20); // false
System.out.println(10 < 20); // true
System.out.println(10 <= 10); // true
System.out.println(10 == 10); // true
System.out.println(10 == 20); // false
System.out.println( 10 != 10); // false
System.out.println(10 != 20); //true
}
}

7) Shift operators
====================
Right shift operator (>>)
-------------------------
10 >> 1 = 10/2
10 >> 2 = 10/4
10 >> 3 = 10/8
10 >> 4 = 10/16
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 10 >> 3;
System.out.println(i); // 1
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 100 >> 5;
System.out.println(i); // 100/32 = 3
}
}
Left shift operator (<<)
-------------------------
10 << 1 = 10*2
10 << 2 = 10*4
10 << 3 = 10*8

10 << 4 = 10*16
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 10 << 4;
System.out.println(i); // 10 * 16 = 160
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 100 << 2;
System.out.println(i); // 100 << 4 = 400
}
}

8) Unary operators
==================
Increment/Decrement operators(++/--)
------------------------------------
We have two types of increment operators.
1) post increment
ex:
i++;
2) pre increment
ex:
++i;
We have two types of decrement operators.
1) post decrement
ex:
i--;
2) pre decrement
ex:
--i;
POST Increment/Decrement operators
----------------------------------
Rule1 : First Take
Rule2 : Then Change
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 10;
i++;
System.out.println(i); // 11
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 10;
System.out.println(i++); // 10
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 10;
int j = i++;
System.out.println(i+" "+j); // 11 10
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 10;

int j = i++ + i++; //10 + 11

System.out.println(i+" "+j); // 12 21
}
}
ex:
----
class Test
{
public static void main(String[] args)
{
int i = 10;
int j = i-- + i--; // 10 + 9
System.out.println(i+" "+j); // 8 19
}
}
PRE Increment/Decrement operators
----------------------------------
Rule1 : First Change
Rule2 : Then Take
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 10;h
++i;
System.out.println(i); // 11
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 10;
System.out.println(++i); // 11
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 10;
int j= ++i;
System.out.println(i+" "+j); // 11 11
}
}
ex:
----
class Test
{
public static void main(String[] args)
{
int i = 10;
int j= ++i + ++i; // 11 + 12
System.out.println(i+" "+j); // 12 23
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i = 10;
int j= --i + --i + --i; // 9 + 8 + 7
System.out.println(i+" "+j); // 7 24
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
byte b=127;
b++;
System.out.println(b);// - 128
}
}

ex:
---
class Test
{
public static void main(String[] args)
{
int g=5;
g++;
System.out.println(10 * g++);// 10 * 6
}
}

ex:
class Test
{
public static void main(String[] args)
{
int i=10;
System.out.println(++(i++));// C.T.E
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=10;
System.out.println(i++ + ++i);// 10 + 12 = 22
}
}

Control Statements
==================
Control statement enables the programmer to control flow of the program.
Control statement allows us to make decisions, to jump from one section of code to another section and to
execute the code repeatedly.
In java, we have four types of control statements.
1) Decision Making Statement
2) Selection Statement
3) Iteration Statement
4) Jump Statement
1) Decision Making Statement
-----------------------------
It is used to declare the conditions in our program.
Decision making statement is possible by using following ways.
i) if stmt
ii) if else stmt
iii) if else if ladder
iv) nested if stmt
i) if stmt
------------
It will execute the source code only if our condition is true.
syntax:
-----
if(condition)
{e
-
- //code to be execute
-
}
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");
if(5>2)
{
System.out.println("stmt2");
}

System.out.println("stmt3");
}
o/p:
stmt1
stmt2
stmt3
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");

if(!(5>2))
{
System.out.println("stmt2");
}
System.out.println("stmt3");
}
}
o/p:
stmt1
stmt3
ex:
---
class Test
{
public static void main(String[] args)
{
if((5>2) && (6<1))
System.out.println("stmt1");
System.out.println("stmt2");
System.out.println("stmt3");
}
}
o/p:
stmt2
stmt3
Q) Write a java program to find out greatest of two numbers?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first number :");
int a=sc.nextInt();
System.out.println("Enter the second number :");
int b=sc.nextInt();
if(a>b)d
System.out.println(a+" is greatest");
if(b>a)
System.out.println(b+" is greatest");
}
}
Q) Write a java program to find out greatest of three numbers?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first number :");
int a=sc.nextInt();
System.out.println("Enter the second number :");
int b=sc.nextInt();
System.out.println("Enter the third number :");
int c=sc.nextInt();
if((a>b) && (a>c))
System.out.println(a+" is greatest");
if((b>a) && (b>c))
System.out.println(b+" is greatest");
if((c>a) && (c>b))
System.out.println(c+" is greatest");
}
}
ii) if else stmt
-----------------
It will execute the source code either our condition is true or false.

syntax:
------
if(condition)
{
- //code to be execute if cond is true
}
else
{
- //code to be execute if cond is false
}
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");
if(10 == 10)
{
System.out.println("stmt2");
}
else
{
System.out.println("stmt3");
}
System.out.println("stmt4");
}
}
o/p:
stmt1
stmt2
stmt4
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");
if(10 != 10)
{
System.out.println("stmt2");
}
else
{
System.out.println("stmt3");
}
System.out.println("stmt4");
}
}

o/p:
stmt1
stmt3
stmt4
Q) Write a java program to check given age is eligible to vote or not?
import java.util.Scanner;
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)
System.out.println("U r eligible to vote");
else
System.out.println("U r not eligible to vote");

}
}

Q) Write a java program to find out given number is even or odd ?


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();
if(n%2==0)
System.out.println("It is even number");
else
System.out.println("It is odd number");

}
}
Q) Write a java program to find out given number is odd or not?
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();

if(n%2!=0)
System.out.println("It is odd number");
else
System.out.println("It is not odd number");

}
}
Q) Write a java program to find out given number is positive or negative?

ex:
---
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();

if(n==0)
{
System.out.println("It is not a positive or negative number");
System.exit(0);
}

if(n>0)
System.out.println("It is positive number");
else
System.out.println("It is negative number");

}
}
Q) Write a java program to find out given year is a leap year or not?

import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the year :");
int year=sc.nextInt();

if( (year%4==0 && year%100!=0) || year%400==0)


System.out.println("It is a leap year");
else
System.out.println("It is not a leap year");

}
}
iii) if else if ladder
------------------------
It will execute the source code based on multiple conditions.
syntaX:
-----
if(cond1)
{
- //code to be execute if cond1 is true
}
else if(cond2)
{
- //code to be execute if cond2 is true
}
else if(cond3)
{
- //code to be execute if cond3 is true
}
else
{
- //code to be execute if all conditions are false.
}
kex:
---
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the option :");
int option=sc.nextInt();
if(option==100)
System.out.println("It is police number");
else if(option==103)
System.out.println("It is enquiry number");
else if(option==108)
System.out.println("It is emergency number");
else
System.out.println("Invalid option");
}
}
Q) Write a java program to find out given alphabet is a vowel or not?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the alphabet :");
char ch=sc.next().charAt(0);
if(ch=='a' || ch=='A')
System.out.println("It is a vowel");
else if(ch=='e' || ch=='E')
System.out.println("It is a vowel");
else if(ch=='i' || ch=='I')
System.out.println("It is a vowel");
else if(ch=='o' || ch=='O')
System.out.println("It is a vowel");
else if(ch=='u' || ch=='U')
System.out.println("It is a vowel");
else
System.out.println("It is not a vowel");

}
}
Q) Write a java program to find out given alphabet is a uppercase letter, lowercase letter , digit
or special symbol?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

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


char ch=sc.next().charAt(0);

if(ch>='A' && ch<='Z')


System.out.println("It is uppercase letter");
else if(ch>='a' && ch<='z')
System.out.println("It is lowercase letter");
else if(ch>='0' && ch<='9')
System.out.println("It is digit");
else
System.out.println("It is special symbol");
}
}
Assignment
===========
Q) Write a java program to accept six marks of a student then find out total , average and grade?
i) if average is greater then equals to 70 then A grade.
ii) if average is greater then equals to 50 then B grade.
iii) if average is greater then equals to 35 then C grade.
iv) if average is less the 35 then failed.

ii) while loop


==============
It will execute the source code untill our condition is true.
syntax:
------
while(condition)
{
-
- // code to be execute
-
}
ex:
--
class Test
{
public static void main(String[] args)
{
int i=1;

while(i<=10)
{
System.out.print(i+" "); // infinite 1
}
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
int i=11;
while(i<=10)
{
System.out.print(i+" "); // nothing
}
}
}
Q) Write a java program to display 100 natural numbers?
class Test
{
public static void main(String[] args)
{
int i=1;
while(i<=100)
{
System.out.print(i+" "); //1 2 3 4 5 .... 100
i++;
}
}
}
Q) Write a java program to perform sum of 10 natural numbers?
class Test
{
public static void main(String[] args)
{
int i=1,sum=0;
while(i<=10)
{
sum+=i;
i++;
}
System.out.println(sum);
}
}
Q) Write a java program to find out factorial 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(); //5
int i=n,fact=1;
while(i>=1)
{
fact*=i;
i--;
}
System.out.println(fact);
}
}
Q) Write a java program to display multiplication table 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(); //5
int i=1;
while(i<=10)
{
System.out.println(n+" * "+i+" = "+n*i);
i++;
}
}
}

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


Input:
123
Output:
6
ex:
---.k
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(); //123

int rem,sum=0;
while(n>0)
{
rem=n%10;
sum=sum+rem;
n=n/10;
}
System.out.println(sum);
}
}
Q) Write a java program to find out given number is Armstrong or not?
Input:
153 (1*1*1+5*5*5+3*3*3)(1+125+27)(153)
Output:
It is a armstrong 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(); //153
int temp=n;
int rem,sum=0;
while(n>0)
{
rem=n%10;
sum=sum+rem*rem*rem;
n=n/10;
}
if(temp==sum)
System.out.println("It is a armstrong number");
else
System.out.println("It is not a armstrong number");
}
}
Q) Write a java program to display reverse of a given number?
Input:
123
output:
321
ex:
---
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(); //123
int rem,rev=0;
while(n>0)
{
rem=n%10;
rev=rev*10+rem;
n=n/10;
}
System.out.println(rev);
}
}
Q) Write a java program to find out given number is palindrome or not?

input:
121

output:
It is a palindrome number

ex:

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(); //121

int temp=n;

int rem,rev=0;
while(n>0)
{
rem=n%10;
rev=rev*10+rem;
n=n/10;
}
if(temp==rev)
System.out.println("It is a palindrome number");
else
System.out.println("It is not a palindrome number");
}
}

iii) for loop


===============
It will execute the source code untill our condition is true.

syntax:
------
for(initialization;condition;incrementation/decrementation)
{
-
- //code to be execute
-
}

ex:
---
class Test
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
System.out.print(i+" ");//1 2 3 4 5 6 7 8 9 10
}
}
}

ex:
---
class Test
{
public static void main(String[] args)
{
for(int i=10;i>=1;i--)
{
System.out.print(i+" ");//10 9 8 7 6 5 4 3 2 1
}
}
}

ex:
---
class Test
{
public static void main(String[] args)
{
int sum=0;
for(int i=1;i<=10;i++)
{
sum+=i;
}
System.out.println(sum);//55
}
}

ex:
---
class Test
{
public static void main(String[] args)
{
int sum=0;
for(int i=1;i<=10;i++)
{
if(i%2==0) //2 4 6 8 10
{
sum+=i;
}
}
System.out.println(sum);//30
}
}

ex:
---
class Test
{
public static void main(String[] args)
{
int even=0;
for(int i=1;i<=10;i++)
{
if(i%2==0)
{
even++;
}
}
System.out.println(even);//5
}
}

ex:
--
class Test
{
public static void main(String[] args)
{
for(;;)
{
System.out.print("Hello ");
}
}
}

Q) Write a java program to find out given number is prime or not?

prime numbers :

2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,


43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97.

ex:
---
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();

boolean flag=true;

for(int i=2;i<=n/2;i++)
{
if(n%i==0)
{
flag=false;
break;
}
}
if(flag==true)
System.out.println("It is prime number");
else
System.out.println("It is not prime number");
}
}

Q) Write a java program to display prime numbers from 1 to 100?

eclass Test
{
public static void main(String[] args)
{
for(int n=2;n<=100;n++)
{
boolean flag=true;

for(int i=2;i<=n/2;i++)
{
if(n%i==0)
{
flag=false;
break;
}
}
if(flag==true)
System.out.print(n+" ");
}
}
}

Q) Write a java program to find out given number is perfect or not?

Input:
6

Output:
It is a perfect number

ex:
--
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(); //6

int sum=0;
for(int i=1;i<n;i++)
{
if(n%i==0)
{
sum+=i;
}
}
if(n==sum)
System.out.println("It is perfect number");
else
System.out.println("It is not perfect number");
}
}

Q) Write a java program to find out GCD (Greatest Common Divisor) of two numbers?

Input:
12 18

Output:

class Test
{
public static void main(String[] args)
{
int a=12,b=18,gcd=0;

for(int i=1;i<=a && i<=b;i++)


{
if((a%i==0) && (b%i==0))
{
gcd=i;
}
}
System.out.println("GCD of two numbers is ="+gcd);
}
}

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


fibonacci series : 0 1 1 2 3 5 8

ex:
---
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(); //6

int a=0,b=1,c;
System.out.print(a+" "+b+" ");

for(int i=2;i<=n;i++)
{
c = a + b;
System.out.print(c+" ");
a=b;
b=c;
}
}
}

Loop Patterns
==============
1)
1111
2222
3333
4444

class Test
{
public static void main(String[] args)
{
//rows
for(int i=1;i<=4;i++)
{
//cols
for(int j=1;j<=4;j++)
{
System.out.print(i+" ");
}
//new line
System.out.println();
}
}
}

2)

1234
1234
1234
1234

class Test
{
public static void main(String[] args)
{
//rows
for(int i=1;i<=4;i++)
{
//cols
for(int j=1;j<=4;j++)
{
System.out.print(j+" ");
}
//new line
System.out.println();
}
}
}

3)

****
****
****
****

class Test
{
public static void main(String[] args)
{
//rows
for(int i=1;i<=4;i++)
{
//cols
for(int j=1;j<=4;j++)
{
System.out.print("* ");
}
//new line
System.out.println();
}
}
}

4)
4444
3333
2222
1111

class Test
{
public static void main(String[] args)
{
//rows
for(int i=4;i>=1;i--)
{
//cols
for(int j=1;j<=4;j++)
{
System.out.print(i+" ");
}
//new line
System.out.println();
}
}
}

5)
AAAA
BBBB
CCCC
DDDD

class Test
{
public static void main(String[] args)
{
//rows
for(char i='A';i<='D';i++)
{
//cols
for(char j='A';j<='D';j++)
{
System.out.print(i+" ");
}
//new line
System.out.println();
}
}
}

6)
DDDD
CCCC
BBBB
AAAA

class Test
{
public static void main(String[] args)
{
//rows
for(char i='D';i>='A';i--)
{
//cols
for(char j='A';j<='D';j++)
{
System.out.print(i+" ");
}
//new line
System.out.println();
}
}
}

7)
****
* *
* *
****

class Test
{
public static void main(String[] args)
{
//rows
for(int i=1;i<=4;i++)
{
//cols
for(int j=1;j<=4;j++)
{
if(i==1 || i==4 || j==1 || j==4)
System.out.print("* ");
else
System.out.print(" ");
}
//new line
System.out.println();
}
}
}

8)
*---
-*--
--*-
---*

class Test
{
public static void main(String[] args)
{
//rows
for(int i=1;i<=4;i++)
{
//cols
for(int j=1;j<=4;j++)
{
if(i==j)
System.out.print("* ");
else
System.out.print("- ");
}
//new line
System.out.println();
}
}
}

9)
*---*
-*-*-
--*--
-*-*-
*---*

class Test
{
public static void main(String[] args)
{
//rows
for(int i=1;i<=5;i++)
{
//cols
for(int j=1;j<=5;j++)
{
if(i==j || i+j==6)
System.out.print("* ");
else
System.out.print("- ");
}
//new line
System.out.println();
}
}
}

Mock Test
=========
for loop
--------
1) Write a java program to check given number is prime or not ?
2) Write a java program to display prime numbers from 1 to 100?
3) Write a java program to find out GCD of two numbers?
4) Write a java program to find out fibonacci series of a given number?
5) Write a java program to find out factorial of a given number?

while loop
---------
6) Write a java program to display sum of digits of a give number?
7) Write a java program to find out given number is armstrong or not?
8) Write a java program to display reverse of a given number?
9) Write a java program to find out given number is palindrome or not?

Loop Pattern
------------
10)
*---*
-*-*-
--*--
-*-*-
*---*
Left Side Loop Patterns
=======================
1)

1
22
333
4444

class Test
{
public static void main(String[] args)
{
//rows
for(int i=1;i<=4;i++)
{
//columns
for(int j=1;j<=i;j++)
{
System.out.print(i+" ");
}
//new line
System.out.println("");
}
}
}

2)
4444
333
22
1

class Test
{
public static void main(String[] args)
{
//rows
for(int i=4;i>=1;i--)
{
//cols
for(int j=1;j<=i;j++)
{
System.out.print(i+" ");
}
//new line
System.out.println();
}
}
}

3)

*
**
***
****
***
**
*

class Test
{
public static void main(String[] args)
{
//ascending
//rows
for(int i=1;i<=4;i++)
{
//cols
for(int j=1;j<=i;j++)
{
System.out.print("* ");
}
//new line
System.out.println();
}

//descending
//rows
for(int i=3;i>=1;i--)
{
//cols
for(int j=1;j<=i;j++)
{
System.out.print("* ");
}
//new line
System.out.println();
}
}
}

4)
1
23
456
7890

class Test
{
public static void main(String[] args)
{
int k=1;

//rows
for(int i=1;i<=4;i++)
{
//cols
for(int j=1;j<=i;j++)
{
if(k<=9)
System.out.print(k++ +" ");
else
System.out.print("0 ");
}
//new line
System.out.println();
}

}
}

5)

2
4 6
8 10 12
14 16 18 20

class Test
{
public static void main(String[] args)
{
int k=2;

//rows
for(int i=1;i<=4;i++)
{
//cols
for(int j=1;j<=i;j++)
{
System.out.print(k+" ");
k+=2;
}
//new line
System.out.println();
}

}
}

6)
1
3 5
7 9 11
13 15 17 19

ex:
---
class Test
{
public static void main(String[] args)
{
int k=1;

//rows
for(int i=1;i<=4;i++)
{
//cols
for(int j=1;j<=i;j++)
{
System.out.print(k+" ");
k+=2;
}
//new line
System.out.println();
}

}
}

7)

2
3 5
7 11 13
17 19 23 29

ex:

class Test
{
public static void main(String[] args)
{
int n=2;

//rows
for(int i=1;i<=4;i++)
{
//cols
for(int j=1;j<=i;j++)
{
while(true)
{
boolean flag=true;
for(int k=2;k<=n/2;k++)
{
if(n%k==0)
{
flag=false;
break;
}
}
if(flag==true)
{
System.out.print(n+" ");
n++;
break;
}
else
{
n++;
}
}
}
//new line
System.out.println();
}

}
}

Right Side Loop patterns


========================
1)

1
22
333
4444

class Test
{
public static void main(String[] args)
{
//rows
for(int i=1;i<=4;i++)
{
//space
for(int j=4;j>i;j--)
{
System.out.print(" ");
}

//right side elements


for(int j=1;j<=i;j++)
{
System.out.print(i+" ");
}
//new line
System.out.println();
}

}
}

4)

4444
333
22
1

ex:
---
class Test
{
public static void main(String[] args)
{
//rows
for(int i=4;i>=1;i--)
{
//space
for(int j=4;j>i;j--)
{
System.out.print(" ");
}

//right side elements


for(int j=1;j<=i;j++)
{
System.out.print(i+" ");
}
//new line
System.out.println();
}

}
}

5)

*
**
***
****
***
**
*

class Test
{
public static void main(String[] args)
{
//ascending
//rows
for(int i=1;i<=4;i++)
{
//space
for(int j=4;j>i;j--)
{
System.out.print(" ");
}

//right side elements


for(int j=1;j<=i;j++)
{
System.out.print("* ");
}
//new line
System.out.println();
}
//ascending
//rows
for(int i=3;i>=1;i--)
{
//space
for(int j=4;j>i;j--)
{
System.out.print(" ");
}

//right side elements


for(int j=1;j<=i;j++)
{
System.out.print("* ");
}
//new line
System.out.println();
}

}
}

Pyramid loop patterns


====================
1)
1
121
12321
1234321

class Test
{
public static void main(String[] args)
{
//rows
for(int i=1;i<=4;i++)
{
//space
for(int j=4;j>i;j--)
{
System.out.print(" ");
}
//left side elements
for(int j=1;j<=i;j++)
{
System.out.print(j+" ");
}
//right side elements
for(int j=i-1;j>=1;j--)
{
System.out.print(j+" ");
}
//new line
System.out.println();
}

}
}

2)
1234321
12321
121
1

ex:
---

class Test
{
public static void main(String[] args)
{
//rows
for(int i=4;i>=1;i--)
{
//space
for(int j=4;j>i;j--)
{
System.out.print(" ");
}
//left side elements
for(int j=1;j<=i;j++)
{
System.out.print(j+" ");
}
//right side elements
for(int j=i-1;j>=1;j--)
{
System.out.print(j+" ");
}
//new line
System.out.println();
}

}
}

3)

*
***
*****
*******
*****
***
*

ex:

class Test
{
public static void main(String[] args)
{
//ascending
//rows
for(int i=1;i<=4;i++)
{
//space
for(int j=4;j>i;j--)
{
System.out.print(" ");
}
//left side elements
for(int j=1;j<=i;j++)
{
System.out.print("* ");
}
//right side elements
for(int j=i-1;j>=1;j--)
{
System.out.print("* ");
}
//new line
System.out.println();
}

//descending
//rows
for(int i=3;i>=1;i--)
{
//space
for(int j=4;j>i;j--)
{
System.out.print(" ");
}
//left side elements
for(int j=1;j<=i;j++)
{
System.out.print("* ");
}
//right side elements
for(int j=i-1;j>=1;j--)
{
System.out.print("* ");
}
//new line
System.out.println();
}

}
}

4)
*
* *
* *
* *
* *
* *
*

ex:

class Test
{
public static void main(String[] args)
{
//ascending
//rows
for(int i=1;i<=4;i++)
{
//space
for(int j=4;j>i;j--)
{
System.out.print(" ");
}
//left side elements
for(int j=1;j<=i;j++)
{
if(j==1)
System.out.print("* ");
else
System.out.print(" ");
}
//right side elements
for(int j=i-1;j>=1;j--)
{
if(j==1)
System.out.print("* ");
else
System.out.print(" ");
}
//new line
System.out.println();
}

//descending
//rows
for(int i=3;i>=1;i--)
{
//space
for(int j=4;j>i;j--)
{
System.out.print(" ");
}
//left side elements
for(int j=1;j<=i;j++)
{
if(j==1)
System.out.print("* ");
else
System.out.print(" ");
}
//right side elements
for(int j=i-1;j>=1;j--)
{
if(j==1)
System.out.print("* ");
else
System.out.print(" ");
}
//new line
System.out.println();
}

}
}

Interview Questions
==================
Q) Write a java program to display below loop pattern?

*
*
*****
*
*

class Test
{
public static void main(String[] args)
{
//rows
for(int i=1;i<=5;i++)
{
//cols
for(int j=1;j<=5;j++)
{
if(i==3 || j==3)
System.out.print("* ");
else
System.out.print(" ");
}
//new line
System.out.println();
}

}
}

Q) Write a java program to display below loop pattern?

1 1
12 21
123 321
12344321

class Test
{
public static void main(String[] args)
{
int rows=4;

//rows
for(int i=1;i<=rows;i++)
{
//left side elements
for(int j=1;j<=i;j++)
{
System.out.print(j+" ");
}

//space
for(int j=1;j<=(rows-i)*2;j++)
{
System.out.print(" ");
}
//right side elements
for(int j=i;j>=1;j--)
{
System.out.print(j+" ");
}
//new line
System.out.println();
}

}
}

Q) Write a java program to display pascal triangle element?

1
11
121
1331
14641

ex:

class Test
{
public static void main(String[] args)
{
//rows
for(int i=0;i<5;i++)
{
//space
for(int j=1;j<5-i;j++)
{
System.out.print(" ");
}

int number=1;
for(int k=0;k<=i;k++)
{
System.out.print(number+" ");
number = number * (i-k)/(k+1);
}

//new line
System.out.println();
}
}
}

Note:
-----
If number of iterations are known by the user then we need to use for loop.
If number of iterations are not known by the user then we need to use while loop.
If number of iterations are not known by the user but code must execute atleast for one time then we need to
use do while loop.
4) Jump Statement
==================
Jump statement is used to jump from one section of code to another section.
We have two types of jump statements.
1) break stmt
2) continue stmt
1) break stmt
--------------
It is used to break the execution of loops and switch case.
For conditional statements we can use if condition.
syntax:
------
break;

ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");
break;
System.out.println("stmt2");
}
}
o/p:
C.T.E : break outside switch or loop

ex:
----
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");
if(true)
{
break;
}
System.out.println("stmt2");
}
}

o/p:
C.T.E : break outside switch or loop

ex:
---
class Test
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
if(i==5)
{
break;
}

System.out.print(i+" "); // 1 2 3 4
}
}
}

2) continue stmt
-----------------
It is used to continue the execution of loops.
For conditional statement we can use if condition.
hsyntax:
continue;

ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");
continue;
System.out.println("stmt2");
}
}
o/p:
continue outside of loop
ex:
---
class Test
{
public static void main(String[] args)
{
System.out.println("stmt1");
if(true)
{
continue;
}
System.out.println("stmt2");
}
}
o/p:
C.T.E continue outside of loop

ex:
----
class Test
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
if(i==5)
{
continue;
}
System.out.print(i+" "); //1 2 3 4 6 7 8 9 10
}
}
}
Assignment program
=================

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

Input:
123

Output:
ThreeTwoOne

ex:

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();//123

while(n>0)
{
switch(n%10)
{
case 0 : System.out.print("Zero");break;
case 1 : System.out.print("One");break;
case 2 : System.out.print("Two");break;
case 3 : System.out.print("Three");break;
case 4 : System.out.print("Four");break;
case 5 : System.out.print("Five");break;
case 6 : System.out.print("Six");break;
case 7 : System.out.print("Seven");break;
case 8 : System.out.print("Eight");break;
case 9 : System.out.print("Nine");break;
}
n=n/10;
}

}
}

Various ways to write java methods


===================================
There are four ways to write java methods.
1) No returntype with No argument method
2) No returntype with argument method
3) With returntype with No argument method
4) With returntype with argument method

1) No returntype with No argument method


------------------------------------------
If we don't have arguments then we need to ask input values inside callie method.
Q) Write a java program to perform sum of two numbers with no returntype with no argument method?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
//caller method
sum();
}
//callie method
public static void sum()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first number :");
int a=sc.nextInt();
System.out.println("Enter the second number :");
int b=sc.nextInt();
int c=a+b;
System.out.println("sum of two numbers is ="+c);
}
}

Q) Write a java program to perform factorial of a given number using no returntype with no argument method ?

import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
//caller method
factorial();
}
//callie method
public static void factorial()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number :");
int n=sc.nextInt(); //5

int fact=1;
for(int i=n;i>=1;i--)
{
fact=fact*i;
}
System.out.println("Factorial of a given number is ="+fact);
}
}

2) No returntype with argument method


--------------------------------------
If we have arguments then we need to ask input values inside main method.
Number of arguments depends upon number of inputs.
Q) Write a java program to perform sum of two numbers using no returntype with argument method?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first number :");
int a=sc.nextInt();
System.out.println("Enter the second number :");
int b=sc.nextInt();

//caller method
sum(a,b);
}
//callie method
public static void sum(int a,int b)
{
int c=a+b;
System.out.println("sum of two numbers is ="+c);
}
}

Q) Write a java program to perform cube of a given number using no returntype with argument method?
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();//5

//caller method
cube(n);
}
//callie method
public static void cube(int n)
{
int result=n*n*n;
System.out.println("cube of a given number is ="+result);
}
}
3) With returntype with No argument method
------------------------------------------
Returntype is completely depends on output datatype.

Q) Write a java program to perform sum of two numbers using with returntype with no argument method?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
//caller method
int k=sum();
System.out.println("sum of two numbers is ="+k);
}
//callie method
public static int sum()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first number :");
int a=sc.nextInt();
System.out.println("Enter the second number :");
int b=sc.nextInt();

int c=a+b;

return c;
}
}
Q) Write a java program to perform area of a circle using with return with no argument method?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
//caller method
float k=circle();
System.out.println("Area of a circle is "+k);
}
//callie method
public static float circle()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the radius :");
int r=sc.nextInt();

float area=3.14f*r*r;

return area;
}
}
4) With returntype with argument method
--------------------------------------
Q) Write a java program to perform sum of two numbers using with returntype with argument method?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first number :");
int a=sc.nextInt();
System.out.println("Enter the second number :");
int b=sc.nextInt();
//caller method
System.out.println("sum of two numbers is ="+sum(a,b));
}
//callie method
public static int sum(int a,int b)
{
int c=a+b;
return c;
}
}

Q) Write a java program to check given number is even or odd using with returntype with argument method?

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();//4

//caller method
if(find(n))
System.out.println("It is even number");
else
System.out.println("It is odd number");
}
//callie method
public static boolean find(int n)
{
if(n%2==0)
return true;
else
return false;
}
}

Assignment
==========

Q) Write a java program to check given number is palindrome or not?

Recursion
===========
A method which call itself for many number of times is called recursion.
Recursion is similar to loopings.
Whenever we use recursion then we should not use loops.

Q) Write a java program to display 10 natural numbers without using loops?

class Test
{
public static void main(String[] args)
{
//caller method
display(1);
}
//callie method
public static void display(int i)
{
if(i<=10)
{
System.out.print(i+" ");
display(i+1);
}

}
}

Q) Write a java program to perform sum of two numbers without using arithmetic operator ?
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 number :");


int a=sc.nextInt();

System.out.println("Enter the second number :");


int b=sc.nextInt();

//caller method
System.out.println(sum(a,b));
}
//callie method
public static int sum(int a,int b)
{
if(a==0)
return b;

return sum(--a,++b);
}
}
Q) Write a java program to find out factorial of a given number using recursion?
ex:
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();//5

//caller method
System.out.println(factorial(n));
}
//callie method
public static int factorial(int n)
{
if(n<0)
return -1;
if(n==0)
return 1;

return n*factorial(n-1);
}
}
Q) Write a java program to find out N-th element of fibonacci series?
fibonacci sequence : 0 1 1 2 3 5 8
Input:
4
Output:
2
ex:
---
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();//4
//caller method
System.out.println(fib(n));

}
//callie method
public static int fib(int n)
{
if(n==0 || n==1)
return 0;
if(n==2)
return 1;

return fib(n-1)+fib(n-2);

}
}

Arrays
=======
Array is a collection of homogeneous data elements.
The main advantages of arrays are
1) We can represent multiple elements using single variable name.
ex:
int[] arr={10,20,30};

2) Performance point of view arrays are recommanded to use.


The main disadvantages of arrays are
1) Arrays are fixed in size.Once if we create an array there is no chance of increasing or decreasing the size of
an array.

2) To use array concept in advanced we should known what is the size of an array which is always not
possible.
In java, arrays are divided into three types.
1) Single Dimensional Array
2) Double Dimensional Array
3) Multi Dimensional Array
Array Declaration
------------------
At the time of array declaration we should not specify array size.

ex:
Array
|---------------------------------|--------------------------|
Single Dimensional Array Double Dimensional Array MultiDimensional Array

int[] arr; int[][] arr; int[][][] arr;


int []arr; int [][]arr; int [][][]arr;
int arr[]; int arr[][]; int arr[][][];
int[] []arr; int[] [][]arr;
int[] arr[]; int[] arr[][];
int []arr[]; int[] []arr[];
int[][] []arr;
int[][] arr[];
int [][]arr[];
int []arr[][];

Array Creation
--------------
In java , every array consider as an object.Hence we will use new operator to create an array.

ex:
int[] arr=new int[3];

Diagram: class18.1

Rules to constructor an array


-----------------------------
Rule1:
-----
At the time of array creation compulsary we need to specify array size.
ex:
int[] arr=new int[3];
int[] arr=new int[]; // C.T.E array dimension missing

Rule2:
------
It is legal to have an array size with zero.
ex:
int[] arr=new int[0];
System.out.println(arr.length);//0

Rule3:
------
We can't give negative number as an array size otherwise we will get
NegativeArraySizeException.
ex:
int[] arr=new int[-3]; //R.E NegativeArraySizeException

Rule4:
-----
The allowed datatype for an array size is byte,short,int and char.
If we take other datatypes then we will get compile time error.
ex:
byte b=10;
int[] arr=new int[b];

int[] arr=new int['a'];

int[] arr=new int[10.5d]; // C.T.E

Rule5:
-----
The maximum size we can take for an array size is maximum length of int.
ex:
int[] arr=new int[2147483647];

Array Initialization
--------------------
Whenever we create an array , every array element will be initialized with default values.
If we are not happy with default values then we can change those values with customized values.
Diagram: java18.2
Array Declaration , Creation and Initialization using single line
-------------------------------------------------------------------
int[] arr;
arr=new int[3];
arr[0]=10;
arr[1]=20;
arr[2]=30; ==> int[] arr={10,20,30};
char[] carr={'a','b','c'};
String[] sarr={"hi","hello","bye"};

Q) What is the difference between length and length() ?

length length()
------------ -----------
It is a final variable which is applicable It is a final method which is applicable
only for arrays. only for String objects.

It will return size of an array. It will return number of characters present in


string.

ex: ex:
-- ---
int[] arr=new int[3]; String str="bhaskar";
System.out.println(arr.length);//3 System.out.println(str.length());//7

Single Dimensional Array


=======================
ex:
---
class Test
{
public static void main(String[] args)
{
int[] arr=new int[3];
//for each loop
for(int i:arr)
{
System.out.print(i+" ");
}

ex:
---
class Test
{
public static void main(String[] args)
{
int[] arr=new int[3];
arr[0]=10;
arr[1]=20;
arr[2]=30;

//for each loop


for(int i:arr)
{
System.out.print(i+" ");
}

}
ex:
---

class Test
{
public static void main(String[] args)
{
int[] arr={10,20,30};

//for each loop


for(int i:arr)
{
System.out.print(i+" ");
}

Note:
------
For each loop is used to iterate the elements from array.

ex:
---
class Test
{
public static void main(String[] args)
{
int[] arr={10,20,30};

for(int i=0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}

}
t
Q) Write a java program to insert some array element and display them?
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the array size :");
int size=sc.nextInt();//5

int[] arr=new int[size];

//inserting elements
for(int i=0;i<arr.length;i++)
{
System.out.println("Enter the element :");
arr[i]=sc.nextInt();
}

//display elements
for(int i=0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}
}
}

Q) Write a java program to display array elements in reverse order?


input:
629135

output:
531926

class Test
{
public static void main(String[] args)
{
int[] arr={6,2,9,1,3,5};

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

Q) Write a java program to perform sum of array elements?

input:
629135

output:
26

ex:

class Test
{
public static void main(String[] args)
{
int[] arr={6,2,9,1,3,5};
int sum=0;

for(int i:arr)
{
sum+=i;
}

System.out.println(sum);
}
}

Q) Write a java program to display even elements from given array?

input:
629135

output:
62

ex:
---
class Test
{
public static void main(String[] args)
{
int[] arr={6,2,9,1,3,5};

for(int i:arr)
{
if(i%2==0)
{
System.out.print(i+" ");
}
}
}
}

Q) Write a java program to display number of evens and odd elements?

input:
629135

output:
Even elements : 2
Odd elements : 4

ex:

class Test
{
public static void main(String[] args)
{
int[] arr={6,2,9,1,3,5};

int even=0,odd=0;

for(int i:arr)
{
if(i%2==0)
{
even++;
}
else
{
odd++;
}
}
System.out.println("Even elements :"+even);
System.out.println("odd elements :"+odd);
}
}
Q) Write a java program to display prime elements from given array?

input:
4 2 8 7 9 11 21 12

output:
2 7 11

ex:

class Test
{
public static void main(String[] args)
{
int[] arr={4,2,8,7,9,11,21,12};

for(int n:arr)
{
boolean flag=true;
for(int i=2;i<=n/2;i++)
{
if(n%i==0)
{
flag=false;
break;
}
}
if(flag==true)
System.out.print(n+" ");
}
}
}

Q) Write a java program to display array elements in sorting order?


input:
629154

output:
124569

ex:

import java.util.Arrays;
class Test
{
public static void main(String[] args)
{
int[] arr={6,2,9,1,5,4};

Arrays.sort(arr);

for(int i:arr)
{
System.out.print(i+" ");
}
}
}

Q) Write a java program to display array elements in sorting order without using sort() method?

input:
629154

output:
124569

ex:
--

class Test
{
public static void main(String[] args)
{
int[] arr={6,2,9,1,5,4};

//ascending logic
for(int i=0;i<arr.length;i++)
{
for(int j=0;j<arr.length;j++)
{
if(arr[i]<arr[j])
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
for(int i:arr)
{
System.out.print(i+" ");
}
}
}

Q) Write a java program to display array elements in descending order ?

input:
629154

output:
965421

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

Arrays.sort(arr);//1 2 4 5 6 9

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

}
}

Q) Write a java program to display array elements in descending order without using sort() method ?

input:
629154

output:
965421

ex:

class Test
{
public static void main(String[] args)
{
int[] arr={6,2,9,1,5,4};

//descending order
for(int i=0;i<arr.length;i++)
{
for(int j=0;j<arr.length;j++)
{
if(arr[i]>arr[j])
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}

//reading elements
for(int i:arr)
{
System.out.print(i+" ");
}

}
}

Q) Write a java program to display highest element from given array?

input:
629154

output:
9

ex:

import java.util.Arrays;
class Test
{
public static void main(String[] args)
{
int[] arr={6,2,9,1,5,4};

Arrays.sort(arr);//1 2 4 5 6 9

System.out.println(arr[arr.length-1]);
}
}

Q) Write a java program to display highest element from given array without using sort() method?

input:
629154

output:
9

class Test
{
public static void main(String[] args)
{
int[] arr={6,2,9,1,5,4};

int big=arr[0];

for(int i:arr)
{
if(i>big)
{
big=i;
}
}
System.out.println("Highest element is ="+big);

}
}
Q) Write a java program to display least element from given array ?

input:
629154

output:
1

ex:

import java.util.Arrays;
class Test
{
public static void main(String[] args)
{
int[] arr={6,2,9,1,5,4};

Arrays.sort(arr);//1 2 4 5 6 9

System.out.println(arr[0]);
}
}

Q) Write a java program to display least element from given array without using sort() method ?

input:
629154

output:
1

class Test
{
public static void main(String[] args)
{
int[] arr={6,2,9,1,5,4};

int small=arr[0];

for(int i:arr)
{
if(i<small)
{
small=i;
}
}
System.out.println(small);
}
}

Q) Write a java program to display three highest elements from given array?

input:
47196283

output:
987

class Test
{
public static void main(String[] args)
{
int[] arr={4,7,1,9,6,2,8,3};

int firstElement=Integer.MIN_VALUE;
int secondElement=Integer.MIN_VALUE;
int thirdElement=Integer.MIN_VALUE;
for(int i:arr)
{
if(i>firstElement)
{
thirdElement=secondElement;
secondElement=firstElement;
firstElement=i;
}
else if(i>secondElement)
{
thirdElement=secondElement;
secondElement=i;
}
else if(i>thirdElement)
{
thirdElement=i;
}
}
System.out.println(firstElement+" "+secondElement+" "+thirdElement);
}
}

Q) Write a java program to segregate array elements?

input:
1010011010

output:
0000011111

ex:
class Test
{
public static void main(String[] args)
{
int[] arr={1,0,1,0,0,1,1,0,1,0};

int[] resArr=new int[arr.length];

//inserting '0'
int j=0;
for(int i:arr)
{
if(i==0)
{
resArr[j++]=i;
}
}

//inserting '1'
while(j<arr.length)
{
resArr[j++]=1;
}

//display elements
for(int i:resArr)
{
System.out.print(i+" ");
}

}
}
Q) Write a java to add two array elements and store them in third array?

input:
arr1 = 1 6 9 4 2
arr2 = 8 2 7 3 6

output:
9 8 16 7 8
ex:
---
class Test
{
public static void main(String[] args)
{
int[] arr1 ={1,6,9,4,2};
int[] arr2 ={8,2,7,3,6};

int[] resArr=new int[arr1.length];

for(int i=0;i<arr1.length && i<arr2.length;i++)


{
resArr[i]=arr1[i]+arr2[i];
}

//display the elements


for(int i:resArr)
{
System.out.print(i+" ");
}

}
}

Q) Write a java program to merge two array and display them in sorting order?

input:
arr1 = 5 1 3 4 2
arr2 = 9 6 8 7 10

output:
1 2 3 4 5 6 7 8 9 10

ex:
---
import java.util.Arrays;
class Test
{
public static void main(String[] args)
{
int[] arr1 ={5,1,3,4,2};
int[] arr2 ={9,6,8,7,10};

int size1=arr1.length;
int size2=arr2.length;

arr1=Arrays.copyOf(arr1,size1+size2);

int j=0;
for(int i=size1;i<arr1.length;i++)
{
arr1[i]=arr2[j++];
}

Arrays.sort(arr1);

//display the elements


for(int i:arr1)
{
System.out.print(i+" ");
}

}
}

Q) Write a java program to find out missing element from given array?

input:
157263
output:
4

ex:
---
class Test
{
public static void main(String[] args)
{
int[] arr={1,5,7,2,6,3};

int sum_of_arr_ele=arr.length+1;

int sum=(sum_of_arr_ele*(sum_of_arr_ele + 1))/2;

for(int i:arr)
{
sum=sum-i;
}
System.out.println(sum);
}
}

Q) Write a java program to display duplicate elements from given array?

input:
571395372

output:
573

class Test
{
public static void main(String[] args)
{
int[] arr={5,7,1,3,9,5,3,7,2};

//duplicates
for(int i=0;i<arr.length;i++)
{
for(int j=i+1;j<arr.length;j++)
{
if(arr[i]==arr[j])
{
System.out.print(arr[i]+" ");
}
}
}
}
}

Q) Write a java program to display unique elements from given array?

input:
571395372

output:
192

ex:

class Test
{
public static void main(String[] args)
{
int[] arr={5,7,1,3,9,5,3,7,2};

//uniques
for(int i=0;i<arr.length;i++)
{
int cnt=0;

for(int j=0;j<arr.length;j++)
{
if(arr[i]==arr[j])
{
cnt++;
}
}
if(cnt==1)
System.out.print(arr[i]+" ");
}
}
}

Q) Write a java program to find out most repeating element from given array?

input:
528921627247

output:
2 is repeating for 4 times

ex:

class Test
{
public static void main(String[] args)
{
int[] arr={5,2,8,9,2,1,6,2,7,2,4,7};

int element=0;
int maxCount=0;

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

for(int j=0;j<arr.length;j++)
{
if(arr[i]==arr[j])
{
cnt++;
}
}
if(maxCount<cnt)
{
maxCount=cnt;
element=arr[i];
}
}

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


}
}

Q) Write a java program to find out leader element from given array?

input:
4 9 34 5 12 1 9

output:
9 12 34

ex:
class Test
{
public static void main(String[] args)
{
int[] arr={4,9,34,5,12,1,9};
int max=arr[arr.length-1];

System.out.print(max+" ");

for(int i=arr.length-2;i>=0;i--)
{
if(arr[i]>max)
{
max=arr[i];
System.out.print(max+" ");
}
}

}
}

Q) Write a java program to display pair of array elements equals to sum ?

input:
arr = 3 6 1 4 9 2 7
sum = 10
output:
37
64
19

ex:

class Test
{
public static void main(String[] args)
{
int[] arr={3,6,1,4,9,2,7};
int sum=10;

for(int i=0;i<arr.length;i++)
{
for(int j=i+1;j<arr.length;j++)
{
if(arr[i]+arr[j]==sum)
{
System.out.println(arr[i]+" "+arr[j]);
}
}
}
}
}

Q) Write a java program to display triplet of array elements equals to sum ?

input:
arr = 3 6 1 4 9 2 7
sum = 10
output:
361
127

ex:
class Test
{
public static void main(String[] args)
{
int[] arr={3,6,1,4,9,2,7};
int sum=10;

for(int i=0;i<arr.length;i++)
{
for(int j=i+1;j<arr.length;j++)
{
for(int k=j+1;k<arr.length;k++)
{
if(arr[i]+arr[j]+arr[k]==sum)
{
System.out.println(arr[i]+" "+arr[j]+" "+arr[k]);
}
}
}
}

}
}

Q) Write a java program to delete first occurance of a given element?

input:
arr = 5 2 9 1 2 6 7 2
element = 2

output:
5912672

class Test
{
public static void main(String[] args)
{
int[] arr ={5,2,9,1,2,6,7,2};
int element=2;

int cnt=0;
for(int i:arr)
{
if(i==element && cnt==0)
{
cnt=1;
continue;
}
System.out.print(i+" ");
}
}
}

Q) Write a java program to insert element on given index?

input:
arr = 6 2 9 1 4 3 7
index = 3
element = 10

output:
6 2 9 10 1 4 3 7

import java.util.Arrays;
class Test
{
public static void main(String[] args)
{
int[] arr ={6,2,9,1,4,3,7};
int index = 3;
int element=10;

arr=Arrays.copyOf(arr,arr.length+1);

for(int i=arr.length-1;i>=index;i--)
{
arr[i]=arr[i-1];
}
arr[index]=element;

//display
for(int i:arr)
{
System.out.print(i+" ");
}
}
}

Q) Write a java program to identify and print all elements in an array that are greater
than both their immediate predecessors and successors, considering the first and
last elements as having only one neighbor?

Input:
1 3 20 4 75 0 90
Output:
20 75 90

ex:

class Test
{
public static void main(String[] args)
{
int[] arr={1,3,20,4,75,0,90};

//first element
if(arr[0]>arr[1])
{
System.out.print(arr[0]+" ");
}

//middle elements
for(int i=1;i<arr.length-1;i++)
{
if(arr[i]>arr[i-1] && arr[i]>arr[i+1])
{
System.out.print(arr[i]+" ");
}
}
//last element
if(arr[arr.length-1]>arr[arr.length-2])
{
System.out.print(arr[arr.length-1]);
}
}
}

Q)
Write a java program to determine the smallest number of coins needed to total
86 rupees. Use the denominations provided in the array {1,2,5,10}?

Output:
1 coin(s) of 1 rupee(s)
1 coin(s) of 5 rupee(s)
8 coin(s) of 10 rupee(s)

ex:

class Test
{
public static void main(String[] args)
{
int[] denominations={1,2,5,10};
int amount=86;
//caller method
int[] result=findMinimumCoins(denominations,amount);

for(int i=0;i<result.length;i++)
{
if(result[i]>0)
{
System.out.println(result[i]+" coin(s) of "+denominations[i]+" rupee(s)");
}
}

}
//callie method
public static int[] findMinimumCoins(int[] denominations,int amount)
{
int[] coinsCount=new int[denominations.length];

for(int i=denominations.length-1;i>=0;i--)
{
coinsCount[i]=amount/denominations[i];

amount%=denominations[i];
}

return coinsCount;
}
}

Double Dimensional Array


========================
Double dimensional array is a combination of rows and columns.

Double dimensional array is implemented based on array or arrays approach but not matrix form.F

Double dimensional array is used to develop matrix type of applications, gaming applications , business
oriented applications and etc.

The main objective of double dimensional array is a memory utilization.

We can declare double dimensional array as follow.

ex: rows columns


| |
int[][] arr=new int[3][3];
Here we can store 9 elements.

Q) Write a java program to display array elements in matrix form?

import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the rows :");
int rows=sc.nextInt();

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


int cols=sc.nextInt();

int[][] arr=new int[rows][cols];

//insert elements
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
System.out.println("Enter the element :");
arr[i][j]=sc.nextInt();
}
}

//display elements
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
System.out.print(arr[i][j]+" ");
}
//new line
System.out.println();
}
}
}

Q) Write a java program to display square of a matrix?

input:
123
456
789

output:
1 4 9
16 25 36
49 64 81

ex:

class Test
{
public static void main(String[] args)
{
int[][] arr={
{1,2,3},
{4,5,6},
{7,8,9}
};

for(int i=0;i<arr.length;i++)
{
for(int j=0;j<arr[0].length;j++)
{
System.out.print(arr[i][j] * arr[i][j]+" ");
}
//new line
System.out.println();
}
}
}

Q) Write a java program to perform sum of diagonal elements?

class Test
{
public static void main(String[] args)
{
int[][] arr={
{1,2,3},
{4,5,6},
{7,8,9}
};

int sum=0;
for(int i=0;i<arr.length;i++)
{
for(int j=0;j<arr[0].length;j++)
{
if(i==j)
{
sum+=arr[i][j];
}
}
}

System.out.println("sum of diagonal elements :"+sum);


}
}

Q) Write a java program to perform sum of upper triangle elements?

class Test
{
public static void main(String[] args)
{
int[][] arr={
{1,2,3},
{4,5,6},
{7,8,9}
};

int sum=0;
for(int i=0;i<arr.length;i++)
{
for(int j=0;j<arr[0].length;j++)
{
if(i<j)
{
sum+=arr[i][j];
}
}
}

System.out.println("sum of upper triangle elements :"+sum);


}
}

Q) Write a java program to display lower triangle elements ?


class Test
{
public static void main(String[] args)
{
int[][] arr={
{1,2,3},
{4,5,6},
{7,8,9}
};

int sum=0;
for(int i=0;i<arr.length;i++)
{
for(int j=0;j<arr[0].length;j++)
{
if(i>j)
{
sum+=arr[i][j];
}
}
}

System.out.println("sum of lower triangle elements :"+sum);


}
}

Q) Write a java program to display array elements in spiral form?

input:
123
456
789

output:
123698745

ex:

class Test
{
public static void main(String[] args)
{
int[][] matrix={
{1,2,3},
{4,5,6},
{7,8,9}
};

int rows=matrix.length;
int cols=matrix[0].length;

int top=0;
int bottom=rows-1;
int left=0;
int right=cols-1;

while(true)
{
if(left>right)
{
break;
}

for(int i=left;i<=right;i++)
{
System.out.print(matrix[top][i]+" ");
}
top++;

if(top>bottom)
{
break;
}
for(int i=top;i<=bottom;i++)
{
System.out.print(matrix[i][right]+" ");
}
right--;

if(left>right)
{
break;
}

for(int i=right;i>=left;i--)
{
System.out.print(matrix[bottom][i]+" ");
}
bottom--;

if(top>bottom)
{
break;
}
for(int i=bottom;i>=top;i--)
{
System.out.print(matrix[i][left]+" ");
}
left++;
}
}
}

Anonymous Array
===============
Sometimes we will declare an array without name such type of nameless array is called anonymous array.

The main objective of anonymous array is just for instance use.

We can declare anonymous array as follow.

ex:
new int[]{10,20,30};
new int[][]{{10,20,30},{40,50,60}};

ex:
---
class Test
{
public static void main(String[] args)
{
//caller method
sum(new int[]{10,20,30});
}
//callie method
public static void sum(int[] arr)
{
int sum=0;
for(int i:arr)
{
sum+=i;
}
System.out.println(sum);
}
}

ex:
---
class Test
{
public static void main(String[] args)
{
//caller method
System.out.println(sum(new int[]{10,20,30}));
}
//callie method
public static int sum(int[] arr)
{
int sum=0;
for(int i:arr)
{
sum+=i;
}
return sum;
}
}

Q) Write a java program to display array elements in sorting order?

input:
47139

output:
13479

class Test
{
public static void main(String[] args)
{
//code here
}
//callie method
public static int[] sort(int[] arr)
{
//code here
}
}

solution
----------
import java.util.Arrays;
class Test
{
public static void main(String[] args)
{
int[] arr={4,7,1,3,9};

//caller method
int[] result=sort(arr);

//display the elements from result array


for(int i:result)
{
System.out.print(i+" ");
}
}
//callie method
public static int[] sort(int[] arr)
{
Arrays.sort(arr);

return arr;
}
}

Assignment
==========

Q) Write a java program to find out second highest element from given array?

Input:
6 9 1 4 7 5 2

output:
7
class Test
{
public static void main(String[] args)
{
//code here
}
//callie method
public static int sort(int[] arr,int size)
{
//code here

return secondElement;
}
}

OOPS
=====
OOPS stands for Object Oriented Programming System/Structure.
OOPS are used to deal with real world entities using programming language.
OOPS contains following features.
ex:
class
object
Abstraction
Encapsulation
Inheritance
Polymorphism
Object oriented technology
--------------------------
A technology which provides very good environment to represent our data in the form of objects is called
object oriented technology.
class
======
A class is a blue print of an object.
A class is a collection of objects.
A class is a logical entity.
We can declare a class as follow.
syntax:
optional
|
modifier class class_name <extends> Parent_classname
<implements> Interface_name
{
-
- // variables
- // methods
-
}

A class will accept following modifiers.


ex:
default
public
final
abstract
Realtime example :
----------------
To construct a building we required a design.
That design is called blue print i.e class.
Q) What is the difference between default class and public class?
default class public class
----------------- --------------
To declare a default class we should not To declare a public class we should use
use any modifier. public modifier.
ex: ex:
class A public class A
{ {
} }

If we declare any class default then we If we declare any class as public then we
can access that class within the package. can access that class within the package and
outside the package.
Q) What is the difference between final class and abstract class?
final class abstract class
------------- ---------------
To declare final class we will use final To declare abstract class we will use abstract
modifier. modifier.
ex: ex:
final class A abstract class A
{ {

} }
Child creation is not possible. Child creation is possible.
Object creation is possible. Object creation is not possible.
object
======
It is a outcome of a blue print.
It is a instance of a class.
Here instance means allocating memory of our data members.
It is a collection of properties and behaviours.
It is a physical entity.
realtime example
---------------
Dog (object)
|
|----------------------------------------------|
properties behaviours

Name barking
Breed bitting
Color eating
Age running
Height sleeping
Weight and etc.
and etc

We can declare object as follow.


ex:
classname operator
| |
Test t = new Test();
| |
reference variable constructor

It is possible to create more then one object in a single class.

ex:
----
class Test
{
public static void main(String[] args)
{
Test t1=new Test();
Test t2=new Test();
Test t3=new Test();

System.out.println(t1.hashCode());
System.out.println(t2.hashCode());
System.out.println(t3.hashCode());

System.out.println(t1); //Test@Hexadecimanumber
System.out.println(t2.toString());
System.out.println(t3.toString());
}
}
Q) What is hash code in java?
For every object, JVM will create a unique identification number i.e hash code.
In order to read hash code of an object we need to use hashCode() method of Object class.
Diagram: java23.1
Q) What is toString() method?
A toString() method present in Object class.
Whenever we are trying to display any object reference , directly or indirectly toString() method will be
executed.
Q) What is Object class?
Object class consider as parent class for every java class.
Object class present in java.lang package.
Object class contains following methods.
ex:
cmd> javap java.lang.Object
hashCode()
toString()
wait()
notify()
notifyAll()
getClass()
and etc.
Q) What is the difference between class and object?
class object
---------- ---------
It is a blue print of an object. It is a instance of a class.
It is a logical entity. It is a physical entity.
It does not allocate memory. It allocates memory.
It does not manipulate. It manipulates.
It declares only once. It declares many times.
To declare a class we will use class keyword. To declare object we will use new keyword.
Data Hiding
===========
The process of hiding object data from the outsider is called data hiding.
The main objective of data hiding is to provide security.
Using "private" modifier we can implements data hiding concept.
ex:
---
class Account
{
private double balance=5000d;
}
class Test
{
public static void main(String[] args)
{
Account account=new Account();
System.out.println(account.balance);
}
}
Abstraction
============
Hiding internal implementation and highlighting the set of services is called abstraction.
Using abstract classes and interfaces we can implements abstraction.
The best example of abstraction is GUI ATM machine where bank people will hide internal implementation and
highlights the set of services like banking, withdrawl, mini statement and etc.
The main advatages of abstraction are
1) It gives security because it will hide internal implementation from outsider.
2) Enhancement becomes more easy without effecting enduser they can perform any changes in our internal
system.
3) It provides flexibility to the enduser to use the system.
4) It improves maintainability of an application.
In realtime we will use abstraction to hide the data.

Encapsulation
==============
The process of encapsulating or grouping variables and it's associate methods in a single unit is called
encapsulation.
Diagram: java24.1

In realtime encapsulation is used to protect the data.


A class is said to be encapsulated class if it supports data hiding and abstraction.
In encapsulation for every variable we need to write setter and getter method.
Diagram: java24.2
The main advantages of encapsulation are.
1) It gives security.
2) Enhancement becomes more easy.
3) It provides flexibility to the enduser.
4) It improves maintainability of an application.
The main disadvantage of encapsulation is , it will increase length of our code and slowdown the
execution process.
ex:
----
class Student
{
private int studId;
private String studName;
private double studFee;

//setter methods
public void setStudId(int studId)
{
this.studId=studId;
}
public void setStudName(String studName)
{
this.studName=studName;
}
public void setStudFee(double studFee)
{
this.studFee=studFee;
}

//getter methods
public int getStudId()
{
return studId;
}
public String getStudName()
{
return studName;
}
public double getStudFee()
{
return studFee;
}

class Test
{
public static void main(String[] args)
{
Student s=new Student();

s.setStudId(101);
s.setStudName("Alan");
s.setStudFee(1000d);

System.out.println("Student Id :"+s.getStudId());
System.out.println("Student Name :"+s.getStudName());
System.out.println("Student Fee :"+s.getStudFee());
}
}
Q) What is the difference between Abstraction and Encapsulation?
Abstraction Encapsulation
----------- ----------------
Hiding internal implementation and highlighting The process of encapsulating or grouping variables
the set of services is called abstraction. and its associate methods in a single unit is
called encapsulation.
It is used to hide the data. It is used to protect the data.
Using abstract classes and interfaces we can Using access modifiers we can implements
implements abstraction. encapsulation.

It is a process of gaining the information. It is a process of containing the information.

It solves an issue at design level. It solves an issue at implementation level.

Q) What is the difference beteen POJO and Java Bean class?


POJO Java Bean
---------- -------------
It can’t be serialized. It can be serialized.
Fields can have any visibility. Fields can have only private visibility.
There may or may not have 0-arg constructor. It must have 0-argument constructor.
It does not extend any other class. It can extends.
It does not implement any other interface. It can implements.
It does not use any outside annotation. It uses outside annotation.
Java bean example
--------------------
class Student implements java.io.Serializable
{
private int studId;
private String studName;
private double studFee;

//zero-argument constructor
Student()
{
System.out.println("0-arg const");
}

//setter methods
public void setStudId(int studId)
{
this.studId=studId;
}
public void setStudName(String studName)
{
this.studName=studName;
}
public void setStudFee(double studFee)
{
this.studFee=studFee;
}

//getter methods

public int getStudId()


{
return studId;
}
public String getStudName()
{
return studName;
}
public double getStudFee()
{
return studFee;
}

Is-A relationship
=================
Is-A relationship is also known as inheritance.
Using "extends" keyword we can implements Is-A relationship.
The main objective of Is-A relationship is to provide reusability.
ex:
---
class Honda
{
public void price()
{
System.out.println("Honda-price method");
}
}
class HondaAmaze extends Honda
{
public void model()
{
System.out.println("HondaAmaze-Model method");
}
}
class Customer
{
public static void main(String[] args)
{
Honda h=new Honda();
h.price(); //Honda-price method

HondaAmaze ha=new HondaAmaze();


ha.price(); //Honda-price method
ha.model(); //HondaAmaze-Model method

Honda h1=new HondaAmaze();


h1.price(); // Honda-price method

HondaAmaze ha1=new Honda(); //invalid


}
}
conclusion
---------
Whenever our parent having properties bydefault it comes to child.But whatever our child is having properties
it never goes back to parent.
A parent reference can hold child object but child reference can't hold parent object.

Inheritance
============
Inheritance is a mechanism in which we derived a class in the presence of existing class.
Inheritance is a mechanism in which one class will inherit the properties of another class.
The main object of inheritance is to achieve reusability.
Diagram: java25.1

Using "extends" keyword we can implements inheritance.


In java, we have five types of inheritance.
1) Single Level inheritance
2) Multi level inheritance
3) Multiple inheritance
4) Hierarchical inheritance
5) Hybrid inheritance

1) Single Level inheritance


----------------------------
If we derived a class in the present of one base class is called single level inheritance.
Diagram:
A (Parent / Base / Super class)
|
|
|
B (Child / Sub / Derived class)
ex:
---
class A
{
public void m1()
{
System.out.println("M1-Method");
}
}
class B extends A
{
public void m2()
{
System.out.println("M2-Method");
}
}
class Test
{
public static void main(String[] args)
{
A a=new A();
a.m1();

B b=new B();
b.m1();
b.m2();

}
}

ex:
---
class A
{
int i=10;
}
class B extends A
{
int j=20;
}
class Test
{
public static void main(String[] args)
{
A a=new A();
System.out.println(a.i); //10

B b=new B();
System.out.println(b.i+" "+b.j);//10 20

}
}
2) Multi level inheritance
---------------------------
If we derived a class in the presence of one base class and that class is derived from another base class is
called multi level inheritance.
Diag:
A
|
|
|
B
|
|
|
C

Ex class A
{
public void m1()
{
System.out.println("M1-Method");
}
}
class B extends A
{
public void m2()
{
System.out.println("M2-Method");
}
}
class C extends B
{
public void m3()
{
System.out.println("M3-Method");
}
}
class Test
{
public static void main(String[] args)
{
A a=new A();
a.m1();

B b=new B();
b.m1();
b.m2();

C c=new C();
c.m1();
c.m2();
c.m3();

}
}
3) Multiple inheritance
-----------------------
In java, we can't extends more then one class simulteneously because java does not support multiple
inheritance.
ex:
class A
{
}
class B
{
}
class C extends A,B --> invalid
{
}
Interface can extends more then one interface.Hence we can achieve multiple inheritance concept through
interfaces.
ex:
interface A
{
}
interface B
{
}
interface C extends A,B
{
}
If our class does not extends any other class then it is a direct child class of Object class.
ex: diag:

class A Object
{ |
|
} A

If our class extends some other class then our class is a indirect child class of Object class.

ex: diag:

class A Object
{ |
|
} |
class B extends A A
{ |
|
} |
B

Java does not support cyclic inheritance.


ex:
class A extends B
{
}
class B extends A
{
}
Q) Why Java does not support multiple inheritance?
There is a chance of raising ambiguity problem that's why java does not support multiple inheritance.
Diagram:
p1.m1() p2.m1()
|---------------------------------------------|
|
c.m1();

4) Hierarchical inheritance
---------------------------
If we derived multiple classes by using one base class is called hierarchical inheritance.

Diag:
A
|
|-------------------------------|
B C

ex:
---
class A
{
public void m1()
{
System.out.println("M1-Method");
}
}
class B extends A
{
public void m2()
{
System.out.println("M2-Method");
}
}
class C extends A
{
public void m3()
{
System.out.println("M3-Method");
}
}
class Test
{
public static void main(String[] args)
{
A a=new A();
a.m1();

B b=new B();
b.m1();
b.m2();

C c=new C();
c.m1();
c.m3();

}
}
5) Hybrid inheritance
------------------------
Hybrid inheritance is a combination of more then one inheritance.
Java does not support hybrid inheritance.
Diag:
A
|
|-------------------------------|
B C
|-------------------------------|
|
D

Has-A relationship
===================
Has-A relationship is also known as composition and aggregation.
There is no specific keyword to implements Has-A relationship but mostly we will use new operator.
The main objective of Has-A relationship is to provide reusability.
Has-A relationship will increase dependency between two components.
ex:
----
class Engine
{
-
- //engine specific functionality
-
}
class Car
{
Engine e=new Engine();
-
-
}

ex:
---
class Ihub
{
public String courseName()
{
return "Full Stack Java Development";
}
public double courseFee()
{
return 30000d;
}
public String trainerName()
{
return "Niyaz Sir";
}
}
class Usha
{
public void getCourseDetails()
{
Ihub i=new Ihub();
System.out.println("Course Name :"+i.courseName());
System.out.println("Course Fee :"+i.courseFee());
System.out.println("Trainer Name :"+i.trainerName());
}
}
class Student
{
public static void main(String[] args)
{
Usha u=new Usha();
u.getCourseDetails();
}

Composition
===========
Without existing container object there is no chance of having contained object then the relationship between
container and contained object is called composition which is strongly association.
Diagram: java25.2

Aggregation
===========
Without existing container object there is a chance of having contained object then the relationship between
container and contained object is called aggregation which is loosely association.
Diagram: java25.3

Method Overloading
===================
Having same method name with different parameters/signatures in a single class is called method overloading.
Methods which are present in a class are called overloaded methods.
Method overloading will reduce complexity of the programming.
ex:
---
class MeeSeva
{
//overloaded methods
public void search(int voterId)
{
System.out.println("Details Found via voterId");
}
public void search(String houseNo)
{
System.out.println("Details Found via houseNo");
}
public void search(long aadharNo)
{
System.out.println("Details Found via aadharNo");
}
}
class Test
{
public static void main(String[] args)
{
MeeSeva ms=new MeeSeva();
ms.search(1001);
ms.search("1-4-76/A/1");
ms.search(22222L);
}
}
Q) Can we overload main method in java?
Yes, we can overload main method in java but JVM always execute main method with String[] parameter only.
ex:
class Test
{
public static void main(int[] iargs)
{
System.out.println("int arg method");
}
public static void main(String[] args)
{
System.out.println("String arg method");
}
}

Method Overriding
=================
Having same method name with same argument in two different classes is called method overriding.
Methods which are present in parent class are called overridden methods.
Methods which are present in child class are called overriding methods.
ex:
----
class Parent
{
public void property()
{
System.out.println("cash+gold+land");
}
//overridden methods
public void marry()
{
System.out.println("Subhalakshmi");
}
}
class Child extends Parent
{
//overriding methods
public void marry()
{
System.out.println("Rashmika");
}
}
class Test
{
public static void main(String[] args)
{
Parent p=new Parent();
p.property(); //cash+gold+land
p.marry(); // Subhalakshmi

Child c=new Child();


c.property(); //cash+gold+land
c.marry(); // Rashmika

Parent p1=new Child();


p1.property(); // cash+gold+land
p1.marry(); //Rashmika
}
}
If we declare any method as final then overriding of that method is not possible.
ex:
---
class Parent
{
public void property()
{
System.out.println("cash+gold+land");
}
//overridden methods
public final void marry()
{
System.out.println("Subhalakshmi");
}
}
class Child extends Parent
{
//overriding methods
public void marry()
{
System.out.println("Rashmika");
}
}
class Test
{
public static void main(String[] args)
{
Parent p=new Parent();
p.property(); //cash+gold+land
p.marry(); // Subhalakshmi

Child c=new Child();


c.property(); //cash+gold+land
c.marry(); // Rashmika

Parent p1=new Child();


p1.property(); // cash+gold+land
p1.marry(); //Rashmika
}
}
o/p:
C.T.E
private methods can't be override in java.
ex:
---
class Parent
{
public void property()
{
System.out.println("cash+gold+land");
}
private void marry()
{
System.out.println("Subhalakshmi");
}
}
class Child extends Parent
{
//overriding methods
public void marry()
{
System.out.println("Rashmika");
}
}
class Test
{
public static void main(String[] args)
{
Parent p=new Parent();
p.property(); //cash+gold+land
p.marry(); // Subhalakshmi

Child c=new Child();


c.property(); //cash+gold+land
c.marry(); // Rashmika
Parent p1=new Child();
p1.property(); // cash+gold+land
p1.marry(); //Rashmika
}
}

o/p:
C.T.E

Method Hiding
==============
Method hiding is exactly same as method overriding with following differences.
Method overriding Method hiding
----------------- ----------------
Methods present in method overriding must Methods present in method hiding must be
be non-static. static.

Method resolution will taken care by Method resolution will taken care by compiler
JVM based on runtime object. based on reference type.

It is also known as runtime polymorphism, It is also known as compile time polymorphism,


dynamic polymorphism or late binding. static polymorphism or early binding.

ex:
---
class Parent
{
public static void property()
{
System.out.println("cash+gold+land");
}
public static void marry()
{
System.out.println("Subhalakshmi");
}
}
class Child extends Parent
{
public static void marry()
{
System.out.println("Rashmika");
}
}
class Test
{
public static void main(String[] args)
{
Parent p=new Parent();
p.property(); //cash+gold+land
p.marry(); // Subhalakshmi

Child c=new Child();


c.property(); //cash+gold+land
c.marry(); // Rashmika

Parent p1=new Child();


p1.property(); // cash+gold+land
p1.marry(); //Subhalakshmi
}
}
Q) Can we override main method in java?
No, We can't override main method in java because it is static.
In java, static methods can't be override.

Polymorphism
=============
Polymorphism has taken from Greek Word.
Here poly means many and morphism means forms.
The ability to represent in different forms is called polymorphism.
Diagram: java26.1
The main objective of polymorphism is to provide flexibility.
In java, polymorphism is divided into two types.
1) Compile time Polymorphism / Static Polymorphism / Early Binding
2) Runtime Polymorphism / Dynamic Polymorphism / Late Binding

1) Compile time Polymorphism


---------------------------
A polymorphism which exhibits at compile time is called compile time polymorphism.
ex:
Method Overloading
Method Hiding
2) Runtime Polymorphism
-----------------------
A polymorphism which exhibits at runtime is called runtime polymorphism.
ex:
Method overriding
Q) What is the difference between Method overloading and Method overriding?

Method overloading Method overriding


--------------------- -----------------
Having same method name with difference Having same method name with same signatures in
signatures in a single class is called method two different classes is called method overriding.
overloading.

It is a compile time polymorphism. It is runtime polymorphism.

Method resolution taken care by compiler based Method resolution taken care by JVM based on
on reference type. runtime object.

Private and final methods can be overloaded. Private and final methods can’t be overridden.
Summary Diagram: java26.2
Constructors
=============
It is a special method which is used to create and initialize an object.
Having same name as class name is called constructor.
It does not allow any returntype.
It will execute when we create an object.
A constructor a will accept following modifiers.
ex:
default
public
private
protected
We can declare a constructor as follow.
ex:
Test t=new Test();
|
constructor
In java, constructors are divided into two types.
1) Userdefined constructor
2) Default constructor
1) Userdefined constructor
--------------------------
A constructor which is created by the user based on the application requirement is called userdefined
constructor.
User defined constructor is classified into two types.
i) Zero-Argument constructor
ii) Parameterized constructor

i) Zero-Argument constructor
-----------------------------
Suppose if we are not passing any argument to userdefined constructor then that constructor is called 0-arg
constructor.
ex:
---
class Test
{
//constructor
Test()
{
System.out.println("constructor");
}
public static void main(String[] args)
{
System.out.println("main-method");
}
}

ex:
--
class Test
{
//constructor
public Test()
{
System.out.println("constructor");
}
public static void main(String[] args)
{
Test t=new Test();
System.out.println("main-method");
}
}
o/p:
constructor
main-method

ex:
---
class Test
{
//constructor
private Test()
{
System.out.println("constructor");
}
public static void main(String[] args)
{
Test t1=new Test();
System.out.println("main-method");
Test t2=new Test();
}
}
o/p:
constructor
main-method
constructor

ex:
---
class Test
{
//constructor
protected Test()
{
System.out.println("constructor");
}
public static void main(String[] args)
{
Test t1=new Test();
System.out.println("main-method");
Test t2=new Test();
}
}
o/p:
constructor
main-method
constructor

ii) Parameterized constructor


---------------------------
Suppose if are passing atleast one argument to userdefined constructor then that constructor is called
parameterized constructor.
ex:
---
class Employee
{
//current class variables
private int empId;
private String empName;
private double empSal;

public Employee(int empId,String empName,double empSal)


{
this.empId=empId;
this.empName=empName;
this.empSal=empSal;
}

public void getEmployeeDetails()


{
System.out.println("Employee Id :"+empId);
System.out.println("Employee Name :"+empName);
System.out.println("Employee Salary :"+empSal);
}
}
class Test
{
public static void main(String[] args)
{
Employee e=new Employee(101,"Alan",1000d);
e.getEmployeeDetails();
}
}
2) Default constructor
---------------------
It is a compiler generated constructor for every java program where we are not defining atleast zero argument
constructor.

To see the default constructor we need to use below command.


ex:
javap -c Test
Diagram: java26.3

constructor overloading
=====================
Having same constructor name with different parameters in a single class is called constructor overloading.

ex:
---
class A
{
A()
{
System.out.println("0-arg const");
}
A(int i)
{
System.out.println("int-arg const");
}
A(double d)
{
System.out.println("double-arg const");
}
}
class Test
{
public static void main(String[] args)
{
A a1=new A();
A a2=new A(10);
A a3=new A(10.5d);
}
}

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();
}
}

interface
==========
Interface is a collection of zero or more abstract methods.

Abstract method is a incomplete method because it ends with semicolon and does not have any body.
ex:
void methodOne();

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.

By default every abstract method is a public and abstract.

Interface contains only constants i.e public static final.

syntax:
------
interface interface_name
{
-
- //abstract methods
- //constants
-
}
Note:
-----
If we know only service requirement specification then we need to use interface.

Diagram: java27.1

ex:1
---
interface A
{
//abstract method
public abstract void m1();
}
class B implements A
{
//override
public void m1()
{
System.out.println("M1-Method");
}

}
class Test
{
public static void main(String[] args)
{
A a=new B();
a.m1();
}
}

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

class Test
{
public static void main(String[] args)
{
A a=new A()
{
public void m1()
{
System.out.println("From M1 Method");
}
};
a.m1();
}
}

If interface contains four methods then we need to override all methods otherwise we will get compile time
error.

ex:
interface A
{
//abstract methods
public abstract void see();
public void show();
abstract void view();
void display();
}
class B implements A
{
public void see()
{
System.out.println("see-method");
}
public void show()
{
System.out.println("show-method");
}
public void view()
{
System.out.println("view-method");
}
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();
}
}

A class can't extends more then one class but interface can extends more then one interface.

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)
{
D d=new D();
d.m1();
d.m2();
d.m3();
}
}

A class can implements more then one interface.

ex:
---
interface Father
{
double HT=6.2d;
void height();
}
interface Mother
{
double HT=5.8d;
void height();
}
class Child implements Father,Mother
{
public void height()
{
double height=(Father.HT+Mother.HT)/2;
System.out.println("Child Height is ="+height);
}
}
class Test
{
public static void main(String[] args)
{
Child c=new Child();
c.height();
}
}

Note:
------
According to Java 8 , interface is a collection of abstract methods, default methods and static methods.

Abstract class
===============
Abstract class is a collection of zero or more abstract methods and concrete methods.

A abstract keyword is applicable for class and method but not for variables.
It is not possible to create object for abstract class.

To write the implementation of abstract methods we will use sub classes.

By default every abstract method is a public and abstract.

Abstract class contains only instance variables.

syntax:
abstract class class_name
{
-
- //abstract methods
- //concrete methods
- //instance variables
-
}

Note:
-----
If we know partial implementation then we need to use abstract class.

ex:
----
abstract class Plan
{
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 :"+(rate*units));
}
}
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);
}
}

Abstraction example
====================
abstract class Animal
{
public abstract void makeSound();
}
class Dog extends Animal
{
public void makeSound()
{
System.out.println("Boow! Boow!");
}
}
class Test
{
public static void main(String[] args)
{
Dog d=new Dog();
d.makeSound();
}
}

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 constructors. It allows constructors.

It does not allow blocks. It allows blocks.


To write the implementation of abstract methods To write the implementation of abstract methods
we will use implementation class. we will use sub classes.

If we know only specification then we need to If we know partial implementation then we need to
use interface. use abstract class.

Marker Interface
================
Interface which does not have any methods and constants is called marker interface.

In general, Empty interface is called marker interface.

By using marker interface we will get some ability to do.

We have following list of marker interfaces.

ex:
Serializable
Cloneable
Remote
and etc.

ex:
---
class Item implements java.io.Serializable
{
private int itemId;
private String itemName;
private double itemPrice;

//setter and getter methods


public void setItemId(int itemId)
{
this.itemId=itemId;
}
public int getItemId()
{
return itemId;
}

public void setItemName(String itemName)


{
this.itemName=itemName;
}
public String getItemName()
{
return itemName;
}

public void setItemPrice(double itemPrice)


{
this.itemPrice=itemPrice;
}
public double getItemPrice()
{
return itemPrice;
}

API
=====
API stands for Application Programming Interface.

API is a collection of packages.

It is a base for the programmers to develop software applications.

In java , API is categories 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 requirements.

3) Third party API


------------------
API which is given by third party vendor.
ex:
JAVAZOOM API
IText API

package
=========
A package is a collection of a 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 interfaces.

A package is also known as a 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.sql
and etc.

2) Userdefined packages
-----------------------
A package which is created by the user based on the application requirement is called userdefined package.

We can declare userdefined package as follow.

syntax:
-----
package package_name;

It is always recommanded to declare package name in the reverse order of url.


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 location

We can run above program by using below command.


ex:
java com.ihub.www.Test
| |
package name classname

Q) What is singleton class?

A class which allows us to create only one object is called singleton class.

It is a design pattern that ensures that a class can only have one object.

Using a class if we call any method and that method returns same class object is called singleton class.
ex:
Calendar c=Calendar.getInstance();
LocalTime time=LocalTime.now();
LocalDate date=LocalDate.now();
and etc.

To create a singleton class, a class must have private constructor and static method.
ex:
----
class Singleton
{
static Singleton singleton=null;

private Singleton()
{
}

//static method
public static Singleton getInstance()
{
if(singleton==null)
{
singleton=new Singleton();
}

return singleton;
}
}
class Test
{
public static void main(String[] args)
{
Singleton s1=Singleton.getInstance();
Singleton s2=Singleton.getInstance();

System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
}
}

Enum
=====
Enum is a group of named constants.

Enum concept introduced in 1.5v.

Using enum we can created our own datatype called enumerated datatype.

When compare to old language enum, java enum is more powerful.

We can declare enum as follow.

syntax:
--------
enum <type_name>
{
value1,value2,valu3,....,valueN
}

ex:
----
enum Months
{
JAN,FEB,MAR
}

Internal implementation of enum


--------------------------------
Every enum internally implemented as class concept and it is extended 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 switch case allow enum.

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()
-----------
It will return group of constants from enum.

2) ordinal()
-----------
It will return ordinal numbers.

ex:
---
enum Week
{
MON,TUE,WED,THU,FRI,SAT,SUN
}

class Test
{
public static void main(String[] args)
{
Week[] week=Week.values();

for(Week w:week)
{
System.out.println(w+" --------------- "+w.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
{
COLA,SPRITE,MAZAA,STING;

Drinks()
{
System.out.println("constructor");
}
}
class Test
{
public static void main(String[] args)
{
Drinks d=Drinks.COLA;
}
}

ex:
---
enum Cloths
{
COTTON,KHADI,SILK;

static int i=100;

public static void main(String[] args)


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

Inner classes
==============
Sometimes we will declare a class inside another class such concept is called inner class.

ex:
class Outer
{
class Inner
{
-
- //code to declare
-
}
}

Inner class must be declare within the scope of outer class.

Inner classes introduced as a part of event handling to remove GUI bugs.

But due to powerful features of inner classes , programmers started to use inner classes in regular
programming.

Inner classes do not allow static members.

Accessing inner class data from static area of outer class


----------------------------------------------------------
class Outer
{
class Inner
{
public void m1()
{
System.out.println("Inner-M1 method");
}
}

public static void main(String[] args)


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

If we compile above program then we will get two .class files i.e
Outer.class and Outer$Inner.class.

ex:
---
class Outer
{
class Inner
{
public void m1()
{
System.out.println("Inner-M1 method");
}
}

public static void main(String[] args)


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

Accessing inner class data from non-static area of a outer class


--------------------------------------------------------------
class Outer
{
class Inner
{
public void m1()
{
System.out.println("Inner-M1 method");
}
}

public void m2()


{
Inner i=new Inner();
i.m1();
}
public static void main(String[] args)
{
Outer o=new Outer();
o.m2();
}
}

Wrapper classes
===============
The main objective of wrapper classes are

1) To wrap primitive type to wrapper object and vice versa.

2) To define 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 two methods.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);

Integer i2=new Integer("20");


System.out.println(i2);
}
}
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);//a
}
}

Utility methods
---------------

1) valueOf()
-----------
It is similar to constructor.

It will 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

Integer i2=Integer.valueOf("20");
System.out.println(i2);//20

}
}

2) xxxValue()
-------------
It is used to convert wrapper object to primitive type.

ex:
--
class Test
{
public static void main(String[] args)
{
Integer i=new Integer(10);
short s=i.shortValue();
System.out.println(s);//10

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

3) parseXxx()
--------------
It is used to convert string type to primitive type.
ex:
---
class Test
{
public static void main(String[] args)
{
String str="10";

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

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

float f=Float.parseFloat(str);
System.out.println(f);
}
}

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
}
}

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 binary1 : ");


String binary1=sc.next();

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


String binary2=sc.next();

//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);
}
}
Q) In how many ways we can call garbage collector 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();
Runtime.getRuntime().gc();
}

public void finalize()


{
System.out.println("Finalize Method");
}
}
Types of objects in Java
========================
We have two types of objects in java.

1) Immutable object

2) Mutable object

1) Immutable object
--------------------
After object creation if we perform any changes then for every change a new object will be created such type
of object is called immutable object.
ex:
String and wrapper classes

2) Mutable object
--------------
After object creation if we perform any changes then all changes will be reflected to same object such type of
object is called mutable object.

ex:
StringBuffer and StringBuilder

String
========
It 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 type of behaviour is called immutability of an object.
Diagram: java30.1

case2:
-----
What is the difference between == and .equals() method?

==
----
It is used for reference comparision or address comparision.

We can compare objects and primitives.

ex:
---
class Test
{
public static void main(String[] args)
{
String s1=new String("bhaskar");
String s2=new String("bhaskar");
System.out.println(s1==s2);//false
}

.equals()
-------
It is used for content comparision and it is case sensitive.

We can compare only objects.


ex:
---
class Test
{
public static void main(String[] args)
{
String s1=new String("bhaskar");
String s2=new String("bhaskar");
System.out.println(s1.equals(s2));//true
}

case3:
------
Once if 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.

Diagram: java30.2

Object creation in SCP arae 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 will create a
new object.Hence there is no chance of having duplicate objects in SCP area.

SCP objects do not have any object reference even though garbage collector can't access them.

SCP objects will destroy automatically whenever JVM shutdowns or terminated.

Diagram: java30.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: java30.4
String important methods
========================

Q) Write a java program to find out length of the String?

input:
hello

output:
5

ex:

class Test
{
public static void main(String[] args)
{
String str="hello";
System.out.println(str.length());
}

Q) Write a java program to convert given string to lowercase?

input:
HELLO

output:
hello

ex:

class Test
{
public static void main(String[] args)
{
String str="HELLO";
System.out.println(str.toLowerCase());
}

Q) Write a java program to convert given string to uppercase?

input:
hello

output:
HELLO

ex:

class Test
{
public static void main(String[] args)
{
String str="hello";
System.out.println(str.toUpperCase());
}

Q) Write a java program to display the character of a given index?

input:
str = bhaskar
index = 3

output:
s

ex:

class Test
{
public static void main(String[] args)
{
String str="bhaskar";
int index=3;
System.out.println(str.charAt(index));
}

Q) Write a java program to display the index of a given character?

input:
str = bhaskar
ch = 'a'

output:
2

ex:

class Test
{
public static void main(String[] args)
{
String str="bhaskar";
char ch='a';
System.out.println(str.indexOf(ch));
}

}
Q) Write a java program to display the last index of a given character?

input:
str = bhaskar
ch = 'a'

output:
5

ex:

class Test
{
public static void main(String[] args)
{
String str="bhaskar";
char ch='a';
System.out.println(str.lastIndexOf(ch));
}

Q) Write a java program to concatinate two strings?

input:
ihub
talent

output:
ihubtalent

ex:
---
class Test
{
public static void main(String[] args)
{
String str1="ihub";
String str2="talent";
System.out.println(str1.concat(str2));
}

Q) Write a java program to compare two strings?

input:
bhaskar
bhaskar

output:
Both are same

ex:

class Test
{
public static void main(String[] args)
{
String str1="bhaskar";
String str2="bhaskar";
if(str1.equals(str2))
System.out.println("Both are same");
else
System.out.println("Both are not same");
}

Q) Write a java program to compare two strings?


input:
bhaskar
BHASKAR

output:
Both are same

ex:

class Test
{
public static void main(String[] args)
{
String str1="bhaskar";
String str2="BHASKAR";
if(str1.equalsIgnoreCase(str2))
System.out.println("Both are same");
else
System.out.println("Both are not same");
}

Q) Write a java program to replace the character in a given string?

input:
str= bhaskar
ch ='A'
output:
bhAskAr

ex:

class Test
{
public static void main(String[] args)
{
String str="bhaskar";

System.out.println(str.replace('a','A'));
}

Q) Write a java program to remove special characters from given string?

Input:
I_hub@Ta$len#t29

output:
IhubTalent29

ex:
---
class Test
{
public static void main(String[] args)
{
String str="I_hub@Ta$len#t29";

str=str.replaceAll("[^A-Za-z0-9]","");

System.out.println(str);
}

Q) Write a java program to remove 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:
ihub23
talent17

output:
ihubtalent40

ex:

class Test
{
public static void main(String[] args)
{
String str1="ihub23";
String str2="talent17";

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

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

String word=word1+word2;
int num=num1+num2;
System.out.println(word+num);
}

Q) Write a java program to display sub string?

Input:
ihubtalent

output:
talent

ex:

class Test
{
public static void main(String[] args)
{
String str="ihubtalent";

System.out.println(str.substring(4));
}
}

Q) Write a java program to display sub string?

Input:
ihubtalent

output:
tale

class Test
{
public static void main(String[] args)
{
String str="ihubtalent";

System.out.println(str.substring(4,8));
}

Q) Write a java program to perform right rotation of a given String?

input:
str = ihubtalent
count = 2

output:
ubtalentih

class Test
{
public static void main(String[] args)
{
String str="ihubtalent";
int count=2;

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

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

str=word1+word2;

System.out.println(str);
}

Q) Write a java program to insert given word in a given string?

input:
str = IhubTalent
index= 4
word = For

output:
IhubForTalent

ex:
class Test
{
public static void main(String[] args)
{
String str ="IhubTalent";
int index= 4;
String word ="For";

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

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

str = word1+word+word2;

System.out.println(str);

Q) Write a java program to delete the string?

input:
str = This is java class
delete = is

output:
Th java class

ex:

class Test
{
public static void main(String[] args)
{
String str="This is java class";
String delete="is";

str=str.replaceAll(delete,"");

System.out.println(str);
}
}

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";

char[] carr=str.toCharArray(); // h e l l o

String rev="";

//reading reverse
for(int i=carr.length-1;i>=0;i--)
{
rev+=carr[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";

char[] carr=str.toCharArray(); // r a c a r

String rev="";

//reading reverse
for(int i=carr.length-1;i>=0;i--)
{
rev+=carr[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 the reverse of the string?

input:
This is java class
output:
class java is This

class Test
{
public static void main(String[] args)
{
String str="This is java class";

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

String rev="";

for(int i=sarr.length-1;i>=0;i--)
{
rev+=sarr[i]+" ";
}
System.out.println(rev);
}
}

Q) Write a java program to display reverse of a string?

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

//for each loop


for(String s:sarr)
{
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 starting with uppercase letters?

input:
This is Java language For students

output:
This Java For

ex:
---
class Test
{
public static void main(String[] args)
{
String str="This is Java language For students";

String[] sarr=str.split(" "); // This is Java language For students

//for each loop


for(String s:sarr)
{
if(s.charAt(0)>='A' && s.charAt(0)<='Z')
{
System.out.print(s+" ");
}
}

}
}

Q) Write a java program to display vowels present in a given string?

input:
Umbrella

output:
uea

ex:

class Test
{
public static void main(String[] args)
{
String str="Umbrella";
str=str.toLowerCase();

//reading characters from string


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 to display the string in a given format?

Input:
A1B2C3D4

output:
ABBCCCDDDD

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 check given string is anagram or not?

input:
str1 = silent
str2 = 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==true)
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:
XYZ

output
XY
XZ
YX
YZ
ZX
ZY
class Test
{
public static void main(String[] args)
{
String str="XYZ";

char[] carr=str.toCharArray();

for(int i=0;i<carr.length;i++)
{
for(int j=0;j<carr.length;j++)
{
if(carr[i]!=carr[j])
{
System.out.println(carr[i]+""+carr[j]);
}
}
}

}
}

Q) Write a java program to display duplicate and unique characters from given string?

input:
google

output:
Duplicate characters : o g
Unique characters : g o l e

ex:

class Test
{
public static void main(String[] args)
{
String str="google";

String duplicates="";
String uniques="";

for(int i=0;i<str.length();i++)
{
String s=Character.toString(str.charAt(i));
if(!uniques.contains(s))
{
uniques+=s;
continue;
}
duplicates+=s;
}

System.out.println("Duplicate characters :"+duplicates);


System.out.println("Unique characters :"+uniques);
}
}

Q) Write a java program to convert the string's initial letter in uppercase?

input:
this is java class

output:
This Is Java Class

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

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

String result="";

//for each loop


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

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

if(i==0)
{
result+=(char)(carr[i]-32);
}
else
{
result+=carr[i];
}

}
//space
result+=" ";
}

System.out.print(result);
}
}
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 character=' ';


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;
character=str.charAt(i);
}
}
System.out.println(character+" is repeating for "+maxCount+" times");
}
}
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";
//caller method
permutation(str.toCharArray(),0);
}
//callie method
public static void permutation(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);
permutation(arr,fi+1);
swapping(arr,fi,i);
}
}
//callie method
public static void swapping(char[] arr,int fi,int i)
{
char temp=arr[fi];
arr[fi]=arr[i];
arr[i]=temp;
}
}

StringBuffer
==============
If our content change frequently then it is not recommanded to use String because for every change a new
object will be created.

To overcome this limitation Sun Micro System introduced StringBuffer concept.

In SringBuffer all the required changes will be done in a single object only.

constructors
-------------
1) StringBuffer sb=new StringBuffer()
-------------------------------------
It will create empty StringBuffer object with default initial capacity of 16.

If we reach maximum capacity then new capacity will be created with below formulea.

ex:
new 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(initial 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 equivalent to String.

Here capacity will be created with below formulea.

ex:
capacity = s.length() + 16;

ex:

class Test
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer("bhaskar");

System.out.println(sb.capacity()); //7+16=23

Q) Write a java progrm to display reverse of a 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 count number of 2's present in a number?

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 cnt=0;
for(int i=0;i<sb.length();i++)
{
int n=Integer.parseInt(Character.toString(sb.charAt(i)));
if(n==2)
{
cnt++;
}
}
System.out.println(cnt);
}

}
Q) Write a java program to multiply two arrays?

input:
412
25

output:
10300 (412*25)

ex:

class Test
{
public static void main(String[] args)
{
int[] arr1={4,1,2};
int[] arr2={2,5};

//caller method
int a=Integer.parseInt(arrayToString(arr1));
int b=Integer.parseInt(arrayToString(arr2));
System.out.println(a*b);
}
//callie method
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));
sb.append(count);
count=1;
}
}

System.out.println(sb.toString());
}
}

Q) Write a java program to encode the string?

input:
1106

output:
AAJF

ex:
class Test
{
public static void main(String[] args)
{
String str="1106";

StringBuffer sb=new StringBuffer();

for(int i=0;i<str.length();i++)
{
int n=Integer.parseInt(Character.toString(str.charAt(i)));
if(n>0)
{
sb.append((char)('A'+ n-1));
}
else
{
int k=Integer.parseInt(str.substring(i-1,i+1));
sb.append((char)('A' + k-1));
}
}

System.out.println(sb.toString());
}
}

Q) Write a java program to display longest common sub sequence in a given string?

input:
ABCAB
AECB

output:
3

ex:

class Test
{
public static void main(String[] args)
{
String str1="ABCAB";
String str2="AECB";

//caller method
System.out.println(longestCommonSubsequence(str1,str2));
}
//callie method
public static int longestCommonSubsequence(String str1,String str2)
{
return solve(str1,str2,0,0);
}
//callie method
public static int solve(String str1,String str2,int i,int j)
{
if(i==str1.length())
return 0;
if(j==str2.length())
return 0;

int ans=0;

if(str1.charAt(i) == str2.charAt(j))
{
ans=1+solve(str1,str2,i+1,j+1);
}
else
{
ans=Math.max(solve(str1,str2,i+1,j),solve(str1,str2,i,j+1));
}

return ans;
}

Assignment
=========
Write a java program to decode the string?

input:
AAJF

output:
1106
char ch=str.charAt('A')
ch – 64
StringBuilder
=============
StringBuilder is exactly same as StringBuffer with following differences.

StringBuffer StringBuilder
----------------- ---------------
Methods which are present in StringBuffer No method present in StringBuilder is synchronized.
are synchronized.

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

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

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

StringTokenizer
===============
StringTokenizer is a class which is present in java.util package.

It is used to tokenize the string irrespective of regular expression.

We can declare StringTokenizer object as follow.

ex:
StringTokenizer st=new StringTokenizer(String str,RegExp reg);

StringTokenizer class contains following methods.

ex:
public boolean hasMoreTokens()
public String nextToken()
public boolean hasMoreElements()
public Objct 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:
----
Here default regular expression is space.

ex:2
----
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);
}
}
}

Note:
----
If our content change frequently then it is never recommanded to use String.

If our content change frequently where thread safety is required then we need to use StringBuffer.

If our content change frequently where thread safety is not required then we need to use StringBuilder.

Exception Handling
===================

Q) What is the difference between Exception and Error?

Exception
---------
Exception is a problem for which we can provide solution programmatically.

Exceptions will occur due to syntax errors.

ex:
ArithmeticException
FileNotFoundException
IllegalArgumentException

Error
-----
Error is a problem for which we can't provide solution programmatically.

Errors will occur due to lack of system resources.

ex:
OutOfMemoryError
LinkageError
StackOverFlowError

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 intteruption 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 intteruption 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);
}
}
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 of the exception and line number of the
exception.

Exception
==========
It is a unwanted, unexpected event which disturbs normal flow of our program.

Exceptions always raised at runtime so they are also known as runtime events.

The main objective of exception handling is to provide graceful termination.

In java, exceptions are divided into two types.

1) predefined exceptions

2) Userdefined exceptions

1) predefined exceptions
-------------------------
Built-In exceptions are called predefined exceptions.

It is classified into two types.

i) Checked exceptions
-------------------
Exceptions which are checked by the compiler at the time of compilation is called checked exceptions.
ex:
InterruptedException
EOFException
FileNotFoundException
and etc.
ii) Unchecked exceptions
------------------------
Exceptions which are checked by the JVM at runtime is called unchecked exceptions.
ex:

ArithmeticException
ClassCastException
IllegalArgumentException
and etc.

Diagram: java34.1

If any checked exception raised in our program , we must and should handle 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 raise in try block then it won't be executed.

A try block is used to throw the exception to catch block.

catch block
==========
It is a block which contains error handling code.

It is always associate with try block.

A catch block 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 exception name as a parameter and that name must match with exception class name.
syntax:
------
try
{
-
- //risky code
-
}
catch(ArithmeticException ae)
{
-
- //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");
}
}
}
o/p:
stmt1
catch-block

ex:

class Test
{
public static void main(String[] args)
{
int i=1;

try
{
i++;
}
catch (Exception e)
{
i++;
}

System.out.println(i);//2
}
}

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 blocks 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 ");
}
}
}

Various methods to display the exception details


=================================================
Throwable class defines following three methods to display exception details.

1) printStackTrace()
--------------------
It will display name of the excepiton ,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) geMessage()
-------------
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());
}

}
}

finally block
==============
It is never recommanded to maintain cleanup code in try block because if any exception raise in try block then
try block won't be executed.

It is never recommanded to maintain cleanup code in catch bock because if there is no exception in try block
then catch won't be executed.
But 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.

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("try-block");
System.out.println(10/0);
System.out.println("stmt");
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
System.out.println("finally-block");
}

}
}
o/p:
try-block
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");
}

}
}

Q) What is difference between final, finally and finalize method?

final
-----
A 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 will execute irrespective of exception raise or not.

finalize
--------
It is a method called by garbage collector just before destroying an object for cleanup activity.
throw statement
===============
Sometime we will create exception object explicitly and handover to JVM manually by using throw statement.
ex:
throw new ArithmeticException("Don't divide by zero");

ex:
class Test
{
public static void main(String[] args)
{
throw new ArithmeticException("Don't divide by zero");
}
}

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 (Exception e)
{
e.printStackTrace();
}
}
}

ex:
---
class Test
{
public static void main(String[] args) throws InterruptedException
{

Thread.sleep(5000);
System.out.println("Welcome to Java ");

}
}

2) Userdefined exception
=======================
Exception which are created by the user based on the application requirements are called userdefined
exceptions or customized exceptions.

ex:
NoPracticeException
NoInterestInJavaException
NoMoneyToEnjoyException
TooYoungException
TooOldException

ex:

import java.util.Scanner;
class TooYoungException extends RuntimeException
{
TooYoungException(String message)
{
super(message);
}
}
class TooOldException extends RuntimeException
{
TooOldException(String message)
{
super(message);
}
}
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 TooYoungException("U r not eligible to vote");
else
throw new TooOldException("U r eligible to vote");
}
}

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)throws IOException
{
File f=new File("abc.txt");
System.out.println(f.exists()); // false

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

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
}
}

Create a "cricket123" folder and inside that folder create "abc.txt" file.

ex:
--
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)
{

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 ioe)
{
ioe.printStackTrace();
}
}
}

try with resources


==================
A try with resource introduced in Java 7.

A try -with-resource ensures that each resource is closed at the end of the statement.

syntax:
------
try(resources)
{
}
catch(Exception e)
{
}

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();
System.out.println("Please check the location");
}
catch (IOException ioe)
{
ioe.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:
----
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:
---
import java.io.*;
class Test
{
public static void main(String[] args)throws IOException
{
FileReader fr=new FileReader("aaa.txt");
char[] ch=new char[250];

fr.read(ch);

//for each loop


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

fr.close();
}
}

Limitations with FileWriter and FileReader


-------------------------------------------
While write the data by using FileWriter object we need to insert line seperates 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.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(98); // b
pw.println(98);//98

pw.println(true);//true

pw.println(10.5d);//10.5

pw.println("Hello");//Hellow

pw.println('a');// a

pw.flush();

pw.close();

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


}
}

Various ways to accept the values from the keyboard


====================================================
There are following ways to accept the input values from keyboard.

1) Command Line Agument

2) BufferedReader class

3) Console class
4) Scanner class

1) Command Line Agument


-----------------------
Argument which is passing through command prompt such type of argument is called command line
argument.

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 JackMa

2) BufferedReader class
-----------------------
BufferedReader is a class which is present in java.io package.

We can create BufferedReader object as follow.


ex:
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

To read the inputs we need to use readLine() method of BufferedReader object.


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 is a class which is present in java.io package.

We can create Console class object as follow.

ex:
Console c=System.console();

To read the inputs we need to use readLine() method of Console object.

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 is a class which is present in java.util package.

We can create Scanner class object as follow.

ex:
Scanner sc=new Scanner(System.in);

To read the inputs we need to use nextXxx() methods.

We have following nextXxx() methods.


ex:
nextInt()
nextLong();
nextFloat()
nextDouble()
nextLine()
and etc.s

ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the student Id :");


int id=sc.nextInt();

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


String name=sc.next();

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


double fee=sc.nextDouble();

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


}
}

ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the student Id :");


int id=sc.nextInt();

sc.nextLine();

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


String name=sc.nextLine();

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


double fee=sc.nextDouble();
System.out.println(id+" "+name+" "+fee);
}
}

Generics
=========
Arrays are typesafe.It means we can give guaranetee that what type of elements are present in array.

If requirement is there to store string values then it is recommanded to use String array.
ex:
String[] sarr=new String[10];
sarr[0]="hi";
sarr[1]="hello";
sarr[2]="bye";
sarr[3]=10; //invalid

At the time of retrieving the data from array we don't need to perform typecasting.

ex:
String[] sarr=new String[10];
sarr[0]="hi";
sarr[1]="hello";
sarr[2]="bye";
-
-
String value1=sarr[0];

Collections are not typesafe.It means we can't give guarantee that what type of elements are present in
Collections.

If requirement is there to store String values then it is not recommanded to use ArrayList because we won't get
any compile time error or runtime error but sometimes our program get failure.

ex:
ArrayList al=new ArrayList();
al.add("hi");
al.add("hello");
al.add("bye");
al.add(10);

At the time of retrieving the data from Collections compulsary we need to perform typecasting.

ex:
ArrayList al=new ArrayList();
al.add("hi");
al.add("hello");
al.add("bye");
al.add(10);
-
-
String value1=(String)al.get(0);

To overcome this above limitations 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
elements. hetrogeneous data elements.
It is fixed in size. It is growable in nature.

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

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

Arrays not implemented based on data structure Collections are implemented based on data structure
concept so we can't expect any readymade concept so we can expect readymade methods.
methods.

Collection Framework
====================
Collection Framework defines several utility classes and interfaces to represent group of objects in a single
entity.

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 following methods which are available for entire Collection objects.

ex:
cmd> javap java.util.Collection

add()
remove()
removeAll()
addAll()
contains()
containsAll()
retainAll()
clear()
and etc.

List
=====
It is a child interface of Collection interface.

If we want to represent group of individual objects in a single entity where duplicate objects are allowed and
order is preserved then we need to use List interface.

Diagram: java38.1

ArrayList
-------------
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.

If our frequent operation is a retrieval operation then ArrayList is a best choice.

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.isEmpty()); // false

for(int i=0;i<al.size();i++)
{
System.out.println(al.get(i));
}
}
}

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.contains("two")); //true

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

al.clear();

System.out.println(al); //[]
}
}

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

list.add(0,"gogo");

System.out.println(list);//[gogo,one,two,three]
}
}

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

ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(4,2,7,1);
System.out.println(list);
}
}

LinkedList
============
The underlying data structure is doubly LinkedList.

Duplicate objects are allowed.

Insertion order is preserved.

Hetrogeneous objects are allowed.

Null insertion is possible.

It implements Serializable, Cloneable and Deque interface.

If our frequent operation is adding and removing the elements in middle then LinkedList is a best choice.

LinkedList interface 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) Write a java program to store student objects in ArrayList?

import java.util.*;
class Student
{
private int studId;
private String studName;

//constructor
Student(int studId,String studName)
{
this.studId=studId;
this.studName=studName;
}
//getter methods
public int getStudId()
{
return studId;
}
public String getStudName()
{
return studName;
}

public String toString()


{
return "["+studId+" "+studName+"]";
}
}
class Test
{
public static void main(String[] args)
{
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(101,"Alan"));
al.add(new Student(102,"Jose"));
al.add(new Student(103,"Kelvin"));

System.out.println(al);
}
}

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.

All methods present in Vector are synchronized.Hence Vector is thread safe.

Vector contains following methods.


ex:
addElement()
removeElement()
removeAllElements()
firstElement()
lastElement()
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());//10

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.removeElement(5);
System.out.println(v);//[1,2,3,4,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());//10

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(4);
System.out.println(v);//[1,2,3,4,6,7,8,9,10]

v.clear();
System.out.println(v); //[]
}
}

Q) What is the difference between ArrayList vs Vector?

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

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.ArrayList is not on Vector. Vector is thread safe.
thread safe.

Relatively performance is high because Relatively performance is low because of waiting


there is no waiting thread. threads.

Introduced in 1.2v. Introduction in 1.0v.

Q) What is the difference between ArrayList vs LinkedList ?

ArrayList LinkedList
------------ -----------
The underlying data structure is resizable The underlying data structure is doubly
array or growable array. linked list.

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.

Stack
=====
Stack is a child class of Vector class.

If we depend upon Last In First Out (LIFO) order then we need to use Stack.

constructor
---------
Stack s=new Stack();

methods
--------

push(Object o)
-------------
It is used to push the element in stack.

pop()
-----
It is used to pop the element from stack.

peek()
-------
It will return toppest element of a stack.

isEmpty()
--------
It is used to check stack is empty or not.

search(Object o)
----------------
It will return offset value if element 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("K")); // -1

System.out.println(s.search("A")); // 2
}
}

Set
====
It is a child interface of Collection interface.

If we want to represent group of individual objects in a single entity where duplicate objects
are not allowed and order is not preserved then we need to use Set interface.

Diagram: java39.1

HashSet
========
The underlying data structure is Hashtable.

Duplicate objects are not allowed.

Insertion order is not preserved because it will take hashcode of an object.

Hetrogeneous objects are allowed.


Null insertion is possible.

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

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

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

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

LinkedHashSet
==============
It is a child class of HashSet class.

LinkedHashSet is exactly same as HashSet class with following differences.

ex:

HashSet LinkedHashSet
------------ -------------
The underlying data structure is The underlying data structure is Hashtable
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)
{
LinkedHashSet lhs=new LinkedHashSet();
lhs.add("three");
lhs.add("one");
lhs.add("two");
System.out.println(lhs); //[three, one, two]

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

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

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

Q) Write a java program to display distinct elements from given array?

input:
1223334444

output:
1234

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 each loop


for(int i:arr)
{
set.add(i);
}

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


}
}

TreeSet
========
The underlying data structure is Balanced Tree.

Duplicate objects are not allowed.

Insertion order is not preserved because it takes sorting order of an object.

Hetregeneous objects are not allowed. If we insert hetrogeneous objects then we will get
ClassCastException.

Null insertion is not possible. 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(5);
ts.add(1);
ts.add(10);
ts.add(7);
System.out.println(ts);//[1,5,7,l0]

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

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

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

Q) How can we make ArrayList as synchronized?

import java.util.*;
public class Test
{
public static void main(String[] args) {
// Create a new ArrayList
List<String> arrayList = new ArrayList<>();

// Make the ArrayList synchronized


List<String> synchronizedList = Collections.synchronizedList(arrayList);

// Use the synchronized list


synchronizedList.add("one");
synchronizedList.add("two");

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


}
}

Q) Write a java program to display the string in sorting order?

Input:
Ball Dog Apple Cat Elephant

output:
Apple Ball Cat Dog Elephant

ex:

import java.util.*;
class Test
{
public static void main(String[] args)
{
String str="Ball Dog Apple Cat Elephant";

String[] sarr=str.split(" "); // Ball Dog Apple Cat Elephant


List<String> list=new ArrayList<String>();

for(String s:sarr)
{
list.add(s);
}

Collections.sort(list);

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


}
}

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 two methods i.e compare() 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 equals() method is optional because it is available to the class by the Object
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(7);
System.out.println(ts);//[10,7,5,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(7);
System.out.println(ts);//[1,5,7,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(2023,07,31);

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");

}
}

ex:
---
import java.time.*;
class Test
{
public static void main(String[] args)
{
LocalDate date1=LocalDate.now();

LocalDate date2=LocalDate.of(2023,07,31);

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");

}
}

Map
====
It is not a child interface of Collection interface.
If we want to represent group of individual objects in key and value pair then we need to use
Map interface.

Key and value both must be objects.

Key can't be duplicate but value can be duplicate.

Each key and value pair is known as one entry.

Diagram: java40.1

HashMap
=========
The underlying data structure is Hashtable.

Duplicate keys are not allowed but values can be duplicated.

Insertion order is not preserved because it will take hash code of a key.

Hetrogeneous objects are allowed for both key and value.

Null insertion is possible for both key and value.

ex:

import java.util.*;
class Test
{
public static void main(String[] args)
{
HashMap hm=new HashMap();
hm.put(1,"one");
hm.put(7,"seven");
hm.put(10,"ten");
hm.put(3,"three");
System.out.println(hm);//{1=one, 3=three, 7=seven, 10=ten}

hm.put(1,"gogo");
System.out.println(hm);//{1=gogo, 3=three, 7=seven, 10=ten}

hm.put("nine",9);
System.out.println(hm); //{1=gogo, nine=9, 3=three, 7=seven, 10=ten}

hm.put(null,null);
System.out.println(hm);//{null=null, 1=gogo, nine=9, 3=three, 7=seven, 10=ten}
}
}

ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
HashMap<Integer,String> hm=new HashMap<Integer,String>();
hm.put(1,"one");
hm.put(7,"seven");
hm.put(10,"ten");
hm.put(3,"three");
System.out.println(hm);//{1=one, 3=three, 7=seven, 10=ten}
hm.put(1,"gogo");
System.out.println(hm);//{1=gogo, 3=three, 7=seven, 10=ten}

hm.put(null,null);
System.out.println(hm);//{null=null, 1=gogo, 3=three, 7=seven, 10=ten}
}
}

ex:
---
import java.util.*;
class Test
{
public static void main(String[] args)
{
HashMap<Integer,String> hm=new HashMap<Integer,String>();
hm.put(1,"one");
hm.put(7,"seven");
hm.put(10,"ten");
hm.put(3,"three");

Set s=hm.keySet();
System.out.println(s); //[1, 3, 7, 10]

Collection c=hm.values();
System.out.println(c); // [one, three, seven, ten]

Set s1=hm.entrySet();
System.out.println(s1); //[1=one, 3=three, 7=seven, 10=ten]
}
}

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.

Introduced in 1.2v. Introduced in 1.4v.

ex:

import java.util.*;
class Test
{
public static void main(String[] args)
{
LinkedHashMap<Integer,String> lhm=new LinkedHashMap<Integer,String>();
lhm.put(1,"one");
lhm.put(7,"seven");
lhm.put(10,"ten");
lhm.put(3,"three");

System.out.println(lhm); //{1=one, 7=seven, 10=ten, 3=three}

lhm.put(1,"gogo");
System.out.println(lhm); //{1=gogo, 7=seven, 10=ten, 3=three}

lhm.put(null,null);
System.out.println(lhm); //{1=gogo, 7=seven, 10=ten, 3=three, null=null}
}
}

TreeMap
=========
The underlying data structure is RED BLACK TREE.

Duplicate keys are not allowed but values can be duplicated.

Insertion order is not preserved because it will take sorting order of a key.

If we depend upon default natural sorting order then keys must be homogeneous and Comparable.

If we depend upon customized natural sorting order then keys must 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(6,"six");
tm.put(1,"one");
tm.put(5,"five");
tm.put(10,"ten");
System.out.println(tm);//{1=one, 5=five, 6=six, 10=ten}

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

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

//tm.put(null,"seven");// R.E NullPointerException


}
}
Hashtable
=========
The underlying data structure is Hashtable.

Duplicate keys are not allowed but values can be duplicated.

Insertion order is not preserved because it will take 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(6,"six");
ht.put(1,"one");
ht.put(5,"five");
ht.put(10,"ten");
System.out.println(ht);//{10=ten, 6=six, 5=five, 1=one}

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

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

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

Interview Questions
===================
Q) Write a java program to display number of occurance of a given string?

input:
this class class for java java

output:
this=1, class=2 , for=1, java=2

ex:

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

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);
}
}

map.forEach((key,value)-> System.out.print(key+"="+value+" "));

}
}

Q) Write a java program to display number of characters of 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 ch:carr)
{
if(map.get(ch)!=null)
{
map.put(ch,map.get(ch)+1);
}
else
{
map.put(ch,1);
}
}

map.forEach((key,value)-> System.out.print(key+"="+value+" "));

}
}

Cursor
=======
Cursor is used to read the objects one by one from Collections.

We have three types of cursors.

1) Enumeration

2) Iterator

3) ListIterator

1)Enumeration
==============
Enumeration interface present in java.util package.

It is used to read objects one by one from Legacy Collection objects.

Enumeration object can be created by using elements() method.


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);
}
System.out.println(v);//[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Enumeration e=v.elements();
while(e.hasMoreElements())
{
Integer i=(Integer)e.nextElement();
System.out.println(i);
}
}
}

Limitations with Enumeration


--------------------------------
Using Enumeration we can read objects one by one from legacy Collection objects.Hence it is not a universal
cursor.

Using Enumeration interface we can perform read operation but not delete/remove operation.

To overcome this limitation sun micro system introduced Iterator interface.

2)Iterator
==========
It is used to retrieve the objects one by one from any Collection object.Hence it is known as universal cursor.
Using Iterator interface we can perform read and remove operation.

We can create Iterator object by using iterator() method.

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);
}
System.out.println(al);//[1,2,3,4,5,6,7,8,9,10]

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

limitations with Iterator


----------------------------
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 limitation sun micro system introduced ListIterator interface.

3)ListIterator
================
It is a child interface of Iterator interface.

It is used to read objects one by one from List Collection objects.

Using ListIterator we can read objects in forward direction and backward direction.Hence it is a bi-directional
cursor.

Using ListIterator we can perform read, remove ,adding and replacement of new objects.

We can create ListIterator interface by using listIterator() method.

ex:
ListIterator litr=al.listIterator();

ListIterator interface contains following 9 methods.

ex:
public boolean hasNext()
public Object next()
public boolean hasPrevious()
public Object previous()
public void remove();
public void add(Object o);
public void set(Object o);
public void nextIndex();
public void previousIndex();

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

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

}
}

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

ListIterator litr=al.listIterator();
while(litr.hasNext())
{
String s=(String)litr.next();
if(s.equals("nag"))
{
litr.remove();
}
}
System.out.println(al);//[venki, chiru, bala]
}
}

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

ListIterator litr=al.listIterator();
while(litr.hasNext())
{
String s=(String)litr.next();
if(s.equals("nag"))
{
litr.add("Chetu");
}
}
System.out.println(al);//[venki, nag, Chetu, chiru, bala]
}
}

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

ListIterator litr=al.listIterator();
while(litr.hasNext())
{
String s=(String)litr.next();
if(s.equals("nag"))
{
litr.set("Chetu");
}
}
System.out.println(al);//[venki, Chetu, chiru, bala]
}
}

Interview question
====================
Q) Write a java program to find out number of characters occurrence in String?
Example
Input:
java
Output:
j=1, a=2, v=1

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

public static void findDuplicatesCharacters(String str)


{
LinkedHashMap<Character,Integer> lhm=new LinkedHashMap<Character,Integer>();
for(int i=0;i<str.length();i++)
{

char c=str.charAt(i);
if(lhm.get(c)!=null)
{
lhm.put(c,lhm.get(c)+1);
}
else
{
lhm.put(c,1);
}
}
System.out.println(lhm);
}
}

Multithreading
==============
Q) What is the difference between Thread and Process?

Thread
-------
Thread is a light weight sub process.
We can run multiple threads concurently.
One thread can communicate with another thread.
ex:
class is one thread
block is one thread
constructor is one thread
and etc.

Process
--------
Process is a collection of threads.
We can run multiple process concurently.
One process can't communicate with another process.
ex:
Typing the notes in editor is one process
downloading a file from internet is one process
taking class from zoommeeting is one process.
Q) What is multitasking?

Executing several task simultenously such concept is called multitasking.

There are two types of multitasking.

1) Thread based multitasking

2) Process based multitasking

1) Thread based multitasking


-----------------------------
Thread based multitasking is best suitable for programmatic level.

Executing several task simultenously where each task is a same part of a program.

2) Process based multitasking


-----------------------------
Process based multitasking is best suitable for operating system level.

Executing several task simultenously where each task is a independent process.

Q) What is multithreading ?

Executing several threads simultenously such concept is called multithreading.

The main objective of multithreading is to improve performance of an application.

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)
{
//instantiate a thread
MyThread t=new MyThread();

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

case 1 : Thread Schedular


---------------------------
If multiple threads are waiting for execution which thread will execute decided by thread
schedular.

What algorithm, behaviour or mechanism used by thread schedular is depends upon JVM vendor.

Hence we won't expect any execution order or exact output in multithreading.

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


------------------------------------------------
If we invoke t.start() method then 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)
{
//instantiate 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 then 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)
{
//instantiate 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 overload run() method


----------------------------------
If we overload run() method then Thread class start() method always execute run() method with zero
argument 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)
{

MyThread t=new MyThread();


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

case4: 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)
{

MyThread t=new MyThread();


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

case5: Life Cycle of a Thread


-------------------------------

Diagram: java43.1

Once if we create a thread then our thread will be in New or Born state.
Once if we invoke t.start() method then our thread goes to ready/runnable state.

If thread schedular allocates to CPU then our thread enters to running state.

Once the run() method execution is completed then our thread goes 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");
}
}
}

Setting and Getting Name of a thread


====================================
In java , every thread has a name automatically generated by JVM or explicitly provided by the programmer.
We have following methods to set and get name of a thread.

ex:
public final void setName()
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 automatically generated by 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 priority.


ex:
Thread.MAX_PRIORITY - 10
Thread.MIN_PRIORITY -1
Thread.NORM_PRIORITY - 5

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

A thread which is having highest priority will executed first.

If multiple threads having same priority then we can't expect any execution order.

A thread schedular uses thread priority while allocating to CPU.

We have following methods to set and get thread priority.


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

//t.setPriority(11);//R.E IllegalArgumentException
}
}

In how many ways we can 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 current execution thread and gives the chance to other threads having same priority.

If there is no waiting threads then same thread will continue it's execution.

If multiple threads having same priority then we can't expect any execution order.

ex:
public static native void yield()

Diagram: java43.2

ex:
---
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 thread then we need to join() method.

A join() method throws one checked exception 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.3

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 operation on perticular amount of time then we need to use sleep()
method.
A sleep() method throws one checked exception called InterruptedException so we must and should handle
that exception by using try and catch block or using throws 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.4

ex:
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");
}
}
}

Daemon Thread
=============
Daemon thread is a service provider thread which provides services to user threads.

Life of deamon thread is depends upon user threads.

Deamon thread will die automatically when there is no user threads.

There are many deamon threads are running internally like Garbage Collector, Finalizer 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");
}
}
}

Problems without synchronization


===============================
If there is no synchronization then we will face following problems.

1) Data inconsistency

2) Thread interference

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
===============
Lock Mechanism

synchronized method
synchronized block
static synchronization

Inter-Thread Communication
----------------------------
wait(), notify() and notifyAll() method

DeadLock
---------

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 or SAM interface.

The main objective of funtional interface is used to achieve functional programming.


ex:
i=f1()
{
}

f1(f2(){})
{}
@FunctionalInterface annotation is used to declare functional interface which is optional.

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)
{
A a=new A()
{
public void m1()
{
System.out.println("M1-Method");
}
};
a.m1();
}
}

Lamda Expression
================
Lamda expression introduced in java 1.8v.

Lamda expression is used to concise the code.

We can use lamda expression when we have functional interface.

Lamda expression consider as method not a class.

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("M1-Method");
}

Lamda expression
-----------------
()->
{
System.out.println("M1-Method");
};

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

class Test
{
public static void main(String[] args)
{
A a=()->
{
System.out.println("From 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,50));

}
}

default methods in interface


============================
Java provides facility to declare default methods in interface.
If we declare any method inside the interface and tagged with default keyword then it is called
default method.

Default methods are non-abstract method.

Default methods can be override.

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

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:
---
interface A
{
public abstract void m1();

default void m2()


{
System.out.println("m2-Method");
}
}
class B implements A
{
public void m1()
{
System.out.println("M1-Method");
}
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();
}
}

Using default methods of an interface we acieve multiple inheritance in java.

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();
}
}
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()
{
Left.super.m1();
}
}
class Test
{
public static void main(String[] args)
{
Middle m=new Middle();
m.m1();
}
}

Static methods in interface


---------------------------
Java provides facility to declare static methods in interface.

If we declare any method inside the interface and tagged with static keyword then it is called
static method.

Static methods are non-abstract methods.

Static methods can't be override.

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

Stream API
===========
Stream API is used to perform bulk operations on Collection.

Stream is an interface which is present in java.util.stream package.

Stream API is used to process the objects from Collections.

ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(6,2,9,1,3,5,7,4);

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

System.out.println(newList);
}
}

ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(6,2,9,1,3,5,7,4);

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

System.out.println(newList);
}
}

ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(6,2,9,1,3,5,7,4);

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

System.out.println(newList);
}
}

ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(6,2,9,1,3,5,7,4);

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

System.out.println(evens);
}
}

ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(6,2,9,1,3,5,7,4);

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

System.out.println(newList);
}
}

ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(6,2,9,1,3,5,7,4);

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

System.out.println(newList);
}
}

ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(6,2,9,1,3,5,7,4);

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

System.out.println(min);
}
}

ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(6,2,9,1,3,5,7,4);

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

System.out.println(max);
}
}

forEach() method
================
A forEach() method introduced in Java 1.8v.

IT is used to iterate the objects from Collections.

ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(6,2,9,1,3,5,7,4);

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


}
}

ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
Map<Integer,String> map=new LinkedHashMap<Integer,String>();
map.put(1,"one");
map.put(10,"ten");
map.put(5,"five");

map.forEach((key,value)-> System.out.println(key+"="+value));
}
}

Method reference (::)


=====================
It is introduced in Java 1.8 version.

Method references are a special type of lambda expressions.

ex:
---
import java.util.*;
import java.util.stream.*;
class Test
{
public static void main(String[] args)
{
List<Integer> list=Arrays.asList(7,3,9,1,4,6);

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

MHR interview Question


=======================

Q) Write a java program to display employee details in ascending 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> l=new ArrayList<Employee>();
l.add(new Employee(104,"Alan",4000d));
l.add(new Employee(101,"Jose",1000d));
l.add(new Employee(102,"Kelvin",2000d));
l.add(new Employee(103,"Mark",3000d));
List<Employee> newList=l.stream().

sorted(Comparator.comparingInt(Employee::getEmpId)).collect(Collectors.toList());

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


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

You might also like