0% found this document useful (0 votes)
117 views89 pages

Java 1.8 Core Concepts and Features

The document outlines key features of Java 1.8, including its object-oriented nature, support for multi-threading, and various data types. It also covers access specifiers, constructors, methods, and inheritance concepts, along with several example programs demonstrating these features. Additionally, it discusses the use of getters and setters for encapsulation in Java.

Uploaded by

jeevachandru423
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
117 views89 pages

Java 1.8 Core Concepts and Features

The document outlines key features of Java 1.8, including its object-oriented nature, support for multi-threading, and various data types. It also covers access specifiers, constructors, methods, and inheritance concepts, along with several example programs demonstrating these features. Additionally, it discusses the use of getters and setters for encapsulation in Java.

Uploaded by

jeevachandru423
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

Java 1.

8 features
--------------------------
1)Java is Object Oriented programming Language.
2)Java is simpler then c and c++ as we don't have pointer concept,Multiple
Inheritance,operator overloading.
3)Java supports multi-threading or multi-tasking.
4)We can develop web-application,network application,standalone application and
also mobile application.
5)In java we interface which support the concept of multiple inheritance.
6)In java we have constructor but no [Link] is automatic garbage
clearance.
7)java is secured [Link] have 4 access specifier
private,public,protected,default.

------------------------------------------
Data types
---------------------------------------------------------
primative datatype
-------------------------
1)byte - 1 byte
2)short - 2 bytes
3)int - 4 bytes
4)long - 8 bytes
5)char - 2 bytes
6)boolen - 1 bit
7)float - 4 bytes
8)double - 8 bytes
-----------------------------------------
derived datatype
----------------------------
1)String
2)array
----------------------------------------
Operator
-------------------
1)unary :-i++,++i,i--,--i

2)binary :-
i)arithmatic :- +,-,*,/,%(modules)
ii)comparative :- <,>,<=,>=
iii)assignment :- =,!=
iv)bitwise :- >>,<<
3)ternary :- :,?
--------------------------------------
we have 4 access specifier private,public,protected,default.

1)private :- if we declare variable and methods as private we can access it within


the class only.
2)public :- if we declare variable and methods as public we can access it within
the class,outside the class and also outside the package.
3)protected :- if we declare variable and methods as protected we can access it
within the class and also outside the child class.
4)default :- if we declare variable and methods as default we can access it within
the class ,out side the class but not outside the package.
-----------------------------------------------------------------------------------
-------------------------------------
program-1
----------------
package monday;
public class First
{
public static void main(String[] args)
{
[Link]("Welcome to JDK1.8");
}
}
-------------------------------------------------
program-2
----------------------
package monday;

public class First


{
public static void main(String[] args)
{
byte a=10;
short b=20;
int c=30;
long d=40;
float e=5.6f;
double f=6.7;
String g="apple";
char h='a';
[Link](a+" "+b+" "+c);
[Link](d+" "+e+" "+f);
[Link](g+" "+h);
}
}
----------------------------------------------------------------
Class :- A class is a known as object framework.
A class contains variables and methods.
---------------------------------------------------------------------
Object is a reference pointer to the class.
We can access the variables and methods of a class using Object.
------------------------------------------------------------------------------
program-3
---------------------
package monday;
import [Link].*;
import [Link].*;
public class First
{
int empno;
String name,address;
void input()
{
Scanner ob=new Scanner([Link]);
[Link]("enter empno,name,address");
empno=[Link]();
name=[Link]();
address=[Link]();
}
void display()
{
[Link]("the empno is "+empno);
[Link]("the emp name is "+name);
[Link]("the emp address is "+address);
}
public static void main(String[] args) {
First obj=new First();
[Link]();
[Link]();
}
}

----------------------------------------------------------------------------------
Question-1
wap to enter a student data and display it.
rollno,name,physics,chem,maths marks.
-------------------------------------------------------------------------
Program-4
---------------------
package monday;
import [Link].*;
import [Link].*;
public class First
{
int rollno;
String name,address;
float phy,chem,math,total;
void input()
{
Scanner ob=new Scanner([Link]);
[Link]("enter rollno,name,address,phy,chem,math");
rollno=[Link]();
name=[Link]();
address=[Link]();
phy=[Link]();
chem=[Link]();
math=[Link]();
}
void display()
{
[Link]("the rollnono is "+rollno);
[Link]("the name is "+name);
[Link]("the address is "+address);
[Link]("phy"+phy+" chem"+chem+"math"+math);
[Link]("the total is "+(phy+chem+math));
}
public static void main(String[] args) {
First obj=new First();
[Link]();
[Link]();
}
}

-----------------------------------------------------------------------------------
-----------------
Constructor
-----------------------------
A constructor is a method which has the same name as that of the class name.
It doesnot return any [Link] doesnot have any return type.
There are 2 types of constructor
1)default constructor :- it is without any parameter.
2)parameterized constructor :- it is with parameter.
To access a constructor we require an object.
-----------------------------------------------------
program-5
--------------------
package monday;
import [Link].*;
class first
{
int rollno;//intance variable
String name,address;
first()
{
[Link]("this is a default constructor which is without any
parameter");
}
first(int rollno,String name,String address)//local variable
{
[Link]=rollno;//to differenciate between intance variable and local
variable we use this
[Link]=name;//keyword.
[Link]=address;
}
void display()
{
[Link]("the rollno is "+rollno);
[Link]("the name is "+name);
[Link]("the address is "+address);
}
}
class second
{
public static void main(String[] args) {
first ob=new first();
first ob1=new first(101,"ajay","bangalore");
first ob2=new first(102,"trupti","orissa");
[Link]();[Link]();
}
}
-------------------------------------------------------------
Difference between constructor and a method.
-----------------------------------------------------------------
1)a method can have any name but a constructor will have only the class name .
2)a method returns a value but constructor doesnot return any value.
----------------------
program-6
---------------------
package monday;
import [Link].*;
class first
{
int rollno;//intance variable
String name,address;
first()
{
[Link]("this is a default constructor which is without any
parameter");
}
first(int rollno,String name,String address)//local variable
{
[Link]=rollno;//to differenciate between intance variable and local
variable we use this
[Link]=name;//keyword.
[Link]=address;
}
void display()
{
[Link]("the rollno is "+rollno);
[Link]("the name is "+name);
[Link]("the address is "+address);
}
int sum(int a,int b) //method overloading
{
return a+b;
}
float sum(float a,float b)
{
return a+b;
}
}
class second
{
public static void main(String[] args) {
first ob=new first();
first ob1=new first(101,"ajay","bangalore");
first ob2=new first(102,"trupti","orissa");
[Link]();[Link]();
[Link]([Link](6, 6));//compiler will decide where to send the
value
[Link]([Link](6.5f, 6.3f));

}
}
-----------------------------------------------------------------------
Question-2
wap to create a parameterized constractor .pass the values and display it.
employee :- empno,name,designation,salary.
-----------------------------------------------------------------------------------
--------------------------
program-7
---------------------
package monday;
import [Link].*;
class first1
{
int empno;//intance variable
String name,address;
first1()
{
[Link]("this is a default constructor which is without any
parameter");
}
first1(int rollno,String name,String address)//local variable
{
[Link]=rollno;
[Link]=name;
[Link]=address;
}
void display()
{
[Link]("the rollno is "+empno);
[Link]("the name is "+name);
[Link]("the address is "+address);
}

}
class second2
{
public static void main(String[] args) {
first1 ob=new first1();
first1 ob1=new first1(101,"ajay","bangalore");
first1 ob2=new first1(102,"trupti","orissa");
[Link]();[Link]();

}
}
-----------------------------------------------------------------------------------
-
setter() is used to set the values
getter() is used to get the values
-----------------------------------------------------------------
program-8
-----------------------
package monday;

public class Employee


{
int empno;
String name,designation;
float salary;
//right click >source >generate getter and setter
public int getEmpno() {
return empno;
}
public void setEmpno(int empno) {
[Link] = empno;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
[Link] = designation;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
[Link] = salary;
}

}
------------------------------------------------------------
package Wednesday;

public class Student


{
int rollno;
String name,email;
public int getRollno() {
return rollno;
}
public void setRollno(int rollno) {
[Link] = rollno;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
[Link] = email;
}

}
--------------------------------------------------------------------------
package Tuesday;
import [Link];
import [Link];
public class Test
{
public static void main(String[] args)
{
Employee ob=new Employee();
[Link](101);
[Link]("Trupti");
[Link]("software eng");
[Link](45000.50f);
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
Student ob1=new Student();
[Link](102);
[Link]("Madhu");
[Link]("Madhu@[Link]");
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
}

-----------------------------------------------------------------------------------
----------
Program-9
-------------------
package Tuesday;
import [Link].*;
public class ArrayDemo
{
public static void main(String[] args)
{
Scanner ob=new Scanner([Link]);
[Link]("enter 5 nos");
int a[]=new int[5];
for(int i=0;i<5;i++)
a[i]=[Link]();

[Link]("the 5 nos are");


for(int i=0;i<5;i++)
[Link](a[i]);
}
}
----------------------------------------------------------
Program-10
--------------------
package Tuesday;
import [Link].*;
public class Student1
{
String rollno,name,address;
void input()
{
Scanner ob=new Scanner([Link]);
[Link]("Enter rollno,name,address");
rollno=[Link]();//it excepts space in between
name=[Link]();
address=[Link]();
}
void display()
{
[Link]("the rollno is "+rollno);
[Link]("the name is "+name);
[Link]("the address is "+address);
}
public static void main(String[] args) {
Student1[] obj=new Student1[3];
for(int i=0;i<3;i++)
{
[Link]("enter data of student no"+(i+1));
obj[i]=new Student1();
obj[i].input();
}
for(int i=0;i<3;i++)
{
[Link]("data of student no"+(i+1));
obj[i].display();
}

}
}
----------------------------------------------------------------------
question-3
create a bank class
accno,name,email,Balance for 20 customers.
store the data and display it.
-------------------------------------------------------------------------------
Inheritance
----------------------
It is one of the oops concept
Reuse of existing [Link] we can add some more features to it.
example :- iPhone10 to iPhone11 some new features are add to the older version.
There are 5 types of Inheritance.
1)single Inheritance
2)multi-level Inheritance
3)hyrarchal Inheritance
----------------------Java doesn't support---------------------------------
4)multiple inheritance
5)Hybrid inheritance(combination)
-----------------------------------------------------------------------------------
-
we use the keyword extends to inherite the parent class into the child class.
we use the keyword super to access the parent class variables and methods into the
child class.
-----------------------------------------------------------------------------------
--
Program-11
------------------------
package Tuesday;
import [Link].*;
public class Student
{
int rollno;
String name,address;
void input()
{
Scanner ob=new Scanner([Link]);
[Link]("enter rollno,name,address");
rollno=[Link]();
name=[Link]();
address=[Link]();
}
void display()
{
[Link]("the rollno is"+rollno+"the name is "+name+"the address is
"+address);
}
}
--------------------------------------------------------
package Tuesday;
import [Link].*;
public class Marks extends Student
{
int phy,chem,math,total,avg;
String grade;
void input()
{
[Link]();
Scanner ob=new Scanner([Link]);
[Link]("enter phy,chem,math marks");
phy=[Link]();
chem=[Link]();
math=[Link]();
total=phy+chem+math;
avg=total/3;
if(avg>70)
grade="First Grade";
else if(avg>60)
grade="Second Grade";
else if(avg>50)
grade="Third Grade";
else
grade="Fail";
}
void display()
{
[Link]();
[Link]("the total is "+total);
[Link]("the average is "+avg);
[Link]("The grade is "+grade);
}
public static void main(String[] args)
{
Marks ob=new Marks();
[Link]();
[Link]();
}
}
--------------------------------------------------------------------------------
wap to create a multi-level Inheritance
employee class :-empno,name,address
dept class:- loc,designation,dept
salary class :- salary,Hra,Itax
display the employee details
-----------------------------------------------------------------------------
How to use constructor during inheritance.
--------------------------------------------------------------------
program-12
----------------------------
package Tuesday;
public class Student
{
int rollno;
String name,address;
Student(int rollno,String name,String address)
{
[Link]=rollno;
[Link]=name;
[Link]=address;
}
void display()
{
[Link]("the rollno is"+rollno+"the name is "+name+"the address is
"+address);
}
}

-----------------------------------------------------------------------------------
--------
package Tuesday;
import [Link].*;
public class Marks extends Student
{
int phy,chem,math,total,avg;
String grade;
Marks(int rollno,String name,String address,int phy,int chem,int math)
{
super(rollno,name,address);
[Link]=phy;
[Link]=chem;
[Link]=math;
total=phy+chem+math;
avg=total/3;
if(avg>=70)
grade="First Grade";
else if(avg>=60)
grade="Second Grade";
else if(avg>=50)
grade="Third Grade";
else
grade="Fail";
}
void display()
{
[Link]();
[Link]("the total is "+total);
[Link]("the average is "+avg);
[Link]("The grade is "+grade);
}
public static void main(String[] args)
{
Marks ob=new Marks(101,"sandip","Bangalore",77,88,66);
[Link]();
}
}
-----------------------------------------------------------------------------------
---------
program-13
-------------------------
package Tuesday;
public class Student
{
int rollno;
String name,address;
Student(int rollno,String name,String address)
{
[Link]=rollno;
[Link]=name;
[Link]=address;
}
void display()
{
[Link]("the rollno is"+rollno+"the name is "+name+"the address is
"+address);
}
}
-------------------------------------------------
package Tuesday;
import [Link].*;
public class Marks extends Student
{
int phy,chem,math,total,avg;
String grade;
Marks(int rollno,String name,String address,int phy,int chem,int math)
{
super(rollno,name,address);
[Link]=phy;
[Link]=chem;
[Link]=math;
total=phy+chem+math;
avg=total/3;
if(avg>=70)
grade="First Grade";
else if(avg>=60)
grade="Second Grade";
else if(avg>=50)
grade="Third Grade";
else
grade="Fail";
}
void display()
{
[Link]();
[Link]("the total is "+total);
[Link]("the average is "+avg);
[Link]("The grade is "+grade);
}

}
----------------------------------------------------------------------
package Tuesday;

public class Address extends Marks


{
String loc;
Address(int rollno, String name, String address, int phy, int chem, int
math,String loc)
{
super(rollno, name, address, phy, chem, math);
[Link]=loc;
}
void display()
{
[Link]();
[Link]("the location is "+loc);
}
public static void main(String[] args) {
Address ob=new Address(1001,"sandip","Bangalore",77,77,55,"north bangalore");
[Link]();
}
}
-------------------------------------------------------------------------
*super constructor will execute first.
-----------------------------------------------------------------------
In inheritance the child class will depend upon the parent [Link] is known as
tight coupling.
Java supports loose coupling.
Inheritance(IS-A) relationship.
Aggregation(HAS-A) relationship.
example:-
Employee has-a address
Bank has-a customer
-----------------------------------------------------------------------------------
--
program-14
---------------------
package Wednesday;

public class Employee


{
int empno;
String name,phoneno;
Address address;
public Employee(int empno, String name, String phoneno, Address address) {
[Link] = empno;
[Link] = name;
[Link] = phoneno;
[Link] = address;
}
void display()
{
[Link]("empno :"+empno+"Name :"+name+"phone
no :"+phoneno+"address :"+address);
}
}
----------------------------------------------------------------
package Wednesday;

public class Address


{
int streetno,roadno;
String city,state;
public Address(int streetno, int roadno, String city, String state)
{
[Link] = streetno;
[Link] = roadno;
[Link] = city;
[Link] = state;
}

@Override
public String toString() {
return "Address [streetno=" + streetno + ", roadno=" + roadno + ", city=" +
city + ", state=" + state + "]";
}

public static void main(String[] args)


{
Address address=new Address(10,20,"Bangalore","Karnataka");
Employee emp=new Employee(101,"sandip","7766554433",address);
[Link]();
}
}
-----------------------------------------------------------------------------------
----------------
wap to enter details of a (HAS-A)
Bank has-a customer
bank :- accno,branch,balance,customer(object of the customer class)
Customer :- custid,name,address
--------------------------------------------------------------------
Method Overloading:-
Method Overriding:-
Abstract class
Interface
static keyword
final keyword
-----------------------------------------------------------------------------------
------------------------------
polymorphism:-
Method Overloading :- compile time [Link] need one class.
The method name is same but the return type and parameter has different data type.
example:-
int sum(int a,int b);
float sum(float a,float b);
--------------------------------------------------------
program-15
-------------------
package Wednesday;

public class MethodOverloading


{
int sum(int a,int b)
{
return a+b;
}
int sum(int a,int b,int c)
{
return a+b+c;
}
float sum(float a,float b)
{
return a+b;
}
double sum(double a,double b)
{
return a+b;
}
public static void main(String[] args) {
MethodOverloading ob=new MethodOverloading();
[Link]("the sum is "+[Link](6, 7));
[Link]("the sum is "+[Link](6,7,8));
[Link]("the sum is "+[Link](6.5f, 7.3f));
[Link]("the sum is "+[Link](6.53, 7.32));
}
}

-----------------------------------------------------------------------------------
-------------------
Method Overriding:- runtime Polymerphism.(abstract class,Interface).we need two or
more class.
-----------------------------------------------------------------------------------
-------------------
program-16
---------------------
package Wednesday;
class Parent
{
void display()
{
[Link]("This is a parent class");
}
}
public class MethodOverriding extends Parent
{
void display()
{
[Link]("this is new display method");
}
public static void main(String[] args)
{
MethodOverriding ob=new MethodOverriding();
[Link]();
}
}

-----------------------------------------------------------------
Here in the parent class we have the display().
In the child class we have display().We are creating object of the child class.
The child class display() is overriding on the parent class display().The parent
class display() is hidden.
----------------------------------------------------------------------------
Abstract class
------------------------
It is a class which contain abstract method means method without body.
It can also contain method with body known as concret method.
we cannot create object of the abstract class.
we have to inherite it into a child class where we have to override the abstract
methods.
Then we can create object for the child class.
We cannot have a method without body .we have to declare it as abstract or it
should be inside the interface.
What is the use of abstract class.
It contains some abstract methods which has to be overriden inside the child class.
We can have a constructor in the abstract class.
*abstract windowing toolkit(AWT)

-------------------------------------------------------------------
program-17
------------------
package Wednesday;
abstract class Abstract1
{
Abstract1()
{
[Link]("this is a constractor");
}
abstract void display();
int sum(int a,int b)
{
return a+b;
}
}
class AbstractDemo extends Abstract1
{
@Override
void display()
{
[Link]("This is display");
}
public static void main(String[] args) {
AbstractDemo ob=new AbstractDemo();
[Link]("the sum is "+[Link](6, 3));
[Link]();
}
}
-----------------------------------------------------------------------------
Program-18
---------------------
package Wednesday;
abstract class Abstract1
{
Abstract1()
{
[Link]("this is a constractor");
}
Abstract1(int a,int b)
{
[Link]("the sum of super constrctor is "+(a+b));
}
abstract void display();
int sum(int a,int b)
{
return a+b;
}
}
class AbstractDemo extends Abstract1
{
AbstractDemo()
{
super();
}
AbstractDemo(int a,int b)
{
super(a,b);
}
@Override
void display()
{
[Link]("This is display");
}
public static void main(String[] args) {
AbstractDemo ob=new AbstractDemo(7,8);
AbstractDemo ob1=new AbstractDemo();
[Link]("the sum is "+[Link](6, 3));
[Link]();
}
}
--------------------------------------------------------------------------
Create a abstract class bank
having abstract methods register(),apply for loan,credit card,dedit card.
create a child class customer .override all the methods and create object.
-----------------------------------------------------------------------------------
---------
Interface:-
It is similar to abstract class but it only contains abstract methods no concrete
[Link] don't use the keyword abstract in this.
We cannot create object for an interface.
We have to implement the interface into a child class.
We have to override the abstract methods into a child class and create object for
the child class.
By interface java performs the multiple Inheritance.
we can declare a variable inside a interface .this is by default static(we can
access it without object )
and final(cann't be changed)
-----------------------------------------------------------------------------------
---------------
progarm-19
-----------------------
package Wednesday;
interface Interface1
{
void display1();
}
interface Interface2 extends Interface1
{
void display2();
}
interface Interface3
{
void display3();
}
interface Interface4
{
void display4();
}
class InterfaceDemo implements Interface2,Interface3,Interface4
{
@Override
public void display1() {
[Link]("display1"); }
@Override
public void display4() {
[Link]("display4"); }
@Override
public void display3() {
[Link]("display3"); }
@Override
public void display2() {
[Link]("display2");
}
public static void main(String[] args) {
InterfaceDemo ob=new InterfaceDemo();
ob.display1(); ob.display2(); ob.display3(); ob.display4();
}
}

-----------------------------------------------------------------------------------
--------------------------------
program-20
-------------------------
package Wednesday;
interface Interface1
{
int a=10;//this is by default static(we can access it without object and
final(cann't be changed)
void display1();
}
interface Interface2 extends Interface1
{
void display2();
}
interface Interface3
{
void display3();
}
interface Interface4
{
void display4();
}
class InterfaceDemo implements Interface2,Interface3,Interface4
{
@Override
public void display1() {
[Link]("display1"); }
@Override
public void display4() {
[Link]("display4"); }
@Override
public void display3() {
[Link]("display3"); }
@Override
public void display2() {
[Link]("display2");
}
public static void main(String[] args)
{
[Link]("the value of a is "+a);
InterfaceDemo ob=new InterfaceDemo();
ob.display1(); ob.display2(); ob.display3(); ob.display4();
}
}

-----------------------------------------------------------------------------------
------------------------------------
static :- we can declare a variable as static,method as static,we can have static
block and we can have static class.
We can access it without creating an object.
We can access it with the help of the class name.
A single copy of the static variable,method,block or class is created in the JVM.
It is used for memory management.
If we declare a static block it execute before the main method.
---------------------------
progarm-21
---------------------------
package Wednesday;
public class StaticDemo
{
static int rollno=10;
static String name="trupti";
static String address="orissa";
static void display()
{
[Link](rollno+ " "+name+" "+address);
}
static
{
[Link]("This is a static block");
}
public static void main(String[] args)
{
[Link]("rollno is "+rollno);
[Link]("the name is "+[Link]);
[Link]("the address is"+[Link]);
display();
[Link]();
}}

-----------------------------------------------------------------------------------
-----------
we cannot access a non-static variables inside a static method.
we can access static variables inside a non-static method.
program-22
----------------------
package Wednesday;
public class StaticDemo
{
static int rollno=10;
static String name="trupti";
static String address="orissa";
static void display()//we cannot access a non-static variable inside a static
method.
{
[Link](rollno+ " "+name+" "+address);
}
static
{
[Link]("This is a static block");
}
public static void main(String[] args)//we cannot access a non-static variable
inside a static method.
{
[Link]("rollno is "+rollno);
[Link]("the name is "+[Link]);
[Link]("the address is"+[Link]);
display();
[Link]();
}}
--------------------------------------------------------
Once incremented the static variable value remain incremented.
program-23
--------------------------

package Wednesday;
public class StaticDemo
{
static int rollno=10;
static String name="trupti";
static String address="orissa";
static int i;
static void display()//we cannot access a non-static variable inside a static
method.
{
[Link](rollno+ " "+name+" "+address);
}
static void counter()
{
i++;
[Link](i);
}
static
{
[Link]("This is a static block");
}
public static void main(String[] args)//we cannot access a non-static variable
inside a static method.
{
[Link]("rollno is "+rollno);
[Link]("the name is "+[Link]);
[Link]("the address is"+[Link]);
display();
[Link]();
counter();
counter();
counter();
counter();
}}
-----------------------------------------------------------------------------------
-----------------
final keyword
-------------------------
This is a done to protect the data.
We can declare the variable as final,method as final and class as final.
If we declare variable as final we have to assign it and it cannot be changed.
If we declare method as final we cannot override it.
If we declare a class as final we cannot inherite it.
-----------------------------------------------------------------------------------
---------------
program-24
-----------------------
package Wednesday;
public final class FinalDemo
{
final int a=10;
final void display()
{
[Link]("this is final display");
}
public static void main(String[] args) {
FinalDemo ob=new FinalDemo();
[Link]();
[Link]("the value of a is"+ob.a);
}
}
------------------------------------------------------------------------------
create an interface employee :-
input details(empno,name,address);
display details();
-------------------------------------------------
create an interface dept:-
input deatils(deptno,name,loc)
display deatils();
------------------------------------------------------
create a child class to take input and display the details
-----------------------------------------------------------------------------------
---
static class:- It is used in the case of inner class.A inner class can be static.
syntax:-
class outer
{
static int rollno=20;
static class inner
{
}
main
{
[Link] obj=new [Link]();
}}
---------------------------------------------------------------
program-25
------------------------
package Thrusday;

public class OuterClass


{
static int rollno=10;//class variable,global variables can be accessed anywhere
within the program
static String name="sandip";
static class inner
{
void display()
{
[Link]("The rollno is "+rollno);
[Link]("The name is "+name);
}
}
public static void main(String[] args)
{
[Link] obj=new [Link]();
[Link]();
}
}
------------------------------------------------------------------
we can take the class as public or default.
we cannot declare the class as private or protected.
Because the class has to be accessed by the JVM which is out side the class.
JVM can access default or public access specifier.
-------------------------------------------------------------------------
Wrapper class
----------------------
All datatypes in java are also class known as wrapper class.
1)byte -Byte
2)short - Short
3)int - Integer
4)float - Float
5)double - Double
6)String
7)long - Long
8)char - Character
9)boolean - Boolean
These class belongs to lang [Link] is a default package.
---------------------------------------------------------------------
javap [Link] package ---->Integer
javap [Link]
javap [Link] -------super class in java.
------------------------------------------------------------------
program-26
----------------------
package Thrusday;
public class Test1
{
public static void main(String h[])
{
String a=h[0];
String b=h[1];
String c=h[2];
int x=[Link](a);
int y=[Link](b);
int z=[Link](c);
int sum=x+y+z;
[Link]("the sum is "+sum);
}
}
--------------------------------------------------------------------
package Thrusday;
public class Test1
{
public static void main(String h[])
{
String a=h[0];
String b=h[1];
String c=h[2];
float x=[Link](a);
float y=[Link](b);
float z=[Link](c);
float sum=x+y+z;
[Link]("the sum is "+sum);
}
}
----------------------------------------------------------
public static void main(String h[])

public is a access specifier so that JVM can access the main method which is
outside the package.
static is used so that we can access static variables and methods inside [Link] we
need not create object of the main()
void is the return type.
main is the keyword for making the method as main.
(String h[]) -- we can pass string arguments inside it.
-----------------------------------------------------------------------------------
----------
constructor :-
First obj=new First();
First is the class name.
obj is the reference pointer to the class.
new is a keyword which creates the memory block for storing the data.
First() is a default constructor.
-----------------------------------------------------------------------------------
--------------------------
Exception Handling
------------------------------
There are 3 type of error.
1)compile time error.(manually)
2)logical error(manually)
3)runtime error.
In exception handling we will discuss about only runtime error.
example:-
-------------------
1)dividing a number by zero.
2)crossing the array limit.
3)entering a character in place to number.
The aim of exception handling is we don't want the program to terminate in between.
The program should display an error message but the flow of the program should be
till the end.
----------------------------------------------------------------------------
There are 5 keywords used to handle the runtime errors.
1)try
2)catch
3)finally
4)throw
5)throws
-----------------------------------------------------------------------------------
-------------
program-27
----------------------
//The main purpose is to run the program till the end
//[Link] the program is terminated we have to handle the
error.
//we have to put into a try ,catch [Link] we suspect that error may occur.

package Thrusday;
import [Link].*;
public class ErrorExample
{
public static void main(String[] args)
{
try
{
Scanner ob=new Scanner([Link]);
[Link]("Enter 2 nos");
int a=[Link]();
int b=[Link]();
int c=a/b;
[Link]("The result is "+c);
}
catch(Exception ae)
{
[Link]("the error is "+ae);
}
[Link]("The end of the program");
}
}
-----------------------------------------------------------------
In this case when there is error means we divide the number by zero.
The catch will execute and display the error [Link] the rest part of the
program will execute.
-----------------------------------------------------------------------------------
--------------------
when there is no error the catch block will not [Link] program will execute
normally.
-----------------------------------------------------------------------------------
---------------
There are 3 type of Exception
--------------------------------------------
1)checked exception(we have to handle it first otherwise it will give compile time
error.)
i)IOException
ii)SQLException
iii)ClassNotFoundException
iv)Interrupted Exception
-----------------------------------------------------------------
2)unchecked exception
i)Arithmatic exception
ii)NumberFormat exception
iii)IndexOutOfBound exception
iv)NullPointer exception
--------------------------------------------
3)error
i)StackOverFlow error
ii)OutOfMemory error
iii)Machine error
-----------------------------------------------
program-28
-------------------------
Try with multiple catch
-------------------------------------
//try with multiple catch
package Thrusday;
import [Link].*;
public class ErrorExample
{
public static void main(String[] args)
{
try
{
Scanner ob=new Scanner([Link]);
[Link]("Enter 2 nos");
int a=[Link]();
int b=[Link]();
int c=a/b;
[Link]("The result is "+c);
}
catch(ArithmeticException ae)
{
[Link]("the error is "+ae);
}
catch(InputMismatchException ae)
{
[Link]("the errorr is "+ae);
}
catch(Exception ae) //this can handle all types of error
{
[Link]("the errorrr is "+ae);
}
[Link]("The end of the program");
}
}
-------------------------------------------------------------------------
* we cannot put the catch(Exception ae) above the catch(ArithmeticException ae) or
catch(InputMismatchException ae).
This will show error unreachable code.
because catch(Exception ae) will handle all type of [Link]
catch(ArithmeticException ae) will handle only Arithmatic exception.
-----------------------------------------------------------------------------------
---------------------------------------------
We generally don't write so many catch block .It will increase the line of code.
and the execution time also [Link] it in not adviceable to write multiple
catch block.
--------------------------------------------------------------------
try-catch :-if try is getting error then the catch with handle the error and catch
will display the error.
try-finally:-In this if try gets a error or not it doesn't matter the finally block
will definatelly exceute.
It handles the error and mainly used for closing of connection,file closing etc.
Can we write try block without catch block.
yes using finally block.
-----------------------------------------------------------------------------------
---------------------------------
Example-29
---------------------------
//try with finally
package Thrusday;
import [Link].*;
public class ErrorExample
{
public static void main(String[] args)
{
try
{
Scanner ob=new Scanner([Link]);
[Link]("Enter 2 nos");
int a=[Link]();
int b=[Link]();
int c=a/b;
[Link]("The result is "+c);
}

finally
{
[Link]("The end of the program");
}
}
}
-----------------------------------------------------------------------------------
-------------------------------
throws Exception:-
-------------------------------
we don't require any body for throws exception .we mention it with the method.
This is mostly used with checked exception.
when we work with IOException,SQLException,Interrupted Exception etc.
------------------------------------------------------------------
program-30
-----------------------
package Thrusday;
public class ErrorExample
{
public static void main(String[] args) throws Exception
{
for(int i=1;i<=10;i++)
{
[Link](i);
[Link](1000);//interrupt the flow of control
}
}
}
---------------------------------------------------------------------------
*sleep is a static method so we call it using the class name.
Thread is a class belongs to lang package.
[Link](1000);
------------------------------------------------------------------
throw keyword
--------------------------------
It is used for user defined exception.
example :-
1)age should be greater than or equal to 18 years to cast your vote.
2)salary of employee should be greater than 15000.
3)marks should be greater than zero.
------------------------------------------------------------------------
program-31
---------------------
package Thrusday;
import [Link].*;
public class ErrorExample
{
public static void main(String[] args) throws Exception
{
Scanner ob=new Scanner([Link]);
[Link]("enter your age to cast your vote");
int age=[Link]();
if(age>=18)
[Link]("your are eligible to cash your vote");
else
throw new Exception("The age should be greater than or equal to 18 to
caste your vote");
}
}
----------------------------------------------------------------------------
ArrayIndexOutOfBound Exception(crossing the array limit)
----------------------------------------------------------------------
This error occur when we cross the array limit.
example :- if the array size is 5 and we are entering 6 elements it will throw an
error that is ArrayIndexOutOfBound exception.
-----------------------------------------------------------------------------------
---------------------
program-32
-----------------------
package Thrusday;
import [Link].*;
public class ErrorExample
{
public static void main(String[] args) throws Exception
{
try
{
int a[]=new int[5];
Scanner ob=new Scanner([Link]);
[Link]("enter 5 nos");
for(int i=0;i<5;i++)
a[i]=[Link]();
[Link]("5 nos are");
for(int i=0;i<=5;i++)
[Link](a[i]);
}
catch(Exception ae)
{
[Link]();
}

}
}
-----------------------------------------------------------------------------------
-----------------------------
wap to enter am employees data.
1)empno it should only contain number.
2)name
3)age it should be greater than 20 years to do this job.
4)qualification should be Btech.
if all the critaria are ok then he/she is eligible to do the job
-----------------------------------------------------------------------------------
-----------
program-33
-------------------
package Friday;
import [Link].*;
class GFG
{
public static void main (String[] args)throws Exception
{
Scanner ob=new Scanner([Link]);
try
{
[Link]("enter empno :");
String str =[Link]();
int num = [Link](str);
}
catch(NumberFormatException ex)
{
[Link]("Enter only number");
}
finally
{
[Link]("Enter name,age and qualification");
String name=[Link]();
int age=[Link]();
String qual=[Link]();
if(age>=20 && [Link]("btech"))
[Link]("you are eligible");
else
throw new Exception("not eligible");
}
}
}
----------------------------------------------------------------------------------
Lambda Expression
--------------------------------
It is also known as functional interface.
In this the interface will only contain one abstract method so it is called
functional interface.
In lambda expression we don't require 2 classes (parent and child).we don't have to
[Link] don't have to implement the interface.
There is a anotation @FunctionalInterface.
It is used to declare an interface as functional interface.(optional)
------------------------------------------------------------------------
@Override :- It was introduced from [Link] will match the methods of the parent
class and the child class.
both method name and the signatures(return type,parameter) should match.(optional)
-------------------------------------------------------------------------
what is the use of lambda expression
1)The code is reduced in this.
2)To provide the implementation of functional interface.
3)Generally a interface is non-functional we have to override into the child class
and introduce some functionality.
example:-
interface bank
{
void loan(); <------these are non-functional
void applyforCreditCard();
}
------------------------------------------------------------------
*by using lambda expression we will make the interface as functional.
----------------------------------------------------------------------
There are 3 new components in it.
1)Arguument-list:-It can be empty or have parameters.
(),->,{body}
2)Arrow-token:- It is used to link arguments-list and body of the expression.
3)Body:- It contains the expression and statement .
-----------------------------------------------------------------------------------
---------
()->{[Link]("Hello");} //no parameter
----------------------------------------------------------------
(a)->{[Link]("Hello");} //single parameter
----------------------------------------------------------------
(a,b)->{[Link]("Hello");} //multiple parameter
----------------------------------------------------------------
program-34
--------------------
package Friday;
@FunctionalInterface
interface example1
{
public void display(); //only one abstract method
}
public class Lambda1
{
public static void main(String[] args)
{
int length=10;
int breadth=20;
example1 obj=()->
{
[Link]("the length is "+length);
[Link]("the breadth is "+breadth);
[Link]("the area is "+(length*breadth));
};
[Link]();
}
}
-----------------------------------------------------------------------------------
-
program-35
-------------------
package Friday;
@FunctionalInterface
interface example1
{
public void display(); //only one method
}
@FunctionalInterface
interface example2
{
public String name();
}

@FunctionalInterface
interface example3
{
public String address(String loc);
}
@FunctionalInterface
interface example4
{
public int sum(int a,int b);
}

public class Lambda1


{
public static void main(String[] args)
{
int length=10;
int breadth=20;
example1 obj=()-> //display method defined
{
[Link]("the length is "+length);
[Link]("the breadth is "+breadth);
[Link]("the area is "+(length*breadth));
};
[Link]();

example2 obj1=()->
{
return "Lambda Expression";
};
[Link]([Link]());

example3 obj2=(loc)->
{
return "My Loaction is :"+loc;
};
[Link]([Link]("Bangalore"));

example4 obj3=(a,b)->(a+b);
[Link]("the sum is "+[Link](400,500));

}
}
-----------------------------------------------------------------------------------
----
package Friday;
@FunctionalInterface
interface example1
{
public void display(); //only one method
}
@FunctionalInterface
interface example2
{
public String name();
}

@FunctionalInterface
interface example3
{
public String address(String loc);
}
@FunctionalInterface
interface example4
{
public int sum(int a,int b);
}

public class Lambda1


{
public static void main(String[] args)
{
int length=10;
int breadth=20;
example1 obj=()-> //display method defined
{
[Link]("the length is "+length);
[Link]("the breadth is "+breadth);
[Link]("the area is "+(length*breadth));
};
[Link]();

example2 obj1=()->
{
return "Lambda Expression";
};
[Link]([Link]());

example3 obj2=(loc)->
{
return "My Loaction is :"+loc;
};
[Link]([Link]("Bangalore"));

example4 obj3=(a,b)->
{
return a+b;
};
[Link]("the sum is "+[Link](400,500));
}}
-----------------------------------------------------------------------------------
wap to enter amount for withdraw or deposite.
Then display the balance amount.
Use case and switch and FunctionalInterface.
---------------------------------------------------------------------
We have 3 classes String,StringBuffer,StringBuilder
--------------------------------------------------------------------------
String :-Immutable(cannot be changed).
StringBuffer:-mutable(can be changed)
StringBuilder:-mutable(can be changed)
---------------------------------------------------------------------------
Progarm-36
----------------
package Friday;
public class StringDemo
{
public static void main(String[] args) {
String s1="apple";
String s2="apple";
String s3=new String("apple"); //new memory block is created
String s4=new String("apple");
if(s1==s2) //constant pool
[Link]("true");
else
[Link]("false");
if([Link](s2))
[Link]("true");
else
[Link]("false");
if(s1==s3)
[Link]("true");
else
[Link]("false");
}
}
------------------------------------------------------------------------
program-37
-----------------------
package Friday;
public class StringDemo
{
public static void main(String[] args) {
String s1="Marlabs Software Solution";
String s2="Mphasis Software Solution";
[Link](s1);
[Link]([Link]());
[Link]([Link]());
[Link]([Link]('M'));//starts from 0
[Link]([Link]('S'));
[Link]([Link](s2));
[Link]([Link](s2));
[Link]([Link](1));//starts from 1
[Link]([Link](5,6));
[Link]([Link](0));//starts from 0
[Link]([Link]("Marlabs"));//return true or false
[Link]([Link]("Solution"));
[Link]([Link]("Marlabs", "Marlab"));
[Link]([Link]());
char x[]=[Link]();//convert string to char array
int len=[Link];
[Link]("the length of the array is "+len);
for(int i=0;i<len;i++)
[Link](x[i]);
}
}

-----------------------------------------------------------------------------------
-
program-38
----------------------
package Friday;
public class StringBufferDemo
{
public static void main(String[] args)
{
StringBuffer s1=new StringBuffer("My name ") ;
StringBuffer s2=new StringBuffer("is sandip ") ;
StringBuffer s3=new StringBuffer("I am 40 years old");
[Link]([Link](s2));
[Link]([Link](s3));
[Link](s1);//mutable the value of the string is changed
[Link](0, 'm');
[Link](s1);
[Link](20);
[Link](s1);
[Link]([Link](20, " am a java Trainer"));
[Link]([Link](21, 25));
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
}
-----------------------------------------------------------------------------------
-----------
StringBuffer is synchronized.
with the methods we use the key word synchronized.
in this after one method complete then the second method start excecuting.
-----------------------------------------------------------------------------------
-------------------
StringBuilder is not synchronized.
StringBuffer takes more time to execute than StringBuilder.
Thread synchronized means one thread complete excecution then the next thread will
start execute.
example :-ATM (one person will do the transaction then the second person will do
the transaction).
-----------------------------------------------------------------------------------
------------------------------
Collection Framework
----------------------------------------
int a[]=new int[5]; ---------------array the size is fixed.
In case of Collection the size will be incrementing dyamically as we enter the
data.
---------------------------------------------------------------
It is a collection of Object.
It provides architecture to store,manupulate group of Objects.
We can do all operations such as searching,sorting,inserting,delete,manupulating .
1)Set 2)List 3)Map
Set is a Interface .It doesnot allow duplicate data.
It has classes :-
1)TreeSet :- It will display the data in the shorted order.
2)HashSet :-It will display the data in random order.
3)LinkedHashSet :- It will display the data in same order.
---------------------------------------------------------------------------------
program-39
---------------------
//TreeSet :- It will display the data in the shorted order.
package Friday;
import [Link].*;
public class SetDemo
{
public static void main(String[] args)
{
TreeSet<Integer> ts=new TreeSet<Integer>();
[Link](70);
[Link](20);
[Link](30);
[Link](10);
[Link](50);
[Link](50);
[Link](60);
[Link](ts);
}
}
---------------------------------------------------------------------------
//HashSet :-It will display the data in random order.
package Friday;
import [Link].*;
public class SetDemo
{
public static void main(String[] args)
{
HashSet<Integer> ts=new HashSet<Integer>();
[Link](70);
[Link](20);
[Link](30);
[Link](10);
[Link](50);
[Link](50);
[Link](60);
[Link](ts);
}
}
-----------------------------------------------------------------
LinkedHashSet :- It will display the data in same order.
package Friday;
import [Link].*;
public class SetDemo
{
public static void main(String[] args)
{
LinkedHashSet<Integer> ts=new LinkedHashSet<Integer>();
[Link](70);
[Link](20);
[Link](30);
[Link](10);
[Link](50);
[Link](50);
[Link](60);
[Link](ts);
}
}
-----------------------------------------------------------------------------------
-----
Program-40
-----------------------
package Friday;
public class Student
{
int rollno;
String name,address;
public Student(int rollno, String name, String address) {
super();
[Link] = rollno;
[Link] = name;
[Link] = address;
}
@Override
public String toString() {
return "Student [rollno=" + rollno + ", name=" + name + ", address=" +
address + "]";
}

}
-----------------------------------------------------------------------------------
----
package Friday;
import [Link].*;
public class SetDemo
{
public static void main(String[] args)
{
Student ob=new Student(101,"sandip","bangalore");
Student ob1=new Student(102,"shubam","bangalore");
Student ob2=new Student(103,"trupti","bangalore");

LinkedHashSet<Student> ts=new LinkedHashSet<Student>();


[Link](ob);
[Link](ob1);
[Link](ob2);
[Link](ts);
}
}
-----------------------------------------------------------------------------------
---------------
wap to enter data of few employees into a LinkedHashSet and display it.
empno,name,salary
-----------------------------------------------------------------------------------
-------------------
AutoBoxing and Unboxing
------------------------------------------
The autoboxing convert the primative data types into it equivalent Wrapper type.
The unboxing convert the wrapper type to primative datatype.
-----------------------------------------------------------------------------------
----
Example
-------------------
package Friday;
public class AutoBoxingDemo
{
public static void main(String[] args) {
int a=10;//primative data type to wrapper class convertion is known as
autoboxing
Integer b=new Integer(a);
[Link](b);
}
}
--------------------------------------------------
package Friday;
public class UnBoxingDemo
{
public static void main(String[] args) {
Integer b=new Integer(10);//wrapper class to primative data type conversion
int a=b;
[Link](b);
}
}
----------------------------------------------------------------
Example-41
--------------------
package monday;
import [Link].*;
public class SetDemo
{
public static void main(String[] args)
{
TreeSet<Integer> ts=new TreeSet<Integer>();
[Link]([Link]());//to check if the TreeSet is empty or not returns
a boolean value
[Link]([Link]());
[Link](70);
[Link](20);
[Link](30);
[Link](10);
[Link](50);
[Link](50);
[Link](60);
[Link]([Link]());
[Link]([Link]());
[Link]([Link](10));//searching .return boolean value
[Link]([Link](100));
[Link]([Link]());
[Link](50);//remove the object
[Link](ts);
[Link](); //remove all the objects
[Link](ts);
[Link]([Link]());
}
}
------------------------------------------
for each Demo
---------------------
package monday;
import [Link].*;
public class SetDemo
{
public static void main(String[] args)
{
TreeSet<Integer> ts=new TreeSet<Integer>();
[Link]([Link]());//to check if the TreeSet is empty or not returns
a boolean value
[Link]([Link]());
[Link](70);
[Link](20);
[Link](30);
[Link](10);
[Link](50);
[Link](50);
[Link](60);
[Link]("***********************");
//for each loop
for(Object obj:ts)//the ts value will be stored into the obj one by one and we will
print the obj.
[Link](obj);
[Link]("***********************");
}
}
-------------------------------------------
Iterator :- it is used to iterate the data .It is an Iterface.
It has 3 methods
1)hasNext();
2)next();
3)remove();
--------------------------------------------------------------
example-42
----------------------
package monday;
import [Link].*;
public class SetDemo
{
public static void main(String[] args)
{
TreeSet<Integer> ts=new TreeSet<Integer>();
[Link](70);
[Link](20);
[Link](30);
[Link](10);
[Link](50);
[Link](50);
[Link](60);
[Link]("***********************");
//for each loop
for(Object obj:ts)//the ts value will be stored into the obj one by one and we will
print the obj.
[Link](obj);
[Link]("***********************");
Iterator itr=[Link]();
while([Link]())
{
[Link]([Link]());
}
}
}
--------------------------------------------------------------------------------
List :-It is an Interface.
It allows duplicate records.
We have classes 1)Stack 2)ArrayList 3)Linkedlist 4)Vector
stack :FILO .The last element will be index 0.
List display in the same order.
---------------------------------------------------------------
example-43
-------------------
package monday;
import [Link].*;
public class ListDemo
{
public static void main(String[] args)
{
Stack<Integer> st=new Stack<Integer>();
[Link](10);//insert the data
[Link](20);
[Link](30);
[Link](40);
[Link](50);
[Link](60);
for(Object obj:st)
[Link](obj);
[Link]("********************************");
[Link]([Link]());//delete the data
[Link]([Link]());//to see the last data
[Link]([Link]());//delete the data
[Link]("********************************");
for(Object obj:st)
[Link](obj);
}
}
-----------------------------------------------------------------------------------
------------
example-44
---------------------
package monday;
import [Link].*;
public class ListDemo
{
public static void main(String[] args)
{
Stack<Integer> st=new Stack<Integer>();
[Link](10);//insert the data
[Link](20);
[Link](30);
[Link](40);
[Link](50);
[Link](60);
for(Object obj:st)
[Link](obj);
[Link]("********************************");
[Link]([Link]());//delete the data
[Link]([Link]());//to see the last data
[Link]([Link]());//delete the data
[Link]("********************************");
for(Object obj:st)
[Link](obj);
[Link]("********************************");
//jdk1.8
[Link]((x)->[Link](x));//The wrapper class super class is Object
[Link]([Link](10));//It will return the position of [Link] is last
[Link]([Link](20));
[Link]([Link](200));
}
}
----------------------------------------------------------------------------
package monday;
import [Link].*;
public class ListDemo
{
public static void main(String[] args)
{
Stack<Integer> st=new Stack<Integer>();
[Link](10);//insert the data
[Link](20);
[Link](30);
[Link](40);
[Link](50);
[Link](60);
for(Object obj:st)
[Link](obj);
[Link]("********************************");
[Link]([Link]());//delete the data
[Link]([Link]());//to see the last data
[Link]([Link]());//delete the data
[Link]("********************************");
for(Object obj:st)
[Link](obj);
[Link]("********************************");
//jdk1.8
[Link]((x)->[Link](x));//The wrapper class super class is Object
[Link]([Link](10));//It will return the position of 10.
[Link]([Link](20));
[Link]([Link](200));//element not found it displays -1
try
{
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
catch(Exception ae)
{
[Link]("Stack is empty");
}
}
}
-----------------------------------------------------------------------------------
Example-45
------------------------
Linked List
----------------------
package monday;
import [Link].*;
public class ListDemo
{
public static void main(String[] args)
{
LinkedList<Integer> ls=new LinkedList<Integer>();
LinkedList<Integer> ls1=new LinkedList<Integer>();
[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link](100);
[Link](200);
[Link](300);
[Link](400);
[Link]((x)->[Link](x));
[Link]("*******************");
[Link]((x)->[Link](x));
[Link]("*******************");
[Link](9);
[Link](99);
[Link]((x)->[Link](x));
[Link]("*******************");
[Link]((x)->[Link](x));
[Link]("*******************");
[Link]();
[Link]();
[Link]((x)->[Link](x));
[Link]("*******************");
[Link]((x)->[Link](x));
[Link]("*******************");
[Link]();
[Link]();
[Link]([Link]());
[Link]([Link]());
[Link](ls1);
[Link]("*******************");
[Link]((x)->[Link](x));
}
}
-----------------------------------------------------------------------------------
---
Interface to iterate the data:-
----------------------------------------------
Iterator:-hasNext(),next();remove();//In this we can move in one direction.
ListIterator:- In this we can move in both direction.
forward :- In this we have hasNext(),next().First the pointer with move in forward
direction then it will move in backward direction.
backword:- In this we have hasPrevious(),previous();
-----------------------------------------------------------------------------------
--------------------------
Example-46
--------------------------
package monday;
import [Link].*;
public class ListDemo
{
public static void main(String[] args)
{
LinkedList<String> ls=new LinkedList<String>();
[Link]("Trupti");
[Link]("Shubham");
[Link]("Madhu");
[Link]("Geetanjali");
[Link]("Sunil");
[Link]("Deepak");
[Link]("Forword Direction");
ListIterator<String> li=[Link]();
while([Link]())
{
[Link]([Link]());
}
[Link]("Backward Direction");
while([Link]())
{
[Link]([Link]());
}
}
}
-----------------------------------------------------------------------------------
--------------------
[Link]
---------------------------------------
It has lot of static methods which can be implemented ob set,list,map,queue
It this we have sort() which can sort a list,map,queue.
[Link]()
---------------------------------------------------
Example-47
----------------------
package monday;
import [Link].*;
public class ListDemo
{
public static void main(String[] args)
{
LinkedList<String> ls=new LinkedList<String>();
[Link]("Trupti");
[Link]("Shubham");
[Link]("Madhu");
[Link]("Geetanjali");
[Link]("Sunil");
[Link]("Deepak");
[Link](ls);
[Link]((x)->[Link](x));
}
}
-------------------------------------------------------------------------
package monday;
import [Link].*;
public class ListDemo
{
public static void main(String[] args)
{
LinkedList<Integer> ls=new LinkedList<Integer>();
[Link](10);
[Link](40);
[Link](30);
[Link](20);
[Link](50);
[Link](ls);
[Link]((x)->[Link](x));
[Link]("the largest no is "+[Link](ls));
[Link]("the smallest no is "+[Link](ls));
}
}
-----------------------------------------------------------------------------------
--------------
package monday;
import [Link].*;
public class ListDemo
{
public static void main(String[] args)
{
ArrayList<Integer> ls=new ArrayList<Integer>();
[Link](10);
[Link](40);
[Link](30);
[Link](20);
[Link](50);
[Link](ls);
[Link]((x)->[Link](x));
[Link]("the largest no is "+[Link](ls));
[Link]("the smallest no is "+[Link](ls));
}
}
-------------------------------------------------------------------------
package monday;
import [Link].*;
public class ListDemo
{
public static void main(String[] args)
{
ArrayList<Integer> ls=new ArrayList<Integer>();
[Link](10);
[Link](40);
[Link](30);
[Link](20);
[Link](50);
[Link](ls,[Link]());
[Link]((x)->[Link](x));
}
}
-----------------------------------------------------------------------------------
-------------------------
package monday;
import [Link].*;
public class ListDemo
{
public static void main(String[] args)
{
ArrayList<Integer> ls=new ArrayList<Integer>();
[Link]([Link](10));//it will convert Object to primative datatype
[Link]([Link](40));
[Link](30);//it internally convert object to primative datatype
[Link](20);
[Link](50);
[Link](ls,[Link]());
[Link]((x)->[Link](x));
}
}
-------------------------------------------------------------
[Link] :-
public abstract int compareTo(T);
it is used to sort our own object [Link] checks the String ascii code.
in this if the current object is greater than the specified object it return (+)
value.
in this if the current object is lesser than the specified object it return (-)
value.
in this if the current object is equal than the specified object it return zero
value.
-----------------------------------------------------------------------
Example-48
----------------------
package monday;

public class MarlabsEmp implements Comparable<MarlabsEmp>


{

String name;
MarlabsEmp(String name)
{
[Link]=name;
}
@Override
public int compareTo(MarlabsEmp obj)
{
return [Link]([Link]);
}}
-----------------------------------------------------------------------------------
---------------------------------------
package monday;
import [Link].*;
public class ListDemo
{
public static void main(String[] args)
{
ArrayList<MarlabsEmp> al=new ArrayList<MarlabsEmp>();
[Link](new MarlabsEmp("Geetanjali"));
[Link](new MarlabsEmp("Shubam"));
[Link](new MarlabsEmp("Deepak"));
[Link](new MarlabsEmp("Trupti"));
[Link](al);
for(MarlabsEmp ob:al)
[Link]([Link]);
}
}
-----------------------------------------------------------------------------------
---------
Example-47
---------------------
package monday;

public class MarlabsEmp implements Comparable<MarlabsEmp>


{
Integer empid;
String name;
MarlabsEmp(Integer empid,String name)
{
[Link]=empid;
[Link]=name;
}
@Override
public int compareTo(MarlabsEmp obj)
{
return [Link]([Link]);
}}

-----------------------------------------------------------
package monday;
import [Link].*;
public class ListDemo
{
public static void main(String[] args)
{
ArrayList<MarlabsEmp> al=new ArrayList<MarlabsEmp>();
[Link](new MarlabsEmp(104,"Geetanjali"));
[Link](new MarlabsEmp(103,"Shubam"));
[Link](new MarlabsEmp(102,"Deepak"));
[Link](new MarlabsEmp(101,"Trupti"));
[Link](al);
for(MarlabsEmp ob:al)
[Link]([Link]);
}
}
-----------------------------------------------------------------------------------
---
Map :-It is an interface.
In this we enter key and values pair.
The key should not be [Link] value can be duplicate.
The key and value pair is known as entry.
Map is useful to search,update or delete elements on the basis of the key.
-------------------------------------------------------------
Map --HashMap,LinkedHashMap,TreeMap(sorting)
-----------------------------------------------------------------------------------
Example-48
------------------
package monday;
import [Link].*;
public class HashMapDemo
{
public static void main(String[] args)
{
HashMap<Integer, String> hm=new HashMap<Integer, String>();
[Link](1, "Gitanjali");
[Link](2, "Subham");
[Link](3, "sandip");
[Link](4, "sunil");
[Link](5, "sunil");
[Link](4, "ajay");
Scanner ob=new Scanner([Link]);
[Link]("enter rollno and name");
int rollno=[Link]();
String name=[Link]();
[Link](rollno, name);
[Link](hm);
}
}
-------------------------------------------------------------------
Set set=[Link]();
Iterator itr=[Link]();
while([Link]())
{
[Link] en=([Link]<Integer, String>)[Link]();
[Link]([Link]()+ " "+[Link]());
}
-----------------------------------------------------------------------------------
----------
HashSet is converted to set because we don't the Interface Iterator in the
[Link] have it in Set.
entrySet() is used to convert the Map into set.
[Link] is a class contain getKey(),getValue()
-----------------------------------------------------------------------------------
--------------------
Example-49
--------------------
package monday;
import [Link].*;
public class HashMapDemo
{
public static void main(String[] args)
{
HashMap<Integer, String> hm=new HashMap<Integer, String>();
[Link](1, "Gitanjali");
[Link](2, "Subham");
[Link](3, "sandip");
[Link](4, "sunil");
[Link](5, "sunil");
[Link](4, "ajay");
Scanner ob=new Scanner([Link]);
[Link]("enter rollno and name");
int rollno=[Link]();
String name=[Link]();
[Link](rollno, name);
[Link](hm);
Set set=[Link]();
Iterator itr=[Link]();
while([Link]())
{
[Link] en=([Link]<Integer, String>)[Link]();
[Link]([Link]()+ " "+[Link]());
}}}
-----------------------------------------------------------------------------------
--------------------------
package monday;
import [Link].*;
public class HashMapDemo
{
public static void main(String[] args)
{
HashMap<Integer, String> hm=new HashMap<Integer, String>();
[Link](1, "Gitanjali");
[Link](2, "Subham");
[Link](3, "sandip");
[Link](4, "sunil");
[Link](5, "sunil");
[Link](4, "ajay");
Scanner ob=new Scanner([Link]);
[Link]("enter rollno and name");
int rollno=[Link]();
String name=[Link]();
[Link](rollno, name);
[Link](hm);
Set set=[Link]();
Iterator itr=[Link]();
while([Link]())
{
[Link] en=([Link]<Integer, String>)[Link]();
[Link]([Link]()+ " "+[Link]());
}
[Link]("********************");
for([Link]<Integer, String> m: [Link]())
[Link]([Link]()+ " "+[Link]());
[Link]("****************************");
[Link](4);
[Link](1,"Gitanjali");
[Link](2, "Ravi");
[Link](3,"sandip", "Ravi.k");
[Link]("********************");
for([Link]<Integer, String> m: [Link]())
[Link]([Link]()+ " "+[Link]());
[Link]("****************************");
}}
---------------------------------------------------------------------------
package monday;
import [Link].*;
public class HashMapDemo
{
public static void main(String[] args)
{
HashMap<Integer, String> hm=new HashMap<Integer, String>();
[Link](1, "Gitanjali");
[Link](2, "Subham");
[Link](3, "sandip");
[Link](4, "sunil");
[Link](5, "sunil");
[Link](4, "ajay");
Scanner ob=new Scanner([Link]);
[Link]("enter rollno and name");
int rollno=[Link]();
String name=[Link]();
[Link](rollno, name);
[Link](hm);
Set set=[Link]();
Iterator itr=[Link]();
while([Link]())
{
[Link] en=([Link]<Integer, String>)[Link]();
[Link]([Link]()+ " "+[Link]());
}
[Link]("********************");
for([Link]<Integer, String> m: [Link]())
[Link]([Link]()+ " "+[Link]());
[Link]("****************************");
[Link](4);
[Link](1,"Gitanjali");
[Link](2, "Ravi");
[Link](3,"sandip", "Ravi.k");
[Link]("********************");
for([Link]<Integer, String> m: [Link]())
[Link]([Link]()+ " "+[Link]());
[Link]("****************************");
[Link]((Integer,String)->"sandip");
[Link]("****************************");
for([Link]<Integer, String> m: [Link]())
[Link]([Link]()+ " "+[Link]());
[Link]();
[Link]("****************************");
for([Link]<Integer, String> m: [Link]())
[Link]([Link]()+ " "+[Link]());
[Link]("****************************");
}}
-----------------------------------------------------------------------------------
-----------
Example-50
-------------------------
package HashMapDemo;
import [Link].*;
public class Employee
{
int empid;
String name,address;
float salary;
public Employee(int empid, String name, String address, float salary)
{
super();
[Link] = empid;
[Link] = name;
[Link] = address;
[Link] = salary;
}
@Override
public String toString() {
return "Employee [empid=" + empid + ", name=" + name + ", address=" + address + ",
salary=" + salary + "]";
}}
-----------------------------------------------------------------------------------
----------------
package HashMapDemo;
import [Link].*;
public class HashMapExample
{
public static void main(String[] args)
{
HashMap<Integer,Employee> map=new HashMap<Integer,Employee> ();
Employee emp1=new Employee(101,"sandip","Bangalore",5600.50f);
Employee emp2=new Employee(102,"sunil","Bangalore",5700.50f);
Employee emp3=new Employee(103,"pradeep","Bangalore",5800.50f);
[Link](101, emp1);
[Link](102, emp2);
[Link](103, emp3);
Scanner ob=new Scanner([Link]);
[Link]("Enter the empno you want to search");
int empno=[Link]();

for([Link]<Integer, Employee> m: [Link]())


if([Link]()==empno)
[Link]([Link]()+ " "+[Link]());
}
}
-----------------------------------------------------------------------------------
------------------------------------
HashMap :- It gives high performance in the total data-structure of java collection
framework.
There are 2 factors which effect the performance of hashmap.
1)Initial Capacity.
2)Load Factor.
------------------------------------------
1)Initial Capacity is 16 bytes.
2)It increses automatically when it reaches to the threshold.
3)Initailly it is 2 pow 4=16,Then it will 2 pow 5=32,then it will be 2 pow 6=64
-----------------------------------------------------------------------------------
---------------------------------------
Load Factor :- is measured that decides when to increase the HashMap capacity to
maintain the get() and put() request.
-----------------------------------------------------------------------------------
---------------------------------------------

wap to create a BookShop where we have some books.(bookid,book name,price)


enter the book list into a HashMap.
if the book is sold remove from the list.
if the price of the book is increased modify the list.
if a person wants to search for the book he can put the bookid and see the book is
available or not.
finally display the total books available.
--------------------------------------------------------------------------------
Queue Interface
------------------------------
It maintains the first-in-first-out order.
It can be defined as an ordered list that is used to hold elements in the same
order.
The classes are PriorityQueue,Deque and ArrayDeque .
------------------------------------------------------------------
Example-51
---------------------
package HashMapDemo;
import [Link].*;
public class PriorityQueueDemo
{
public static void main(String[] args)
{
PriorityQueue<String> queue=new PriorityQueue<String>();
[Link]("Subham");
[Link]("Sandip");
[Link]("Geetanjali");
[Link]("Ajay");//first-in-first-out
[Link]([Link]());//this will display the head element
[Link]([Link]());//this will display the head element
[Link]([Link]());//this removes the head element
[Link]([Link]());//remove the head element
[Link]("************************************************");
Iterator itr=[Link]();
while([Link]())
{
[Link]([Link]());
}
[Link]("sunil");
[Link]("trupti");
[Link]("************************************************");
Iterator itr1=[Link]();
while([Link]())
{
[Link]([Link]());
}
[Link]("the head is "+[Link]());//this will display the head
element
}}
----------------------------------------------------------------------------
ArrayDeque :- It is a [Link] can remove and add the elements from both sides.
It is also called double-ended queue.
Example-52
----------------------
package HashMapDemo;
import [Link].*;
public class DequeDemo {
public static void main(String[] args) {
ArrayDeque<String> obj=new ArrayDeque();
[Link]("sunil");
[Link]("Subham");
[Link]("Sandip");
[Link]("Geetanjali");
[Link]("Ajay");
[Link]("Kiran");
[Link]("trupti");
[Link]([Link]());
[Link]([Link]());
[Link]("****************************************");
for(String abc : obj)
[Link](abc);
}
}
-----------------------------------------------------------------------------------
------------------
Example-1
-----------------------
//we want to convert Array to List.
//We manually have to traverse the array and add the element into list one by one.
//The array size is fix but the arraylist size increase dynamically.
package Wednesday;
import [Link].*;
public class ArrayToListDemo
{
public static void main(String[] args)
{
//array
String arr[]= {"Shubham","Geetanjali","Trupti","Ajay"};
[Link]("the array is :"+[Link](arr));
//Convert array to List
ArrayList<String> list=new ArrayList<String>();
for(String str:arr)
{
[Link](str);
}
[Link]("The list is :"+list);
}
}
-----------------------------------------------------------------------------------
---------------
Example-2
---------------------
//to convert List to Array
package Wednesday;
import [Link].*;
public class ListToArrayDemo
{
public static void main(String[] args)
{
ArrayList<String> list=new ArrayList<String>();
[Link]("apple");
[Link]("orange");
[Link]("grapes");
[Link]("strawberry");
[Link]("the list is :"+list);
//to convert List to Array we use toArray()
String arr[]=[Link](new String[[Link]()]);
[Link]("Print the array :"+[Link](arr));
}
}
---------------------------------------------------------------------------------
Properties class
-----------------------------
1)The properties object contains key and value pair both as string.
2)It belongs to [Link] class .It is a subclass of HashTable.
3)We get the properties value based on the properties key.
4)The advantage is we neednot to re-compile when the value in the properties files
is changed.
5)It is mostly useful during migration of project from one database to another
database (Example:Oracle9 to Oracle11)

Example :-
database setup
----------------------------
[Link]
----------------------------
user=system
password=1234
Driver=[Link]
connection=jdbc:oracle:thin:@localhost:1521:xe

[Link]=8090
--------------------------------------------------------------------------
Example-3
-------------------
package Wednesday;
import [Link].*;
import [Link].*;
public class PropertiesDemo
{
public static void main(String[] args)throws Exception
{
FileReader fr=new FileReader("[Link]");
Properties p=new Properties();
[Link](fr);

[Link]("the user name is :"+[Link]("user"));


[Link]("the password is :"+[Link]("password"));
[Link]("the Driver is :"+[Link]("Driver"));
[Link]("the connection is :"+[Link]("connection"));
//[Link]("the data base is :"+[Link]("Data"));
}
}
------------------------------------------------------------------------------
We have 2 interfaces to sort the data.
1)Comparable interface:-
It provides a single sorting sequence [Link] can sort a single element only.
In this we have a abstract method
public int compareTo(Student obj);//This will compare the single element of the
object which may be a rollno,name or age.
----------------
----------------------------------------------------------------------------------
2)Comparator interface.
We can sort a object of a class.
In this we have a abstract method
public int compare(Object ob1,Object ob2);//This will compare the first object with
the second object.
-----------------------------------------------------------------------------------
-----------------------------
Example-4
---------------------
package Wednesday;

public class Student implements Comparable<Student>


{
int rollno,age;
String name;

public Student(int rollno, int age, String name)


{
super();
[Link] = rollno;
[Link] = age;
[Link] = name;
}

@Override
public int compareTo(Student obj)
{
if(age==[Link])
return 0;
else if(age>[Link])
return 1;
else
return -1;
}

}
---------------------------------------------------------
package Wednesday;
import [Link].*;
public class ComparableDemo
{
public static void main(String[] args)
{
ArrayList<Student> al=new ArrayList<Student>();
[Link](new Student(101,21,"Trupti"));
[Link](new Student(102,24,"Shubam"));
[Link](new Student(103,22,"Ajay"));
[Link](new Student(104,23,"Madhu"));
[Link](al);
for(Student st:al)
[Link]([Link]+" "+[Link]+" "+[Link]);
}
}
-----------------------------------------------------------------------------------
--------------------
syntax :-
-------------
public int compare(Object o1, Object o2)
{
Employee ob1=(Employee) o1;
Employee ob2=(Employee) o2;
if([Link]==[Link])
return 0;
else if([Link] > [Link])
return 1;
else
return -1;
}
------------------------------------------------------------------------------
compare() has a logic to compare the int values.
if the 1st object age is greater than the second object age it will return (+)
value.
if the 1st object age is less than the second object age it will return (-) value.
if the 1st object age is equal than the second object age it will return (0) value.
we have age 23,22,21 .if first age is geater then the second the it return (+) and
the values are swapped.
we have age 22,23,21 .if first age is geater then the second the it return (+) and
the values are swapped.
we have age 22,21,23 .if first age is geater then the second the it return (+) and
the values are swapped.
we have age 21,22,23 .if first age is geater then the second the it return (+) and
the values are swapped.
-----------------------------------------------------------------------------------
-------------------------------------------
Example-5
----------------------
package Wednesday;
public class Employee
{
int empno,age;
String name;
public Employee(int empno, int age, String name) {
super();
[Link] = empno;
[Link] = age;
[Link] = name;
}

}
----------------------------------------------------------------
package Wednesday;
import [Link].*;
public class EmployeeAge implements Comparator
{
@Override
public int compare(Object o1, Object o2)
{
Employee ob1=(Employee) o1;
Employee ob2=(Employee) o2;
if([Link]==[Link])
return 0;
else if([Link] > [Link])
return 1;
else
return -1;
}

}
--------------------------------------------------------------------
package Wednesday;
import [Link].*;
public class EmployeeName implements Comparator
{
@Override
public int compare(Object o1, Object o2)
{
Employee ob1=(Employee) o1; //we are creating out own object and assigning it to
the compare() Object o1 and o2
Employee ob2=(Employee) o2;
return [Link]([Link]);
}
}
------------------------------------------------------------------------------
package Wednesday;
import [Link].*;
public class EmployeeMain
{
public static void main(String[] args)
{
ArrayList<Employee> al=new ArrayList<Employee>();
[Link](new Employee(101,21,"Shubham"));
[Link](new Employee(102,23,"Trupti"));
[Link](new Employee(103,22,"Ajay"));
[Link](new Employee(104,24,"Kiran"));

//Sorting by age
[Link](al,new EmployeeAge());
Iterator<Employee> itr=[Link]();
while([Link]())
{
Employee emp=[Link]();
[Link]([Link]+" "+[Link]+" "+[Link]);
}
[Link]("***************************************************");
//Sorting by name
[Link](al,new EmployeeName());
Iterator<Employee> itr1=[Link]();
while([Link]())
{
Employee emp=[Link]();
[Link]([Link]+" "+[Link]+" "+[Link]);
}
}
}
-----------------------------------------------------------------------------------
--------------------------------------------
Example-54
-------------------------
CompareTo
---------------------
package Collection;

public class Product


{
int id;
String name;
Float price;
public Product(int id, String name, Float price) {
super();
[Link] = id;
[Link] = name;
[Link] = price;
}}
-----------------------------------------------------------------------------------
-----------------------------
package Collection;
import [Link].*;
public class LambdaExpressionDemo
{
public static void main(String[] args)
{
ArrayList<Product> al=new ArrayList<Product>();
[Link](new Product(1,"Laptop",40000.35f));
[Link](new Product(2,"desktop",30000.35f));
[Link](new Product(3,"Keyboard",4000.45f));
[Link](new Product(4,"Mouse",300.00f));
//sort on basis of product price
[Link](al,(p1,p2)->{ //p1 and p2 are 2 object to compare
return [Link]([Link]);});

for(Product p:al)
[Link]([Link]+" "+[Link]+" "+[Link]);

//sorting on basis of product name


[Link]("*********************************************");

[Link](al,(p1,p2)->{
return [Link]([Link]);});

for(Product p:al)
[Link]([Link]+" "+[Link]+" "+[Link]);

}
}
-----------------------------------------------------------------------------------
---------------------------------
Filter Data
------------------
package Collection;
import [Link].*;
import [Link];
public class LambdaExpressionDemo
{
public static void main(String[] args)
{
ArrayList<Product> al=new ArrayList<Product>();
[Link](new Product(1,"Laptop",40000.35f));
[Link](new Product(2,"Desktop",30000.35f));
[Link](new Product(3,"Keyboard",4000.45f));
[Link](new Product(4,"Mouse",300.00f));
//sort on basis of product price
[Link](al,(p1,p2)->{
return [Link]([Link]);});

for(Product p:al)
[Link]([Link]+" "+[Link]+" "+[Link]);

//sorting on basis of product name


[Link]("*********************************************");

[Link](al,(p1,p2)->{
return [Link]([Link]);});

for(Product p:al)
[Link]([Link]+" "+[Link]+" "+[Link]);

[Link]("*****************Less than 5000***************************");


//filter the data example :- product less than Rs 5000
//we have a class --(Stream)
Stream<Product> fd=[Link]().filter(x -> [Link] < 5000);
[Link](product -> [Link]([Link]+" "+[Link]+"
"+[Link]));

[Link]("*****************Greater Than
5000***************************");
Stream<Product> fd1=[Link]().filter(x -> [Link] > 5000);
[Link](product -> [Link]([Link]+" "+[Link]+"
"+[Link]));
}
}
-----------------------------------------------------------------------------------
------------------------
Example -55
------------------------
EnumSet :- it sort the data according to the enum list provided.
----------------------------------
package Collection;
import [Link].*;
enum days { SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY}
public class EnumDemo
{
public static void main(String[] args)
{
EnumSet es=[Link]([Link],[Link],[Link],[Link]);
Iterator itr=[Link]();
while([Link]())
[Link]([Link]());
EnumSet es1=[Link]([Link]);
[Link]("the weeks days are :"+es1);
EnumSet es2=[Link]([Link]);
[Link]("the weeks days are :"+es2);
}
}
--------------------------------------------------------------------------------
EnumMap :- in this we will enter key and value pair.
---------------------------------------------------------------------------
Example-56
---------------------
package Collection;
import [Link].*;
enum day { SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY}
public class EnumMapDemo
{
public static void main(String[] args)
{
EnumMap<day, String> em=new EnumMap<day, String>([Link]);
[Link]([Link], "Taken Rest");
[Link]([Link], "Project Work");
[Link]([Link], "Collection");
for([Link] m:[Link]())
[Link]([Link]()+" "+[Link]());
}
}
-----------------------------------------------------------------------------------
---------------
Example-57
---------------------
how can I mention Time suppose today I have meeting from 2 to 6 and 7 to 8 another
meeting how can i display.
-------------------------------------------
package Collection;
public class MeetingDetails
{
int empid,roomno;
String name,Project,meetingstart,meetingend;
public MeetingDetails(int empid, int roomno, String name, String project, String
meetingstart, String meetingend)
{
super();
[Link] = empid;
[Link] = roomno;
[Link] = name;
Project = project;
[Link] = meetingstart;
[Link] = meetingend;
}
@Override
public String toString() {
return "MeetingDetails of Madhusudhan [empid=" + empid + ", roomno=" + roomno
+ ", name=" + name + ", Project=" + Project+ ", meetingstart=" + meetingstart + ",
meetingend=" + meetingend + "]";
}
}

-----------------------------------------------------------------------------------
-----
package Collection;
import [Link].*;
enum meet{Meeting1,Meeting2,Meeting3,Meeting4};
public class MeetingEnumMap
{
public static void main(String[] args)
{
EnumMap<meet, MeetingDetails> em=new EnumMap<meet, MeetingDetails>([Link]);
MeetingDetails ob1=new MeetingDetails(101,1,"Madhu","WMCG","2PM","6PM");
MeetingDetails ob2=new MeetingDetails(101,1,"Madhu","Product Lunch","6PM","8PM");
MeetingDetails ob3=new MeetingDetails(101,1,"Madhu","FMCG","8PM","10PM");
MeetingDetails ob4=new MeetingDetails(101,1,"Madhu","Windows-11","10PM","11.30
PM");
[Link](meet.Meeting1, ob1);
[Link](meet.Meeting2, ob2);
[Link](meet.Meeting3, ob3);
[Link](meet.Meeting4, ob4);
for([Link]<meet, MeetingDetails> ab:[Link]())
{
[Link]([Link]()+" "+[Link]());
}
}
}
-----------------------------------------------------------------------------------
----------------------------
Wap to enter names,shopping done for Chistmas (productname,price,shop/online)
and display it.(EnumMap).
-----------------------------------------------------------------------------------
-----------------
ArrayList and LinkedList Difference
-----------------------------------------------------------------
ArrayList :-
1)It internally use dynamic array to store the elements.
2)Manipulation of arraylist is slow.
3)We can add the element at the rear end.

LinkedList:-
1)It internally use double link list to store the elements.
2)Manipulation of Linkedlist is faster.
3)LinkedList class acts like a list and queue.
4)We can add the element at both the ends.
-----------------------------------------------------------------------------------
HashMap and HashTable Difference
-------------------------------------------------------
HashMap
1)It is not-synchronized .(not Thread safe we can use this with threads)
2)It allows one null key and multiple null values.
3)This faster than hashTable
4)It is traversed by Iterator.
5)It inherits AbstractMap class.
------------------------------------

HashTable
1)It is synchronized .(Thread [Link] can use with threads)
2)It doesn't allow any null key or value.
3)It is slower than HashMap.
4)It is traversed by Iterator and Enumerator.
5)It inherits Dictionary class.
-----------------------------------------------------------------------------------
----------
AbstractMap and Dictonary difference
----------------------------------------------------------
1)AbstractMap it is the super class of HashMap .we cann't intanceate the
AbstractMap so we have to create object of the HashMap.
-------------------------------------------
1)Dictionary it is the super class of HashTable .we cann't intanceate the
Dictionary so we have to create object of the HashTable.

------------------------------------------------------------------------------
package Collection;
import [Link].*;
public class DictonaryDemo
{
public static void main(String[] args)
{
Dictionary<String, String> d=new Hashtable<String, String>();//Dictionary is It is
abstract parent
[Link]("1","sandip");
[Link]("2","shubham");
[Link]("3","sunil");
[Link]("4","ajay");
for(Enumeration i=[Link]();[Link]();)
[Link]("the value are :"+[Link]());
}
}
-----------------------------------------------------------------------------
package Collection;
import [Link].*;
public class DictonaryDemo
{
public static void main(String[] args)
{
AbstractMap<String, String> d=new HashMap<String, String>();//AbstractMap is the
abstact parent class.
[Link]("1","sandip");
[Link]("2","shubham");
[Link]("3","sunil");
[Link]("4","ajay");
for([Link] ab:[Link]())
{
[Link]([Link]()+" "+[Link]());
}
}
}
-----------------------------------------------------------------------------------
-----------------------------------
Thread:-It is a sort of execution of instruction.

single Thread Program:- Till now we were doing single threaded programing the
program start execution from the main() till the end.
-----------------------------------------------------------------------------------
-------------
Multi Thread Program:-
Each thread will do some task.
We can create object of Thread and assign the task.
In this we will have run() and we will have start() .the start() will call the
run().
For this we can either extends Thread class or implement runnable interface.
There will be Thread switching .So we will see all the start() exceute at the same
time and the output will be a mixture of all the task.
-----------------------------------------------------------------------------------
-------------------
Thread lifecycle
--------------------------
new born thread
start
runnable(choose the thread)
running
block/wait/sleep
dead(excution is completed)
-----------------------------------------------------------------------------------
-------------
Example-58
----------------------
package Thread;

public class Thread1 extends Thread


{
public void run()
{
for(int i=1;i<=10;i++)
{
[Link]("Thread1"+" "+i);
try {
sleep(1000);//interrupts the flow of control
} catch (InterruptedException e) {
[Link]();
}
}
}
}
-------------------------------------------------------------------------
package Thread;

public class MainThread


{
public static void main(String[] args)
{
Thread1 ob=new Thread1();
Thread2 ob1=new Thread2();
Thread3 ob2=new Thread3();
[Link](); //start will call the run().At-a-Time all the run() will start
excuting concurrently.
[Link]();
[Link]();
}
}
----------------------------------------------------------------------------
Methods in Thread class
----------------------------------------
1)getName() :- It gets the name of Thread.

2)isAlive() :- It check if the Thread is still running or completed it's


[Link] returns boolean value.

3)run():- Entry point for the thread.

4)start():- It Starts a thread by calling the run().


5)sleep():- In this based on the requirement we can make a thread sleep or wait for
a specific time period.

6)setPriority():- we can set the thead priority.

7)getPriority():- we can get the thread priority.

8)MIN_PRIORITY= range (1 to 4)
NORM_PRIORITY= 5
MAX_PRIORITY=RANGE(6 to 10)

9)Daemon Thread :- It is a low priority thread which runs in the background doing
garbage collection operation.

10)wait() :- The thread will go to wait until some other thread doesnot notify.

11)notify():- Wake up a thread which is in waiting state.

12)notifyAll() :- This will wake up all the waiting threads.

----------------------------------------------------------------------------------
Example-59
---------------------
package Thread;

public class Thread4 extends Thread


{
public void run()
{
for(int i=1;i<=10;i++)
{
[Link]([Link]().getName()+" "+i);
try {
sleep(1000);
} catch (InterruptedException e) {
[Link]();
}
}

}
public static void main(String[] args)
{
Thread4 ob1=new Thread4();
Thread4 ob2=new Thread4();
Thread4 ob3=new Thread4();
[Link]([Link]());
[Link]();
[Link]([Link]());
[Link]();
[Link]();
}
}
-----------------------------------------------------------------
Example-60
----------------------
package Thread;
public class Thread5 implements Runnable
{
@Override
public void run() {

for(int i=1;i<=10;i++)
{
[Link]([Link]().getName()+" "+i);
try {
[Link](1000);
} catch (InterruptedException e) {
[Link]();
}
}
}
public static void main(String[] args)
{
Thread5 ob=new Thread5();
Thread obj1=new Thread(ob,"Shubham");
Thread obj2=new Thread(ob,"Madhu");
Thread obj3=new Thread(ob,"Shilpa");
[Link]();[Link]();[Link]();
}
}
---------------------------------------------------------------
Example-61
------------------------
package Thread;
public class Thread5 implements Runnable
{
@Override
synchronized public void run() {
try {
String name=[Link]().getName();
for(int i=1;i<=10;i++)
{
[Link](name+" "+i);
[Link](1000);
if([Link]("Shubham") && (i==4))
{
wait();
}
if([Link]("Madhu") && (i==4))
{
wait();
}
if([Link]("Shilpa") && (i==6))
{
notifyAll(); //wakeup all waiting Thread
}

if([Link]("Shubham") && (i==9))


{ notify(); //wakeup 1 thread

}}
catch(Exception ae)
{
[Link]();
}
}

public static void main(String[] args)


{
Thread5 ob=new Thread5();
Thread obj1=new Thread(ob,"Shubham");
Thread obj2=new Thread(ob,"Madhu");
Thread obj3=new Thread(ob,"Shilpa");
[Link]();[Link]();[Link]();
}
}
-----------------------------------------------------------------------------------
--
wap to find out who gets the tickects out of the 3 friends.
There are only 2 tickets available in the counter.
-----------------------------------------------------------------------------------
-------
Example-62
-----------------------
package Thread;

public class Thread4 extends Thread


{
public void run()
{
for(int i=1;i<=10;i++)
{
[Link]([Link]().getName()+" "+i);
try {
sleep(1000);
} catch (InterruptedException e) {
[Link]();
}
}

}
public static void main(String[] args)
{
Thread4 ob1=new Thread4();
Thread4 ob2=new Thread4();
Thread4 ob3=new Thread4();
[Link]([Link]());
[Link]();
[Link]([Link]());
[Link]();
[Link](MAX_PRIORITY);
[Link](MIN_PRIORITY);
[Link](NORM_PRIORITY);
[Link](10);
[Link](1);
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());

try {
[Link]();//waits for this thread to die then the other thread will
start executing.
} catch (InterruptedException e) {
[Link]();
}

[Link]();

}
}
-----------------------------------------------------------------------------------
------------------
Example-63
----------------------
package Thread;

public class Thread6


{
public static void main(String[] args)
{
Runnable r1=new Runnable()
{
public void run()
{
for(int i=1;i<=10;i++)
{
[Link](i);
try {
[Link](1000);
} catch (InterruptedException e) {
[Link]();
}
}
}
};
Thread t1=new Thread(r1);
[Link]();
Runnable r2=()->{
for(int i=1;i<=10;i++)
{
[Link]("Merry Christmas");
try {
[Link](1000);
} catch (InterruptedException e) {
[Link]();
}
}
};
Thread t2=new Thread(r2);
[Link]();
[Link]();//the method is deprecated
//[Link]();
}

}
-----------------------------------------------------------------------------------
-----
ThreadGroup:- In this we have a Parent and can have a child.
we can have a multiple ThreadGroups.
A thread is allowed to access information about its own thread group.
A thread is not allowed to access information from any other thread group.
-----------------------------------------------------------------------------------
----------------------------
Example-64
----------------------
package Thread;

public class ThreadGroupDemo implements Runnable


{

@Override
public void run() {
[Link]([Link]().getName());
}
public static void main(String[] args)
{
ThreadGroupDemo obj=new ThreadGroupDemo();
ThreadGroup tg=new ThreadGroup("First Parent Thread");

ThreadGroup tg1=new ThreadGroup("Second Parent Thread");

ThreadGroup tgc1=new ThreadGroup(tg,"The child Thread of First Parent Thread");

Thread t1=new Thread(tg,obj,"First Thread");


[Link]();
Thread t2=new Thread(tg,obj,"Second Thread");
[Link]();
Thread t3=new Thread(tg,obj,"Third Thread");
[Link]();
[Link]("The Thread Group name :"+[Link]());
[Link]();//This will display the list of Threads and there [Link] default
priority is 5 and the max priority is 10

Thread s1=new Thread(tg1,obj,"First Thread");


[Link]();
Thread s2=new Thread(tg1,obj,"Second Thread");
[Link]();
Thread s3=new Thread(tg1,obj,"Third Thread");
[Link]();
[Link]("The Thread Group name :"+[Link]());
[Link]();

Thread v1=new Thread("First Thread");


[Link]();
Thread v2=new Thread("Second Thread");
[Link]();
Thread v3=new Thread("Third Thread");
[Link]();
[Link]("The Thread Group name :"+[Link]());
[Link]();

}
}
-----------------------------------------------------------------------------------
---
destroy():- This will destroy the thread group and the [Link] we have to
destroy the child group then the parent.

Example-65
---------------------
package Thread;

public class DestroyDemo extends Thread


{
DestroyDemo(String tName,ThreadGroup tg)
{
super(tg,tName);
start();
}
public void run()
{
for(int i=1;i<=10;i++)
{
[Link](i);
try {
sleep(1000);
} catch (InterruptedException e) {
[Link]();
}
}
}
public static void main(String[] args) throws InterruptedException {
ThreadGroup tg=new ThreadGroup("The parent Thread");
ThreadGroup tg1=new ThreadGroup(tg,"The child Thread");
DestroyDemo th1=new DestroyDemo("The first thread",tg);
DestroyDemo th2=new DestroyDemo("The first thread",tg);
[Link](); //wait until the thread finish the execution.
[Link]();
[Link]();
[Link]([Link]() +" is destroyed");
[Link]();
[Link]([Link]() +" is destroyed");
}
}
-----------------------------------------------------------------------------------
--------------
Example-66
----------------------
package Thread;

public class DestroyDemo extends Thread


{
DestroyDemo(String tName,ThreadGroup tg)
{
super(tg,tName);
start();
}
public void run()
{
for(int i=1;i<=10;i++)
{
[Link](i);
try {
sleep(1000);
} catch (InterruptedException e) {
[Link]();
}
}
}
public static void main(String[] args) throws InterruptedException
{
ThreadGroup tg=new ThreadGroup("The parent Thread");
ThreadGroup tg1=new ThreadGroup(tg,"The child Thread");
DestroyDemo th1=new DestroyDemo("The first thread",tg);
DestroyDemo th2=new DestroyDemo("The first thread",tg);
[Link]();
[Link](); //wait until the thread finish the execution.
[Link]();

[Link]();
[Link]([Link]() +" is destroyed");
[Link]();
[Link]([Link]() +" is destroyed");
if([Link]()==true)
{
[Link]("The group is removed");
}
else
{
[Link]("The group is not removed");
}
if([Link]()==true)
{
[Link]("the child is Destroyed");
}
else
{
[Link]("the child is not destroyed");
}

}
}
-----------------------------------------------------------------------------------
--------
Garbage Collection
-----------------------------
DaemonThread is a low priority thread which runs in the background to do garbage
collection.
The garbage collection is done for unreferenced objects.
It removes unreferenced objects so that memory can be reclaimed again for use.
It destroys the unused objects.
Java is memory efficient because the unreferenced Objcet is removerd from the heap
memory .
for it we use finalize().
1)The finalize() is invoked each time before the object is garbage collected.
it is used for cleanup processing.
It is define in Object class.
-----------------------------------------------------------------------------------
----------------------
2)gc()
this method is used to invoke the garbage collector to do the cleanup process.

It is found in the System and Runtime class.


-----------------------------------------------------------------------------------
------------------
Example :-66
-------------------
package Thread;
public class GarbageDemo
{
public void finalize()
{
[Link]("the object is going to garbage collection");
}
public static void main(String[] args) {
GarbageDemo ob1=new GarbageDemo();
GarbageDemo ob2=new GarbageDemo();

ob1=null;
ob2=null;
[Link]();
}
}
-----------------------------------------------------------------------------------
------------
example-67
---------------------
package Thread;
public class StudentDemo
{
int rollno;
String name,address;
public void finalize()
{
[Link]("the object is going to garbage collection");
}
public StudentDemo(int rollno, String name, String address) {
super();
[Link] = rollno;
[Link] = name;
[Link] = address;
}

@Override
public String toString() {
return "StudentDemo [rollno=" + rollno + ", name=" + name + ", address=" +
address + "]";
}

}
-----------------------------------------------
package Thread;

public class GarbageDemo


{

public static void main(String[] args) {


StudentDemo ob1=new StudentDemo(101,"Madhu","hyd");
StudentDemo ob2=new StudentDemo(102,"Sandip","Bangalore");
[Link](ob1);
[Link](ob2);
ob1=null;
ob2=null;
[Link]();
[Link]("the corrent value is "+ob1);
[Link]("the corrent value is "+ob2);
}
}
--------------------------------------------------------------------------------
Thread pool:- It means where the Threads are strore in reserved and used when they
are needed.
The threads can be reused again and again.
Example :- Indian Army .
The thread pool represent a group of worker threads that are waiting for the job
and can be reused.
In the thread pool a fixed size threads are created.
newFixedThreadPool(10); //creates a pool of 10 Threads.
The thread from the thread pool is pulled out and assigned a job by the service
provider.
After the job is completed it is contained in the thread pool [Link] is not
destroyed.
-----------------------------------------------------------------------------------
-------------------------------
methods of Thread pool
-------------------------------------------
1)newFixedThreadPool(10); //creates a pool of 10 Threads.

2)newCachedThreadPool();//This method creates a new thread pool but use the


previously created thread when ever they are available.

3)newSingleThreadExecutor();//This method creates a new thread.


4)ExecutorService :- It is used to create FixedThreadPool(5).
5)Executor :-It is used to execute the threads in the Thread Pool.
6)import [Link] :- This package is used for creating ThreadPool .
7)![Link]()) //it is checking each and every thread that it is terminated
after the task is done
-----------------------------------------------------------------------------------
--------------------------------------
Example-68
------------------------
package Thread;

public class ThreadPoolDemo implements Runnable


{
String msg;
ThreadPoolDemo(String x)
{
[Link]=x;
}
@Override
public void run() {
[Link]([Link]().getName()+" Start Thread ="+msg);

try {
[Link](2000);
} catch (InterruptedException e) {
[Link]();
}
[Link]([Link]().getName()+" End Thread ");

}
-----------------------------------------------------------------------------------
---------
package Thread;

import [Link];
import [Link];

public class ThreadPoolMain


{
public static void main(String[] args)
{
ExecutorService exe=[Link](5); //create a fixed pool
for(int i=1;i<10;i++)
{
Runnable r1=new ThreadPoolDemo(" "+i);
[Link](r1); //execute all the threads
}
[Link](); //close all the threads
while(![Link]())
{}
[Link]("Finished All Thread");
}
}
-----------------------------------------------------------------------------------
---------------------
concurrent :- why this package is created.
all the threads run concurrently at the same [Link] will speed up the exceution
and performance is better.
Multiple threads are running means there will be [Link] we generally use
syncronized so that one thread will exceute and after the completion of that thread
the other thread will execute.

syncronized(ATM) is one of the solution of deadlock.

Concurrent package takes care of [Link] will allow one after the other thread
to excute.
It helps multi-tasking,efficent excution and faster excution .
we have ConcurrentHashMap,ConcurrentHashTable also.
-----------------------------------------------------------------------------------
-------------------
ConcurrentHashMap:-
It is similar to HashMap but it is threadsafe and concurrent and we have some more
[Link] have to import [Link]
-----------------------------------------------------------------------------------
-----
HashTable :-It is synchronized we don't have [Link] deadLock
HashMap :-It is not synchronized we have [Link] of deadLock.
ConcurrentLinkedQueue
-----------------------------------------------------------------------------------
----------------
Example-69
--------------------
package Thread;

import [Link];

public class ConcurrentHashMapDemo


{
public static void main(String[] args)
{
ConcurrentHashMap<String, Integer> chm=new ConcurrentHashMap<String,
Integer>();
[Link]("sandip", 100);
[Link]("sunil", 40);
[Link]("sandy", 60);
[Link]("sumeet", 50);
[Link]("shubham", 70);
[Link](chm);

[Link]([Link](100));
[Link]([Link]("Madhu", k-> 30+40));//adds the record
to the map
[Link]([Link]("Mohan", k-> 60+40));
[Link]([Link]());
[Link](chm);
}
}
----------------------------------------------------------------------
package Thread;

import [Link];
import [Link];
import [Link].*;

public class ConcurrentHashMapDemo


{
public static void main(String[] args)
{
ConcurrentHashMap<String, Integer> chm=new ConcurrentHashMap<String,
Integer>();
[Link]("sandip", 100);
[Link]("sunil", 40);
[Link]("sandy", 60);
[Link]("sumeet", 50);
[Link]("shubham", 70);
[Link](chm);

[Link]([Link](100));
[Link]([Link]("Madhu", k-> 30+40));//adds the record
to the map
[Link]([Link]("Mohan", k-> 60+40));
[Link]([Link]("shubham", (key , val) -> val +100));
//in computeIfPresent if the key is present then we can modify the
value.
[Link]([Link]("sandy", (key , val) -> val +50));
[Link]([Link]());
[Link](chm);
Set set=[Link]();
[Link](set);
Enumeration en=[Link]();
while([Link]())
{
[Link]([Link]());
}
}
}
----------------------------------------------------------------------
package Thread;
//jdk1.8 feature.
import [Link];
public class BiFunctionTest
{
public static void main(String[] args)
{
BiFunction<Integer,Integer,Integer> fun=(x1,x2) -> x1+x2;
Integer result = [Link](12,10);
[Link](result);

BiFunction<Integer,Integer,Double> fun1=(x1,x2) -> [Link](x1, x2);


Double result1 = [Link](2,10);
[Link](result1);

}
}
-----------------------------------------------------------------------------------
---------------------------
T- Type of the first Argument.
U-Type of the second Argument.
R-Return type of the result
------------------------------------------------------
package Thread;

import [Link];
import [Link];
import [Link].*;

public class ConcurrentHashMapDemo


{
public static void main(String[] args)
{
ConcurrentHashMap<String, Integer> chm=new ConcurrentHashMap<String,
Integer>();

ConcurrentHashMap<String, Integer> chm1=chm;

ConcurrentHashMap<String, Integer> chm2=new ConcurrentHashMap<String,


Integer>();
[Link]("sandip", 100);
[Link]("sunil", 40);
[Link]("sandy", 60);

[Link]("sumeet", 50);
[Link]("shubham", 70);
[Link](chm);
[Link](chm2);

[Link]("we are comparing 2 maps :"+[Link](chm1));


[Link]("we are comparing 2 maps :"+[Link](chm2));
}
}
--------------------------------------------------------------------------
ConcurrentLinkedQueue:-
--------------------------------------
The data will be FIFO basis.
We can add elements to the head and tail of the Queue.
-----------------------------
Example-70
---------------------
package Thread;

import [Link];

public class ConcurrentLinkedQueueDemo


{
public static void main(String[] args)
{
ConcurrentLinkedQueue<Integer> clq=new ConcurrentLinkedQueue<Integer>();
for(int i=1;i<=10;i++)
[Link](i);
[Link](11); //add element to the tail
[Link](12);
[Link](clq);
if([Link](4)) //checks if present or not
{
[Link]("the queue contains 4");
}
else
{
[Link]("the queue donot contains 4");

}
[Link](5); // removes particular element from the queue
[Link](clq);
[Link](clq); //removes all the elements from the queue.
[Link](clq);

}
}
-----------------------------------------------------------------------------------
------------
package Thread;

import [Link];

public class StudentQueueDemo


{
String rollno,name,college;

public StudentQueueDemo(String rollno, String name, String college)


{
super();
[Link] = rollno;
[Link] = name;
[Link] = college;
}

@Override
public String toString() {
return "StudentQueueDemo [rollno=" + rollno + ", name=" + name + ", college="
+ college + "]";
}
public static void main(String[] args)
{
StudentQueueDemo ob1=new StudentQueueDemo("MCA101","sandip","ABC");
StudentQueueDemo ob2=new StudentQueueDemo("MCA102","sunil","ABC");
StudentQueueDemo ob3=new StudentQueueDemo("MCA103","shubham","ABC");
StudentQueueDemo ob4=new StudentQueueDemo("MCA104","satish","ABC");
ConcurrentLinkedQueue<StudentQueueDemo> clq=new
ConcurrentLinkedQueue<StudentQueueDemo>();
[Link](ob1);
[Link](ob2);
[Link](ob3);
[Link](ob4);
for(StudentQueueDemo stq:clq)
[Link](stq);

}
}
-----------------------------------------------------------------------------------
---------------
package Thread;

import [Link];
import [Link];
import [Link];

public class QueueListDemo


{
public static void main(String[] args)
{
ConcurrentLinkedQueue<Integer> clq=new ConcurrentLinkedQueue<Integer>();
List k=new ArrayList();
for(int i=1;i<=25;i++)
[Link](i);
[Link](clq);
for(int i=1;i<=10;i++)
{
int j=i*5;
[Link](j);
}
[Link](k);//all the elements in the queue will are present in the list will
be display
[Link](clq);
}
}
-----------------------------------------------------------------------------------
-----
wap to enter a queue of students who appered for exam.
and list of students who qualified for the exam.
------------------------------------------------------------------------
package Thread;
import [Link];
import [Link];
import [Link];
public class QueueListDemo
{
public static void main(String[] args)
{
ConcurrentLinkedQueue<String> clq=new ConcurrentLinkedQueue<String>();
List<String> k=new ArrayList<String>();
[Link]("Student wrote Exam");
[Link]("sandip");
[Link]("sunil");
[Link]("shubham");
[Link]("Madhu");
[Link]("sunil");
[Link]("Madhu");
[Link](clq);
[Link]("Student qualified");
[Link](k);//all the elements in the queue will are present in the list will
be display
[Link](clq);
}
}
-----------------------------------------------------------------------------------
------
Example-71
-----------------
package Thread;

import [Link];
import [Link];
import [Link];
import [Link];

class Tasks implements Runnable


{
String taskName;

public Tasks(String taskName)


{
[Link] = taskName;
}

@Override
public void run()
{
try
{
for (int j=0;j<5;j++)
{
if(j==0)
{
Date dt=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("hh : mm : ss");
[Link]("The start time of :"+ taskName +"
"+[Link](dt));
}
else
{
Date dt=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("hh : mm : ss");
[Link]("The execution time of :"+ taskName +"
"+[Link](dt));
}
[Link](1000);
}
[Link](taskName +" is Completed");
}
catch(Exception ae)
{
[Link]();
} }}
public class ThreadPoolExample
{
public static void main(String[] args)
{
Tasks rb1=new Tasks("task 1");
Tasks rb2=new Tasks("task 2");
Tasks rb3=new Tasks("task 3");
Tasks rb4=new Tasks("task 4");
Tasks rb5=new Tasks("task 5");
ExecutorService pl=[Link](5);
[Link](rb1);
[Link](rb2);
[Link](rb3);
[Link](rb4);
[Link](rb5);
[Link]();

}
}
----------------------------------------
o/p:-
The start time of :task 2 04 : 32 : 59
The start time of :task 5 04 : 32 : 59
The start time of :task 4 04 : 32 : 59
The start time of :task 1 04 : 32 : 59
The start time of :task 3 04 : 32 : 59
The execution time of :task 5 04 : 33 : 00
The execution time of :task 2 04 : 33 : 00
The execution time of :task 4 04 : 33 : 00
The execution time of :task 1 04 : 33 : 00
The execution time of :task 3 04 : 33 : 00
The execution time of :task 5 04 : 33 : 01
The execution time of :task 2 04 : 33 : 01
The execution time of :task 4 04 : 33 : 01
The execution time of :task 1 04 : 33 : 01
The execution time of :task 3 04 : 33 : 01
The execution time of :task 5 04 : 33 : 02
The execution time of :task 2 04 : 33 : 02
The execution time of :task 1 04 : 33 : 02
The execution time of :task 4 04 : 33 : 02
The execution time of :task 3 04 : 33 : 02
The execution time of :task 5 04 : 33 : 03
The execution time of :task 2 04 : 33 : 03
The execution time of :task 1 04 : 33 : 03
The execution time of :task 4 04 : 33 : 03
The execution time of :task 3 04 : 33 : 03
task 1 is Completed
task 5 is Completed
task 2 is Completed
task 4 is Completed
task 3 is Completed
-------------------------------------------------------------------------
Syncronized Thread :- One Thread exceute and after its execution the second thread
will start execution.
-----------------------------------------------------------------------------------
-------
DeadLock:-

public void run()


{
Syncronized Thread1 //this will first start
sleep(1000);//block state
Syncronized Thread2 //Thread 2 will be waiting for thread1 to complete its
execution so that it will start excuting
}

This is the condition for DeadLock.


-----------------------------------------------------------------------------------
----------
Example-71
--------------------
package Thread;
public class SecThread implements Runnable
{
Object ob1;
Object ob2;
public SecThread(Object ob1, Object ob2)
{
super();
this.ob1 = ob1;
this.ob2 = ob2;
}
@Override
public void run() {
String name=[Link]().getName();
[Link](name +" Putting lock on ob1");
synchronized(ob1)
{
[Link](name +" Putting lock on ob1");
work();
[Link](name +" Putting lock on ob2");
synchronized(ob2)
{
[Link](name +" Putting lock on ob2");
work();
}

[Link](name+ "Lock Released on ob1");


}
[Link](name+ "Lock Released on ob2");
[Link]("Finish Excecution");
}
void work()
{
try {
[Link](30000);
} catch (InterruptedException e) {
[Link]();
}

}
}
-----------------------------------------------------------------------------------
--
package Thread;
public class ThreadDeadlock
{
public static void main(String[] args)throws Exception
{
Object ob1=new Object();
Object ob2=new Object();
Object ob3=new Object();

Thread t1=new Thread(new SecThread(ob1,ob2),"t1");


Thread t2=new Thread(new SecThread(ob2,ob3),"t2");
Thread t3=new Thread(new SecThread(ob3,ob1),"t3");
[Link]();
[Link](5000);
[Link]();
[Link](5000);
[Link]();
[Link](5000);
}
}
----------------------------------------------------------------
synchronized there are 3 types
--------------------------------------
1)synchronized method :-DeadLock will be for the object.
2)synchronized block:-DeadLock will be for the object.
3)static synchronized:-There will be no object created for the [Link] will
be for the class.
----------------------------------------------------
synchronized block
-------------------------------------------
package Thread;

class Table
{
void printTable(int n)
{
synchronized(this)
{
for(int i=1;i<=5;i++)
{
[Link](i*n);
try {
[Link](1000);
} catch (InterruptedException e) {
[Link]();
}
}
}
}
}
class Thread1 extends Thread
{
Table t;
Thread1(Table t)
{
this.t=t;
}
public void run()
{
[Link](5);
}
}

class Thread2 extends Thread


{
Table t;
Thread2(Table t)
{
this.t=t;
}
public void run()
{
[Link](50);
}
}

public class synchronizedBlockDemo


{
public static void main(String[] args)
{
Table obj=new Table();
Thread1 t1=new Thread1(obj);
Thread2 t2=new Thread2(obj);
[Link]();[Link]();
}
}
--------------------------------------------------------------------------------
static synchronized
-----------------------------------------
package Wednesday;
class Table1
{
synchronized static void printTable(int n)
{
for(int i=1;i<=10;i++)
[Link](i*n);
try {
[Link](1000);
} catch (InterruptedException e) {
[Link]();
}
}
}
class Thread1 extends Thread
{
public void run()
{
[Link](10);
}
}

class Thread2 extends Thread


{
public void run()
{
[Link](100);
}
}
class Thread3 extends Thread
{
public void run()
{
[Link](200);
}
}
public class StaticSysDemo
{
public static void main(String[] args) {
Thread1 t1=new Thread1();
Thread2 t2=new Thread2();
Thread3 t3=new Thread3();
[Link]();[Link]();[Link]();
}
}
-----------------------------------------------------------------------------------
-------------------
File
-------------
1)It is used to store and manage data.
2)Reading and writing of data into a file can be done using byte stream or
character stream.(flow from source to destination)
3)The process of reading and writing object into a file is known as serialization
and de-serialization.
4)we will be using [Link] package.
5)There are 2 types of stream by which we can read and write data into a file.
a)byte stream
b)character stream
Under this byte stream and charcater stream we have different class.
6)While working with file we have to handle exception because it throws checked
Exception.
Exceptions :-
EOFException,FileNotFoundException,InterruptedIOException,IOException.
----------------------------------------------------------------------------------
We have some file class methods
--------------------------------------------------
Example-72
-------------------
//we have to create a file on the project folder
package File;
import [Link].*;
import [Link].*;
public class FileExample1
{
public static void main(String[] args)
{
Scanner ob=new Scanner([Link]);
[Link]("Enter the file name");
String fname=[Link]();
File f=new File(fname);
[Link]("the file name is "+[Link]());
[Link]("the file path is "+[Link]());
[Link]("the file obsolute path is "+[Link]());
[Link]("the file is existing "+[Link]());
[Link]("the file is in read mode "+[Link]());
[Link]("the file is in write mode "+[Link]());
[Link]("the file is in execute mode "+[Link]());
[Link]("the file length is "+[Link]());
[Link]("this is a file "+[Link]());
[Link]("this is a directory "+[Link]());
}
}
-----------------------------------------------------------------------------------
------
Byte stream(10101001001)
---------------------
There are 2 abstract classes.
--------------------------------------------
1)InputStream-reading data from the file.
2)OutputStream-writing data into the file.

we have some classes


1)BufferInputStream/BufferOutputStream
2)FileInputStream/FileOutputStream
3)ObjectInputStream/ObjectOutputStream ----serialization and de-serialization.
4)DataInputStream/DataOutputStream ----to read and write primative data type into
the file.
------------------------------------------------------------------
Example-73
-----------------------
Reading data from the keyboard
----------------------------------------------
package File;
import [Link].*;
public class FileExample2
{
public static void main(String[] args) throws IOException
{
DataInputStream dis=new DataInputStream([Link]);
FileOutputStream fos=new FileOutputStream("[Link]");//file not found means it
will automatically create a file
[Link]("enter the data");
int data;
while((data=[Link]())!='\n') //data is internally converted into byte format and
while writing it will again convert into //character
{
[Link](data);
}
[Link]("file writing over");
[Link](); //pointer will be released.
[Link]();
}
}
--------------------------------------------------------------------------------
Reading data from one file and writing data into another file.
--------------------------------------------------------------------------------
package File;
import [Link].*;
public class FileExample3
{
public static void main(String[] args)throws Exception
{
FileInputStream fis=new FileInputStream("[Link]");//read from the
file(it should exists or have to create)
FileOutputStream fos=new FileOutputStream("[Link]");//write data into
the file.(automatic create)
int data;
while((data=[Link]())!=-1)//-1 indicates end of the file.
{
[Link](data);
}
[Link]();[Link]();
[Link]("file copied...................");
}
}
-----------------------------------------------------------------------------------
---------------------
package File;
import [Link].*;
public class FileExample4
{
public static void main(String[] args) throws NumberFormatException, IOException
{//reading will be in character format only.(Reader/Writer)
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));//like
scanner intro in jdk1.5
[Link]("enter empno");
int empno=[Link]([Link]());
[Link]("enter empname");
String name=[Link]();
[Link]("enter address");
String add=[Link]();
[Link]("enter salary");
float sal=[Link]([Link]());
[Link]("the empno is :"+empno);
[Link]("the name is :"+name);
[Link]("the address is :"+add);
[Link]("the salary is :"+sal);

}
}
-------------------------------------------------------------------
The process of reading and writing object into a file is known as serialization and
de-serialization.
-----------------------------------------------------------------------
ObjectInputStream/ObjectOutputStream ----serialization and de-serialization.
-------------------------------------------------------------------------------
Serializable -it is a marker [Link] will be no abstract method in it.
---------------------------
example-
package File;

import [Link];

public class Student implements Serializable


{
int rollno;
String name,address;
}
---------------------------------------------------------------------------------
package File;
import [Link].*;
public class SerializableDemo
{
public static void main(String[] args) throws IOException
{
Student obj=new Student();
[Link]=101;
[Link]="sandip";
[Link]="bangalore";
FileOutputStream fos=new FileOutputStream("[Link]");
ObjectOutputStream os=new ObjectOutputStream(fos);
[Link](obj);
[Link]();[Link]();
[Link]("Object written into the file.......");
}
}
---------------------------------------------------------------------------------
package File;
import [Link].*;
public class DeserializableDemo
{
public static void main(String[] args) throws Exception
{
Student s1=null;
FileInputStream fos=new FileInputStream("[Link]");
ObjectInputStream os=new ObjectInputStream(fos);
s1=(Student) [Link]();
[Link]();[Link]();
[Link]("the rollno is :"+[Link]);
[Link]("the name is :"+[Link]);
[Link]("the address is :"+[Link]);
}}
-----------------------------------------------------------------------------------
----
transient :- it is a keyword .this will not be Serialized.
-----------------------------------------------------------------------------------
-------------
o/p:-int
the rollno is :0
the name is :sandip
the address is :bangalore
------------------------------------------------------
o/p:-String
the rollno is :101
the name is :null
the address is :bangalore
------------------------------------------------------
wap to store data of few employees into a files and retrive it using serialization
and de-serialization.
employee class (empno,name,salary,designation)
----------------------------------------------------------------------------------
character stream
------------------------------
1)Reader 2)writer
--------------------------------------------
example:-
-------------------
package File;
import [Link].*;
public class FileExample5
{
public static void main(String[] args) throws IOException
{
FileReader fr=new FileReader("[Link]");
BufferedReader br=new BufferedReader(fr);
String x;
while((x=[Link]())!=null) //null indicates EOF
{
[Link](x);
}
}
}
---------------------------------------------------
CharArrayWriter/CharArrayReader
------------------------------------------------------------
CharArrayWriter :- it is used to write common data to multiple files.

package File;
import [Link].*;
public class FileExample6
{
public static void main(String[] args)throws Exception
{
CharArrayWriter caw=new CharArrayWriter();
[Link]("This is an example of File");
FileWriter f1=new FileWriter("[Link]");
FileWriter f2=new FileWriter("[Link]");
FileWriter f3=new FileWriter("[Link]");
FileWriter f4=new FileWriter("[Link]");
FileWriter f5=new FileWriter("[Link]");
[Link](f1);
[Link](f2);
[Link](f3);
[Link](f4);
[Link](f5);
[Link]();[Link]();[Link]();[Link]();[Link]();
[Link]("success............");
}
}
-----------------------------------------------------------------------------------
------------------------
CharArrayReader:- It reads array of character.
--------------------------------------------------------------------
package File;
import [Link].*;
public class FileExample7
{
public static void main(String[] args) throws Exception
{
char x[]= {'t','h','i','s','a','f','i','l','e','p','r','g'};
CharArrayReader red=new CharArrayReader(x);
int y=0;
while((y=[Link]())!=-1)
{
[Link](y);
char p=(char) y;
[Link](p);
[Link]("*********************************");
}
}
}
-----------------------------------------------------------------------------------
-----------------------------------
JDBC :- Java database connectivity
Oracle 10xe/MySql--structured Data(rows and columns)
MongoDB --unstructured Data(facebook,paytm)
-------------------------
JDBC we have 2 types of driver:-
1)Thick Driver
2)Thin Driver
why we require driver.
1)java(byte code)
-------------Driver(interpreter)-------------------Oracle/Mysql/sqlserver(ASCII
code)

1)Thick Driver
type1 driver-[java prg---odbc driver----Database]
ODBC -open database [Link] comes with the o/s.
-----------------------------------------------------------------------------------
------
type2 driver-[java prg---driver----database]This is vendor specific.
-----------------------------------------------------------------------------------
--------
type3 driver-[Java prg ---middleware server---Databse] This is vendor specific
-----------------------------------------------------------------------------------
----
2)Thin Driver
type4 driver-[java prg---driver----database].The driver is purely java and
interacts directly with the database and is faster.

-----------------------------------------------------------------------------------
-----------
We have to import [Link] package and handle the SQLException.

There are 2 classes and 8 interfaces


classes :- DriverManager,Types
Interfaces :-
Driver,Connection,Statement,PreparedStatement,CallableStatement,ResultSet,ResultSet
MetaData,DatabaseMetaData
-------------------------------------------------------------------------
When we do static data crud (create,read,update,delete) operartion we use
Statement.
When we do dynamic data crud (create,read,update,delete) operartion we use
PreparedStatement.
When we work with function,procedure we use CallableStatement.
-----------------------------------------------------------------------------------
-------------------
Example :-
import [Link];
class student
{
main()throws Exception
{
1)to load the driver
2)to get connection from DriverManager
3)Statement()/preparedStatement(pass the sql query)
4)execute(pass the sql query)/execute();
}}
---------------------------------------------------------------------------------
Example-1
----------------------
Insert
------------------
package JDBC;
import [Link].*;
public class Student
{
public static void main(String[] args)throws Exception
{
//to load the driver
[Link]("[Link]");
//to get connection from DriverManager
Connection
con=[Link]("jdbc:oracle:thin:@localhost:1521:xe","system","123
4");
//jdbc--protocal ,
//oracle is ---database,
//thin--type 4 driver,
//localhost--both server and client reside in the same machine
//localhost (IP address of the server :[Link]),default port no :1521,
//xe is the database name,
//system--username
//1234 is the password.
//Statement()/preparedStatement(pass the sql query)
Statement st=[Link]();
//execute(pass the sql query)/execute();
[Link]("insert into marlabsstud
values(101,'Shubam','Bangalore')");//static query
[Link]("Row Inserted");
}
}
-----------------------------------------------------------------------------------
------------------
create table and insert data
----------------------------------------
import [Link].*;
public class Student
{
public static void main(String[] args)throws Exception
{
[Link]("[Link]");
Connection
con=[Link]("jdbc:mysql://localhost:3306/cognizant","root","123
4");
Statement st=[Link]();
//[Link]("create table employee23(empid int,name
varchar(30),address varchar(30))");
[Link]("insert into employee23 value(101,'sandip','Pune')");
[Link]("Successful");
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------
update data
-------------------
package JDBC;
import [Link].*;
public class Student
{
public static void main(String[] args)throws Exception
{
[Link]("[Link]");
Connection
con=[Link]("jdbc:mysql://localhost:3306/cognizant","root","123
4");
Statement st=[Link]();
[Link]("update employee2023 set address='Kolkotta' where
empno=101");
[Link]("Row updated");
}
}
---------------------------------------------------------------------------------
Delete
-------------------
package JDBC;
import [Link].*;
public class Student
{
public static void main(String[] args)throws Exception
{
[Link]("[Link]");
Connection
con=[Link]("jdbc:mysql://localhost:3306/cognizant","root","123
4");
Statement st=[Link]();
[Link]("delete marlabsstud where empno=101");
[Link]("Row deleted");
}
}
-----------------------------------------------------------------------------------
---------------------
ResultSet rs=[Link]("select * from marlabsstud");
All the data from the marlabsstud table will be stored in the ResultSet variable
rs.
we will use a while loop to eterate the [Link] pointer will move from the first
row till the last row.
-----------------
select
------------------------
package JDBC;
import [Link].*;
public class Student
{
public static void main(String[] args)throws Exception
{
[Link]("[Link]");
Connection
con=[Link]("jdbc:mysql://localhost:3306/cognizant","root","123
4");
Statement st=[Link]();
ResultSet rs=[Link]("select * from marlabsstud");
while([Link]())
{
[Link]([Link](1)+" "+[Link](2)+"
"+[Link](3));
}

}
}
-----------------------------------------------------------------------------------
----
types of execute methods
----------------------------------------
1)executeQuery() ----select
2)exceuteUpdate() -----update(returns 0 or 1)
3)excute() ----insert,update,delete,create (returns true,false);
-----------------------------------------------------------------------------------
----------

1)Oracle 10xe
2)MySql
3)MongoDB
-------------------------------------------------
Path where you can find the [Link] (driver)

C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib
-----------------------------------------------------------------------------
package JDBC;
import [Link].*;
import [Link].*;
public class Student
{
public static void main(String[] args)throws Exception
{
[Link]("[Link]");
Connection
con=[Link]("jdbc:mysql://localhost:3306/cognizant","root","123
4");
Scanner ob=new Scanner([Link]);
[Link]("enter empno,name,address");
int empno=[Link]();
String name=[Link]();
String address=[Link]();
PreparedStatement st=[Link]("insert into marlabsstud
values(?,?,?)");
[Link](1,empno);//1 represent the first ?
[Link](2,name);//2 represent the second ?
[Link](3,address);//3 represenr the third ?
[Link]();
[Link]("row inserted");
}
}
-----------------------------------------------------------------------------------
----------
Basic of Oracle
---------------------------
creating table
-----------------------
create table marlabsstud(empno number, name varchar2(50),address varchar2(100))

select data from the table


------------------------------------------
select * from marlabsstud;

insert data into table


-----------------------------
insert into marlabsstud values(103,'shubham','Bangalore');

update data in the table


---------------------------------
update marlabsstud set address='hyderabad' where empno=103;

delete data from the table


-----------------------------
delete marlabsstud where empno=103
select empno,name from marlabsstud;

the table will be deleted


-----------------------------------
drop table marlabsstud;

table structure will be present but rows will be deleted


-------------------------------------------------------------
truncate table marlabsstud;

add a column phoneno to marlabsstud


-------------------------------------------
alter table marlabsstud add phoneno number

how to update phoneno


--------------------------
update marlabsstud set phoneno='6543435' where empno=102;

how to drop the column


---------------------------
alter table marlabsstud drop column phoneno;
-----------------------------------------------------------------------------------
-----------------------------------------
update
---------------
package JDBC;
import [Link].*;
import [Link].*;
public class Student
{
public static void main(String[] args)throws Exception
{
[Link]("[Link]");
Connection
con=[Link]("jdbc:mysql://localhost:3306/cognizant","root","123
4");
Scanner ob=new Scanner([Link]);
[Link]("enter name,address and empno which you want to
update");
String name=[Link]();
String address=[Link]();
int empno=[Link]();
PreparedStatement st=[Link]("update marlabsstud set
name=?,address=? where empno=?");
[Link](1,name);
[Link](2,address);
[Link](3,empno);
[Link]();
[Link]("row updated");
}
}
-----------------------------------------------------------------------------------
-----------
delete
--------------
package JDBC;
import [Link].*;
import [Link].*;
public class Student
{
public static void main(String[] args)throws Exception
{
[Link]("[Link]");
Connection
con=[Link]("jdbc:mysql://localhost:3306/cognizant","root","123
4");
Scanner ob=new Scanner([Link]);
[Link]("enter empno which you want to delete");
int empno=[Link]();
PreparedStatement st=[Link]("delete marlabsstud where
empno=?");
[Link](1,empno);
[Link]();
[Link]("row deleted");
}
}

-----------------------------------------------------------------------------------
------------------
package JDBC;
import [Link].*;
import [Link].*;
public class Student
{
public static void main(String[] args)throws Exception
{
Scanner ob=new Scanner([Link]);
[Link]("enter empno,name,address,DOJ");
int empno=[Link]();
String name=[Link]();
String address=[Link]();
String DOJ=[Link]();
[Link]("[Link]");
Connection
con=[Link]("jdbc:mysql://localhost:3306/cognizant","root","123
4");
/* PreparedStatement st=[Link]("create table marlabemp(empno
number,name varchar2(30),address varchar2(30),DOJ date)");
[Link]();
[Link]("table created");*/
PreparedStatement st=[Link]("insert into marlabemp
values(?,?,?,?)");
[Link](1, empno);
[Link](2,name);
[Link](3,address);
[Link](4,DOJ);
[Link]();
[Link]("row inserted");

}
}

-----------------------------------------------------------------------------------
----------------------------

Common questions

Powered by AI

Java achieves thread synchronization by using monitors which ensure that only one thread can access a critical section of code at a time. This is done using synchronized methods and blocks. A synchronized method ensures that the method can only be executed by one thread at a time for an object, while a synchronized block provides more granular control by allowing synchronization of specific blocks of code rather than the whole method. Furthermore, static synchronization is used to lock the class rather than the instance. Additionally, Java provides wait, notify, and notifyAll mechanisms for inter-thread communication to handle wait-and-notify scenarios effectively, preventing race conditions and deadlocks .

Java threads can be managed using priorities, which allows the programmer to suggest the importance of threads using the setPriority() method. Priority values range from MIN_PRIORITY (1) to MAX_PRIORITY (10), with NORM_PRIORITY (5) as the default. Although it doesn't guarantee execution order or time, setting thread priorities can influence the thread scheduler to favor threads with higher priorities during contention for shared resources, especially in a preemptive multitasking context. This can be significant in time-sensitive applications where certain tasks must be prioritized over others. Effective use of priorities can enhance performance but requires careful management to avoid priority inversion and ensure fairness across threads .

Java uses automated garbage collection to manage memory, which means that the programmer does not need to write code for memory deallocation. Java's memory management relies on a garbage collector that works to reclaim memory by identifying and collecting objects that are no longer in use by the program. This process helps to prevent memory leaks and optimizes the program's memory usage. Java does not use destructors as seen in languages like C++; instead, it has constructors and relies heavily on garbage collection to manage memory cleanup .

Java supports single, multi-level, and hierarchical inheritance, which allows classes to inherit fields and methods from other classes, promote code reuse, and help create a hierarchy of classes. However, Java does not support multiple inheritance, which is the capability of a class to inherit features from multiple classes. This omission is due to the 'diamond problem,' where ambiguity arises if the same method is inherited from more than one superclass. Java uses interfaces to support the concept of multiple inheritance indirectly .

Java's design choice to not support pointer arithmetic significantly improves the safety and security of the language, making it simpler and less error-prone compared to C/C++. Without pointers, Java eliminates risks like buffer overflow, memory leak, and unauthorized memory access, which are common vulnerabilities in pointer arithmetic. Instead, Java uses references to interact with objects, which plays a role in safeguarding the memory through automatic garbage collection. This decision makes Java safer for novice programmers, easier to maintain, and supports robust security features which are critical for applications like network and web application development .

Access specifiers in Java play a crucial role in the encapsulation principle of object-oriented programming by controlling the visibility and accessibility of classes, methods, and variables. There are four main types: private, default, protected, and public. Private restricts access to within the defining class only, ensuring data hiding. Default, without an explicit specifier, allows package-level access, thereby grouping cohesive classes within a package. Protected grants access within the same package and allows subclasses to access these elements for inheritance purposes. Public enables access from anywhere, simplifying API designs. By effectively using these specifiers, Java developers can protect the internal state of an object, interfering only with controlled, public interfaces .

Java achieves platform independence through the use of the Java Virtual Machine (JVM), which executes bytecode compiled from Java source code. When Java code is compiled, it is not converted into platform-specific machine code; instead, it's turned into an intermediate form known as bytecode. This bytecode is platform-independent, meaning it can be executed on any system that has the appropriate JVM. The JVM acts as an interpreter between the bytecode and the machine code of the host system, providing Java applications the ability to run on any platform without modification—essentially 'write once, run anywhere' .

Java handles primitive data types and object references differently, each serving distinct purposes. Primitive data types such as int, char, and double hold their actual values directly in memory, leading to faster access and less memory usage. They are stored in the stack memory, ensuring quick access. On the other hand, object references, like instances of classes (including strings) and arrays, point to a location in the heap memory where the actual object data is stored. This distinction is significant as primitives are passed by value, while objects are referenced, meaning changes to them can affect all references. This has implications for memory management, data manipulation performance, and how Java ensures security and simplicity in handling data .

In Java, interfaces serve primarily to establish a contract that a class must follow, defining methods that a class needs to implement without dictating how they should be implemented. Interfaces allow for abstraction, enabling classes to implement multiple interfaces, thus simulating multiple inheritance, which Java does not directly support due to the diamond problem. By allowing a class to implement multiple interfaces, Java supports the use of polymorphism, where objects of different classes can be handled through a common interface. This structure provides flexibility in code design and promotes modulo-programming techniques .

The key differences between a constructor and a method in Java include: a constructor is used to initialize objects and has the same name as the class, whereas a method performs specific functions and can have any name. Moreover, a constructor does not return any value and lacks a return type, whereas methods have return types, including 'void' if they do not return a value. Constructors are called when an object of a class is created, while methods can be called multiple times during the object's lifecycle .

You might also like