Core Java by Ashok Pate
Core Java by Ashok Pate
--------------------------------------------------------------------------------------------------------------------------
History of Java
• James Gosling, Mike Sheridan and Patrick Naughton initiated the
Java language project in June 1991.
• Java was originally developed by James Gosling at Sun
Microsystems and released in 1995.
• The language was initially called Oak after an oak tree that
stood outside Gosling's office.
• Later the project went by the name Green and was finally renamed
Java, from Java coffee, a type of coffee from Indonesia.
• Gosling and his team did a brainstorm session and after the
session, they came up with several names such as JAVA, DNA, SILK,
RUBY, etc.
• Sun Microsystems released the first public implementation as Java
1.0 in 1996.
Version History:-
Java Platforms
1. Java SE
Java Platform Standard Edition.
It is also called as Core Java.
For general purpose use on Desktop PC’s, servers and
similar devices.
2. Java EE
Java Platform Enterprise Edition.
page. 1
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
It is also called as advanced Java / enterprise java /
web java.
Java SE plus various API’s which are useful client-server
applications.
3. Java ME
Java Platform Micro Edition.
Specifies several different sets of libraries for devices
with limited storage, display, and power capacities.
It is often used to develop applications for mobile
devices, PDAs, TV set-top boxes and printers.
4. Java Card
A technology that allows small Java-based applications
(applets) to be run securely on smart cards and similar
small-memory devices.
Components Of Java Platform:-
• SDK = Development Tools + Documentation + Libraries + Runtime
Environment.
• JDK = Java Development Tools + Java Docs + rt.jar + JVM.
JDK : Java Development Kit.
It is a software, that need to be install on developers
machine.
We can download it from oracle official website.
• JDK = Java Development Tools + Java Docs + JRE[ rt.jar + JVM ].
• JRE : Java Runtime Environment.
rt.jar and JVM are integrated part of JRE.
JRE is a software which comes with JDK. We can also download it
separately.
To deploy application, we should install it on client’s
machine.
• rt.jar file contains core Java API in compiled form.
• JVM : An engine, which manages execution of Java application.
Java terminologies:-
C++ terminologies Java terminologies
Class Class
Data member Field
Member function Method
Object Instance
Pointer Reference
Access specifier Access Modifier
Base class Super class
Derived class Sub class
Derived from Extended from
Runtime Polymorphism Dynamic method dispatch
Note:-
1.Jis class ka object create kr sakte hai use hum concrete class
bolte hai.
2.jis class ka object create nhi kr sakte hai use hum abstract
class bolte hai.
3.jis method ko body hoti hai use hum concreate method bolte hai
4.jis method ko body nhi hoti hai use hum abstract method bolte
hai.
page. 3
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
5.jis class ka child class nhi bana sakte use final class bolte hai
6.jis method ko hum override nhi kr sakte aise method ko final
method bolte hai.
1.A class from which, we can create object is called concrete
class.
2.A class from which, we can not create object is called abstract
class.
3.A method of class, which is having body is called concreate
method
4.A method of class, which do not have body is called abstract
method.
5.A class, that we can not extend is called final class
6.A method that we can not redefine/override it inside sub class
is called final method.
class Program_1 {
//Entry point method
public static void main(String args[])
{
//Printf("Hello world"); in C
//Std::cout<<"Hello world"<<std::endl; in C++
System.out.println("Hello world"); //in Java
-------------------------------------------------------------------
page. 4
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Flow of Execution program:-
Component of JVM
1.ClassLoader Subsystem
a. Bootstrap class loader
b. Extension class loader
c. Application class loader
d. User defined class loader
3.Execution Engine
a. Interpreter
b. Just in time compiler
c. garbage collector
The Bytecode is object oriented assembly lang code design for JVM
If we create blank java file then it wont give me compile time
error. But runtime error gave me Error: could not find or load main
class program. calling main method is job of JVM not complier.
page. 5
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
It give me Error: Main method not found in class Program_2, please
define the main method as:
class Program_2 {
private static void main(String[] args) {
System.out.println("Hello world");
}
}//Error
class Program_2 {
protected static void main(String[] args) {
System.out.println("Hello world");
}
}//Error
only one type in main method i.e String but args name you can
give anything.
class Program_2 {
public static void MAIN(int args, String[] args) {
System.out.println("Hello world");
}
} //Error
page. 6
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
class Program_2 {
public static void main(String[] Ashok) {
System.out.println("Hello world");
}
} //No error
Program:-
class A{
public static void main(String[] args) {
System.out.println("A.main");
}
}
class B{
public static void main(String[] args) {
System.out.println("B.main");
}
}
class Program_3 {
public static void main(String[] args) {
System.out.println("Program.main");
}
}
-->yaha pr three class likhe hai aur three main hai .class file pr
particular class execute kr skte hai isame.
}
public static void main(String[] args) {
System.out.println("Program.main(args)");
Program_4.main();
}
}
java mai two type ke thread hai first is for to invoke/call main
method
Aur dusra thread to deallocate memory of unused objects.
page. 7
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
• Syntax:
1. public static void main( String[] args )
2. public static void main( String... args )
• Java compiler do not check/invoke main method. JVM invoke main
method.
• When we start execution of Java application then JVM starts
execution of two threads:
1. Main thread : responsible for invoking main method.
2. Garbage Collector : responsible for deallocating memory of
unused object.
• We can overload main method in Java.
• We can define main method per class. But only one main can be
considered as entry point method.
Comments
• Comments should be used to give overviews of code and provide
additional information that is not readily available in the code
itself. Comments should contain only information that is relevant
to reading and understanding the program.
• Types of Comments:
• Implementation Comment:- Implementation comments are those found
in C++, which are delimited by /*...*/, and //.
1. Single-Line Comment
2. Block Comment( also called as multiline comment )
• Documentation Comment :- Documentation comments (known as "doc
comments") are Java-only, and are delimited by /**...*/.
• Doc comments can be extracted to HTML files using the javadoc
tool.
-------------------------------------------------------------------
page. 8
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Data Types:-
• Data type of any variable decide following things:
1. Memory: How much memory is required to store the data.
2. Nature: Which kind of data is allowed to store inside memory.
3. Operation: Which operations are allowed to perform on the data
stored in memory.
4. Range: Set of values that we can store inside memory.
• The Java programming language is a statically typed language,
which means that every variable and every expression has a type
that is known at compile time.
o Types of data type:
1. Primitive type(also called as value type )
boolean type
Numeric type
1. Integral types(byte, char, short, int, long)
2. Floating point types(float, double
2. Non primitive type(also called as reference type)
Interface, Class, Type variable, Array
-------------------------------------------------------------------
Wrapper Class
• In Java, primitive types are not classes. But for every primitive
type, Java has defined a class. It is called wrapper class.
• All wrapper classes are final.
• All wrapper classes are declared in java.lang package.
• Uses of Wrapper class
1. To parse string(i.e. to convert state of string into numeric
type).
2. To store value of primitive type into instance of generic class,
type argument must be wrapper class.
Stack stk = new Stack( ); //Not OK
Stack stk = new Stack( ); //OK
string convert into interger then used wrapper class
integer.parseInt();
int number1=Integer.parseInt("123");
float number2=Float.parseFloat("123.45f");
Double number3=Double.parseDouble("123.45f");
page. 9
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
class Program{
public static void main1(String[] args) {
//Java is statically type checked language
int num1 = 10;
System.out.println( num1 );
}
public static void main2(String[] args) {
int num1 = 10;
//printf( "Num1 %d\n",num1); //in C
//std::cout << "Num1 : " << num1 <<std::endl; in C++
System.out.println("Num1 : "+num1);
}
public static void main(String[] args) {
//int num1;
//System.out.println( num1 ); //error: variable num1 might
not have been initialized
page. 10
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
//int num1 = 10; //Initialization
//System.out.println( num1 ); //OK
int num1;
num1 = 10; //Assignment
System.out.println( num1 ); //OK
}
}
-------------------------------------------------------------------
class Program{
page. 11
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Narrowing
• Process of converting value of variable of wider type into
narrower type is called narrowing.
• In case of narrowing, explicit type casting is mandatory.
class Program{
public static void main1(String[] args) {
double num1 = 10.5; //Initialization
double num2 = num1; //Initialization
System.out.println("Num2 : "+num2);
}
public static void main(String[] args) {
double num1 = 10.5; //Initialization
//int num2 = num1; //error: incompatible types: possible lossy
conversion from double to int
int num2 = (int)num1; //Narrowing //OK : 10
System.out.println("Num2 : "+num2);
}
}
-------------------------------------------------------------------
Note:-
//Static methods are designed to call on classname
//Example : ClassName.staticMethod( );
//Non static methods are designed to call on instance/object
//Example : objectRef.nonStaticMethod( );
-------------------------------------------------------------------
page. 12
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Unboxing :-
• Process of converting value of variable of non primitive type
into primitive type is called unboxing.
• If string does not contain parseable numeric value then parseXXX(
) method throws NumberFormatException.
class Program{
public static void main1(String[] args) {
/*
Employee emp; //Static memory allocation
Employee *ptr = new Employee(); //Dynamic memory allocation
*/
//String is a class declared in java.lang package.
page. 13
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
//NumberFormatException - if the string does not contain a
parsable integer.
}
public static void main(String[] args) {
String str = "A";
char ch = str.charAt(0);
System.out.println("Char : "+ch);
}
}
-------------------------------------------------------------------
Boxing
• Process of converting value of variable of primitive type into
not primitive type is called boxing
class Program{
//string is non-primitive & int is primitive
public static void main(String[] args) {
int number = 10; //primitive to non-primitive is know as boxing
String str = Integer.toString(number); //Boxing
System.out.println("Number : "+str);
}
page. 14
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
public static void main2(String[] args) {
float number = 10.5f;
String str = Float.toString(number); //Boxing
System.out.println("Number : "+str);
}
public static void main3(String[] args) {
double number = 20.5d;
String str = Double.toString(number); //Boxing
System.out.println("Number : "+str);
}
public static void main1(String[] args) {
String str;
page. 15
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------
class Program{
public static void sum( int a, int b ){ //a, b => Method Parameters
/ Parameters
int result = num1 + num2;
System.out.println("Result : "+result);
}
public static void main(String[] args) { //args => Method
Parameter / Parameter
Program.sum( 10, 20 ); //10, 20 => Method Arguments /
Assignments
class Program{
public static void main1(String[] args) {
String message = args[ 0 ];
System.out.println(message);
page. 16
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
}
public static void main2(String[] args) {
//int num1 = args[ 0 ]; //NOT Ok //error: incompatible types:
String cannot be converted to int
int num1 = Integer.parseInt(args[0]);
System.out.println("Result : "+result);
}
}
//args ka type non primitive hai.so parsing karna padenga.
/*
argc: contains argument count passed from terminal
argv: array of string,contains address of arguments passed from cmd line
*/
//=> javac program.java //program classs
//=>java program //Arrayindexoutofboundexception
//if you do not passed the argument then this error occurs
------------------------------------------------------------------
Println & Print & Printf method:-
page. 17
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
class Program{
public static void main1(String[] args) {
System.out.print("Hello"); //Helloworld!! ->all print in one
line
System.out.print("World");
System.out.print("!!");
System.out.print("\n");
}
public static void main2(String[] args) {
System.out.println("Hello"); //Hello
System.out.println("World"); //World
System.out.println("!!"); //!!
System.out.println("\n"); //print in different line
}
public static void main(String[] args) {
String name1 = "Amit Pol";
int empid1 = 1122;
float salary1 = 125345.50f;
//System.out.println(name1+" "+empid1+" "+salary1);
System.out.printf("%-20s%-5d%-10.2f\n", name1, empid1, salary1);
page. 18
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------
Console class:-
import java.io.Console;
class Program{
public static void main(String[] args) {
//java.io.Console console = System.console();
Console console = System.console();
System.out.print("Enter name : ");
String name = console.readLine();
System.out.print("Enter empid : ");
int empid = Integer.parseInt(console.readLine());
System.out.print("Enter salary : ");
float salary = Float.parseFloat(console.readLine());
System.out.println("Name : "+name);
System.out.println("Empid : "+empid);
System.out.println("Salary : "+salary);
}
}
//console is class declare in console.io is pacakage
//this code does not work in Eclipse.
page. 19
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------
Scanner class:-
import java.util.Scanner;
class Program{
//System.in => Keyboard
//System.out => Monitor
//System.err => Error Stream => Monitor
public static void main(String[] args) {
//java.util.Scanner sc = new java.util.Scanner( System.in );
System.out.println("Name : "+name);
System.out.println("Empid : "+empid);
System.out.println("Salary : "+salary);
}
}
page. 20
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
• Stream is an abstraction(object) which either produce (write) /
consume (read) information from source to destination.
• Standard stream objects of Java which is associated with console:
1. System.in
It represents keyboard.
2. System.out
It represents Monitor.
3. System.err
Error stream which represents Monitor.
-----------------------------------------------------------------------
jOptionPane :-
//jOptionPane is class include in jvac.swing pacakge
//mostly used for GUI
import javax.swing.JOptionPane;
class Program{
public static void main(String[] args) {
String name = JOptionPane.showInputDialog("Enter name.");
int empid = Integer.parseInt(JOptionPane.showInputDialog("Enter
empid."));
float salary = Float.parseFloat(JOptionPane.showInputDialog("Enter
salary."));
System.out.println("Name : "+name);
System.out.println("Empid : "+empid);
System.out.println("Salary : "+salary);
}
}
-----------------------------------------------------------------------
page. 21
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
BufferedReader:-
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Program{
public static void main(String[] args)throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("Name : "+name);
System.out.println("Empid : "+empid);
System.out.println("Salary : "+salary);
}
}
/*error: unreported exception IOException; must be caught or declared to
be thrown
int empid = Integer.parseInt(reader.readLine());
-----------------------------------------------------------------------
page. 22
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Class:-
• Consider following examples:
1. day, month, year - related to – Date
2. hour, minute, second - related to – Time
3. red, green, blue - related to Color
4. real, imag - related to – Complex
5. xPosition, yPosition - related to Point
6. number, type, balance - related to Account
7. name, id, salary - related to Employee
• If we want to group related data elements together then we should
use/define class in Java.
• class is a non primitive/reference type in Java.
• If we want create object/instance of a class then it is mandatory
to use new operator.
• If we create instance using new operator then it gets space on
heap section.
• Only fields of the get space once per instance according to order
of their declaration inside class.
page. 23
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
}
//name, rollNumber, marks are realated to Student
class Student{
String name;
int rollNumber;
float marks;
}
//name, empid, salary are realated to Employee
class Employee{
String name;
int empid;
float salary;
}
-----------------------------------------------------------------------
import java.util.Scanner;
class Program{
public static void main(String[] args) {
Scanner sc = new Scanner( System.in );
System.out.print("Name : ");
String name = sc.nextLine( );
System.out.print("Empid : ");
int empid = sc.nextInt();
System.out.print("Salary : ");
float salary = sc.nextFloat( );
page. 24
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Class is a collection of fields and methods.
Class can contain
1. Nested Type 2. Field 3. Constructor 4. Method
• Instance
In Java, Object is also called as instance.
Process of creating instance/object from a class is called as
instantiation.
• Every instance on heap section is anonymous.
import java.util.Scanner;
class Program{
public static void main(String[] args) {
Scanner sc = new Scanner( System.in );
class Employee{
String name; //Field => Default value null
int empid; //Field => Default value 0
float salary; //Field => Default value 0.0f
}
page. 25
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
page. 26
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------
import java.util.Scanner;
class Program{
public static void main(String[] args) {
Scanner sc = new Scanner( System.in );
class Employee{
String name; //Field => Default value null
int empid; //Field => Default value 0
float salary; //Field => Default value 0.0f
}
//Employee emp = new Employee();
Employee emp;
emp = new Employee();
emp.name = "Sandeep";
emp.empid = 33;
emp.salary = 12345.50f;
System.out.println("Name : "+emp.name);
System.out.println("Empid : "+emp.empid);
System.out.println("Salary : "+emp.salary);
}
page. 27
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
}
-----------------------------------------------------------------
import java.util.Scanner;
class Program{
public static void main(String[] args) {
Scanner sc = new Scanner( System.in );
class Employee{
String name; //Field => Default value null
int empid; //Field => Default value 0
float salary; //Field => Default value 0.0f
}
//Employee emp = new Employee();
Employee emp;
emp = new Employee();
emp.name = "Sandeep";
emp.empid = 33;
emp.salary = 12345.50f;
System.out.println("Name : "+emp.name);
System.out.println("Empid : "+emp.empid);
System.out.println("Salary : "+emp.salary);
}
}
-------------------------------------------------------------------------
This is not suitable method:-
import java.util.Scanner;
class Program{
public static void main(String[] args) {
//Scanner sc = new Scanner( System.in );
class Employee{
//Field / Attribute / Property
String name; //Field => Default value null
int empid; //Field => Default value 0
float salary; //Field => Default value 0.0f
}
page. 28
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
//If we want to perform operation on instance then we should
define method inside class.
//Function implemented inside class is called method.
/* System.out.print("Name : ");
emp.name = sc.nextLine();
System.out.print("Empid : ");
emp.empid = sc.nextInt();
System.out.print("Salary : ");
emp.salary = sc.nextFloat(); */
/* System.out.println("Name : "+emp.name);
System.out.println("Empid : "+emp.empid);
System.out.println("Salary : "+emp.salary); */
}
}
-------------------------------------------------------------------
Suitable method for above program:-
import java.util.Scanner;
class Program{
public static void main(String[] args) {
//Scanner sc = new Scanner( System.in );
class Employee{
//Field / Attribute / Property
String name; //Field => Default value null
int empid; //Field => Default value 0
float salary; //Field => Default value 0.0f
page. 29
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
void printRecord( ){
System.out.println("Name : "+name);
System.out.println("Empid : "+empid);
System.out.println("Salary : "+salary);
}
}
void acceptRecord( ){
Scanner sc = new Scanner( System.in );
page. 30
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
System.out.print("Name : ");
name = sc.nextLine();
System.out.print("Empid : ");
empid = sc.nextInt();
System.out.print("Salary : ");
salary = sc.nextFloat();
}
void printRecord( ){
System.out.println("Name : "+name);
System.out.println("Empid : "+empid);
System.out.println("Salary : "+salary);
}
}//End of class Employee
Employee emp = new Employee();
emp.acceptRecord( );
emp.printRecord( );
}
}
-------------------------------------------------------------------
page. 31
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------
NullPointerException :-
import java.util.Scanner;
class Program{ //Program.class
public static void main(String[] args) {
//Non static field(s) declared inside class is called instance
variable
//A metod of a class which is designed to call on instance is
called instance method.
class Employee{ //Concrete class
String name; //instance variable
int empid; //instance variable
float salary; //instance variabl
/*
page. 32
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Exception in thread "main" java.lang.NullPointerException
at Program.main(Program.java:33)
*/
//Using null object, if we try to access any member of the class
then JVM throws NullPointerException
}
}
-------------------------------------------------------------------
To avoid NullPointerException Program :-
import java.util.Scanner;
class Program{ //Program.class
//Employee e1; //Error
//Employee e2 = new Employee(); // Error
public static void main(String[] args) {
//We can not use reference or instance of local class outside
method.
class Employee{ //Concrete class
String name; //instance variable
int empid; //instance variable
float salary; //instance variable
page. 34
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Import java.util.Scanner;
class Employee{
String name;
int empid;
float salary;
page. 35
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
//this is implicit reference variable which is available in
every non static method
//of a class which is used to store reference of
current/calling instance.
//this is keyword in Java.
//this is method parameter hence it doesnt get space inside
inside.
//It gets space once per method call.
page. 36
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------
Getters & Setters:-
Object ke ander ki salary asani se read kr pa rahe hai aur modify bhi
kar pa rahe the upar wale program mai.pr object oriented dekhe tho aisa
nhi hona chahiye is liye solution hai instance variable ko private kr do.
ab value directly print nhi honi chahiye method through hi hona
chahiye.
sirf read krna hai change nhi krana tho getsalary method banayege.
SOP statement print on console but now we used getters they provide
flixiblity if you want print only name, only empid,only salary also then
can print on console.
ab muje kuch change karna honga tho mai setter method use kr sakta hu.
setter method likhenge clas mai jakar.
import java.util.Scanner;
class Program{ //Program.class
public static void main(String[] args) {
class Employee{
private String name;
private int empid;
private float salary; //Data hiding
void acceptRecord( ){
Scanner sc = new Scanner( System.in );
System.out.print("Name : ");
this.name = sc.nextLine();
System.out.print("Empid : ");
this.empid = sc.nextInt();
System.out.print("Salary : ");
this.salary = sc.nextFloat();
}
void printRecord( ){
System.out.println("Name : "+this.name);
System.out.println("Empid : "+this.empid);
System.out.println("Salary : "+this.salary);
}
}
page. 38
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------
ab iss program mai user input lenge.
import java.util.Scanner;
class Program{ //Program.class
public static void main(String[] args) {
class Employee{
private String name;
private int empid;
private float salary; //Data hiding
System.out.println("Name : "+emp.getName());
System.out.println("Empid : "+emp.getEmpid());
System.out.println("Salary : "+emp.getSalary());
}
}
page. 39
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------
Global Class :-
Ab muje iss program mai date program outside main used karna hai par
local se kaam nhi chalenga isliye date class ko global mai likhana
padenga.
import java.util.Scanner;
class Date{
private int day;
private int month;
private int year;
public int getDay() {
return this.day;
}
public void setDay(int day) {
this.day = day;
}
public int getMonth() {
return this.month;
}
public void setMonth(int month) {
this.month = month;
}
public int getYear() {
return this.year;
}
public void setYear(int year) {
this.year = year;
}
}
class Program{
public static void main(String[] args) {
Date date = new Date( );
date.setDay(25);
date.setMonth(03);
date.setYear(2022);
System.out.println(date.getDay()+" / "+date.getMonth()+" /
"+date.getYear());
}
}
-------------------------------------------------------------------
page. 40
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Constructor:-
import java.util.Scanner;
class Date{
private int day;
private int month;
private int year;
public void initDate( ){ //Constructor
this.day = 11;
this.month = 8;
this.year = 2021;
}
public void acceptRecord( ){
Scanner sc = new Scanner( System.in );
System.out.print("Day : ");
this.day = sc.nextInt();
System.out.print("Month : ");
this.month = sc.nextInt();
System.out.print("Year : ");
this.year = sc.nextInt();
}
public void printRecord( ){
System.out.println(this.day+" / "+this.month+" / "+this.year);
}
}
class Program{
public static void main(String[] args) {
date = new Date( ); //0 / 0/ 0
date.intiDate(); // 25/03/2022
date.acceptRecord(); // 28/10/2022
date.intiDate(); // 25/03/2022
date.printRecord(); // 25/03/2022
}
}
//Logically yaha galat ho raha hai initdate humne intialization ke likhe
hai
//aur intilization one time hota hai aur intilization ek bar hona chahiye
aur call bhi ek hi bar hona chahiye
//so this is not intialization
//now we change in next program then the intialization happend only once
-------------------------------------------------------------------------
page. 41
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
import java.util.Scanner;
class Date{
private int day;
private int month;
private int year;
public Date( ){ //Constructor
this.day = 11;
this.month = 8;
this.year = 2021;
}
public void acceptRecord( ){
Scanner sc = new Scanner( System.in );
System.out.print("Day : ");
this.day = sc.nextInt();
System.out.print("Month : ");
this.month = sc.nextInt();
System.out.print("Year : ");
this.year = sc.nextInt();
}
public void printRecord( ){
System.out.println(this.day+" / "+this.month+" / "+this.year);
}
}
class Program{
public static void main(String[] args) {
Date date = null;
date = new Date( );
date.acceptRecord();
}
}
page. 42
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
4. It gets called once per instance.
• We can not call constructor on instance explicitly Employee emp =
new Employee(); emp.Employee( ); //Not Ok
• Types of constructor:
1. Parameterless constructor
2. Parameterized constructor
3. Default constructor.
class Employee{
private String name; //Fields
private int empid;
private float salary;
//parameterless constructor /zero argument constructor/user defined
default constructor
public Employee( ){
this.name = "";
this.empid = 0;
this.salary = 0;
}
//parameterized constructor
public Employee( String name, int empid, float salary){
this.name = name;
this.empid = empid;
this.salary = salary;
}
public void printRecord( ){
System.out.println("Name : "+this.name);
System.out.println("Empid : "+this.empid);
System.out.println("Salary : "+this.salary);
}
}
class Program{
public static void main(String[] args) {
Employee emp1 = new Employee();
//Here on instance parameterless constructor will call.
emp1.printRecord();
System.out.println("----------------------------------");
page. 43
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Default Constructor:-
class Employee{
private String name; //null
private int empid; //0
private float salary; //0.0
/*
If we do not define any constructor inside class then compiler
generates one constructor
for the class by default. It is default constructor.
//Compiler generated default constructor
public Employee( ){ //Parameterless constructor
//Empty body
} */
public void printRecord( ){
System.out.println("Name : "+this.name);
System.out.println("Empid : "+this.empid);
System.out.println("Salary : "+this.salary);
}
}
class Program{
public static void main(String[] args) {
Employee emp1 = new Employee( ); //OK
//Here on instance default constructor will call.
emp1.printRecord( );
class Employee{
private String name; //null
private int empid; //0
private float salary; //0.0
page. 44
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
this.salary = salary;
}
public void printRecord( ){
System.out.println("Name : "+this.name);
System.out.println("Empid : "+this.empid);
System.out.println("Salary : "+this.salary);
}
}
class Program{
public static void main(String[] args) {
Employee emp1 = new Employee( ); //NOT OK : Compiler error
emp1.printRecord( );
class Employee{
private String name; //null
private int empid; //0
private float salary; //0.0
public Employee( ) {
this( "Empty", -1, 85000.0f); //Constructor Chaining
}
/*
--> To achieve reusability, we can call constructor from another
constructor.
--> This process of calling constructor from another constructor is
called constructor chaining.
--> For constructor chaining,we should use this statement.
--> this statement must be first statment inside constructor body.
*/
/*
Advanatages of reusability:
1. We can reduce development time
2. We can reduce development cost
3. We can reduce develpers effort.
*/
page. 45
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
public Employee( String name, int empid, float salary ) {
this.name = name;
this.empid = empid;
this.salary = salary;
}
public void printRecord( ){
System.out.println("Name : "+this.name);
System.out.println("Empid : "+this.empid);
System.out.println("Salary : "+this.salary);
}
}
class Program{
public static void main(String[] args) {
Employee emp = new Employee( ); //OK
emp.printRecord( );
}
}
------------------------------------------------------------------------
Coding and Naming convension:-
-------------------------------------------------------------------
page. 46
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Coding Convension For Package Name & Final(const)variable & Enum:-
-------------------------------------------------------------------
Integer Class Constructor :-
class Program{
public static void main1(String[] args) {
//public Integer(int value)
Integer i1 = new Integer( 10 );
System.out.println(i1.toString());
String s = "456";
Integer i2 = new Integer( s );
System.out.println(i2.toString());
}
public static void main3(String[] args) {
String s = "1a2b3c";
Integer i1 = new Integer( s ); //NumberFormatException
page. 47
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
System.out.println(i1.toString());
}
public static void main(String[] args) {
Object objl;
Integer i1 = new Integer( );//error: no suitable constructor
found for Integer(no arguments)
System.out.println(i1.toString());
}
}
-------------------------------------------------------------------
Object Class:-
• It is a non final and concrete class declared in java.lang
package. • In java all the classes( not interfaces )are directly or
indirectly extended from java.lang.Object class.
• In other words, java.lang.Object class is ultimate base
class/super cosmic base class/root of Java class hierarchy.
page. 48
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
• Object class do not extend any class or implement any interface.
• It doesn’t contain nested type as well as field.
• It contains default constructor.
Object o = new Object(“Hello”); //Not OK
Object o = new Object( ); //OK
• Object class contains 11 methods.
• Consider the following code:
• In above code, java.lang.Object is direct super class of class
Person.
page. 49
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------
page. 50
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Difference between primitive and non primitive type?
-------------------------------------------------------------------
Initialization & Assignment:-
class Program{
public static void main1(String[] args) {
//During declaration, process of stroing value inside variable is
called initialization.
int num1 = 10; //Initialization
class Program{
public static void main1(String[] args) {
int number = 10;
number = number + 5;
System.out.println("Number : "+number);//15
}
class Test{
/* private final int number;
public Test( ){
this.number = 10;
//this.number = 20; //Not OK
}*/
page. 53
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
System.out.println("------------");
t.printRecord( );
}
}
• Once initialized, if we don't want to modify state of any field
inside any method of the class( including constructor body ) then
we should declare field final.
• If we want to declare any field final then we should declare it
static also.
-------------------------------------------------------------------
Final Keyword :- (use in object/reference)
class Complex{
private int real;
private int imag;
public Complex(int real, int imag ){
this.real = real;
this.imag = imag;
}
public void setReal(int real) {
this.real = real;
}
public void setImag(int imag) {
this.imag = imag;
}
@Override
public String toString() {
return this.real + " " +this.imag;
}
}
class Program{
public static void main1(String[] args) {
Complex c1 = new Complex( 10, 20 );
c1 = new Complex( 50, 60 );
System.out.println(c1.toString());
}
public static void main(String[] args) {
//Object/referance is final
//Instance is not final.
final Complex c1 = new Complex( 10, 20 ); //Instance is not final
c1.setReal(11);
c1.setImag(22);
//c1 = new Complex( 50, 60 ); //Not OK
page. 54
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
System.out.println(c1.toString()); //11, 22
}
}
• In Java, we can declare reference final but we can not declare
instance final.
• We can declare method final. It is not allowed to override final
method in sub class.
• We can declare class final. It is not allowed to extend final
class.
-------------------------------------------------------------------------
References Memory allocation:-
class Date{
//TODO
}
class Employee{
private String name;
private int empid;
private float salary;
private Date joinDate; //joinDate is non static field of the class.
// Non static field get space inside instance and instance get space on
heap.
public Employee(){
this.joinDate = new Date( );
}
}
class Program{
public static void main(String[] args) {
Date joinDate = new Date( );
//Date joinDate => joinDate is a method local variable. It will
get space on Java Stack.
page. 55
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
//new Date( ) => It is Date instance.It will get space on Heap.
}
}
• Local reference variable get space on Java Stack.
• In above code joinDate is method local reference variable hence
it gets space on Java Stack.
• Class scope reference variable get space on heap.
• In above code, emp is method local reference variable hence it
gets space on Java Stack. But joinDate is field of Employee class
hence it will get space inside instance on Heap.
-------------------------------------------------------------------------
Access Modifier:-
• If we want to control visibility of members of class then we
should use access modifier.
import java.util.Scanner;
/*
- Access modifiers in Java
1. private
2. package level private / default
3. protected
4. public
page. 56
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
- In Java, members of a class are by default considered as package
level private i.e default.
*/
class Employee{
private String name;
private int empid;
private float salary;
//Parameterless constructor / zero argument constructor / user
defined default constructor
//We can use any access modifier on constructor including the
private
public Employee( ){
}
//Parameterized constructor
//If name of method parameter / Method local variable and name
of field is same then preference is always is given to the local
variable/parameter
//In this case we should use this before members of class.
public Employee( String name, int empid, float salary){
this.name = name;
this.empid = empid;
this.salary = salary;
}
public void acceptRecord( ){
Scanner sc = new Scanner( System.in );
System.out.print("Name : ");
this.name = sc.nextLine();
System.out.print("Empid : ");
this.empid = sc.nextInt();
System.out.print("Salary : ");
this.salary =sc.nextFloat();
}
page. 57
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Employee emp1 = new Employee( "Sandeep", 33, 23000.50f );
//here on instance, parameterized constructor will call
emp1.printRecord( );
//this is looking for parameter less constructor.if you not
written then error give.
Employee emp2 = new Employee( );//Error:here on instance,
parameterized constructor will call
emp1.acceptRecord( );
emp1.printRecord( );
}
//Only Fields of the class gets space once per instance,
according to their order of declaration inside class.
//Method do not get space inside instance. Rather all the
instances of same class share single copy of it.
//By passing reference, all the instances of same class share
methods defined inside class.
public static void main(String[] args) {
Employee e1 = new Employee( "Digvijay", 11, 25000.50f );
Employee e2 = new Employee( "Rahul", 12, 27000.50f );
Employee e3 = new Employee( "Sandeep", 13, 28000.50f );
e1.printRecord( ); //e1.printRecord( e1 );
e2.printRecord( ); //e2.printRecord( e2 );
e3.printRecord( ); //e3.printRecord( e3 );
}
}
Only Fields of the class gets space once per instance, according to
their order of declaration inside class.
Method do not get space inside instance. Rather all the instances of
same class share single copy of it.
By passing reference, all the instances of same class share methods
defined inside class.
page. 58
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------
page. 59
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Static Field:-
import java.util.Scanner;
/*
- A field of a class which get space inside instance is called
instance variable.
- In other words, non static field declared inside class gets
space inside instance. Hence it is called instance variable.
- Instance variable get space after instantiation( i.e after
creating instance ).
- To access instance variable we must use object reference.
- We can not call non static method on class name. Non static
method is designed to call on instance.
- A method, which is designed to call on instance is called
instance method.
- Since non static method is designed to call on instance, it
is also called as instance method.
t1.printRecord( );
t2.printRecord( );
t3.printRecord( );
page. 61
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------
import java.util.Scanner;
/*
- To intialize non static field / instance variable we should
use constructor.
- To intialize static field / class level variable we should
use static initializer block.
- JVM execute static initializer block during class loading.
*/
class Test{
private int num1; //Non static field / Instance
variable
private int num2; //Non static field / Instance
variable
private static int num3; //static field / Class level
variable
//Constructor
public Test( int num1, int num2){
this.num1 = num1;
this.num2 = num2;
//Test.num3 = 500; // OK: But not recommended
//this.num3 = 500; //OK : Warning The static field
Test.num3 should be accessed in a static way
}
//Concrete method
public void printRecord( ){ //Non static method
System.out.println("Num1 : "+this.num1);
System.out.println("Num2 : "+this.num2);
System.out.println("Num3 : "+Test.num3);
//System.out.println("Num3 : "+this.num3);//OK :
Warning The static field Test.num3 should be accessed in a static
way
System.out.println("-------------------------");
}
}
class Program{
public static void main(String[] args) {
Test t1 = new Test( 10, 20 );
Test t2 = new Test( 30, 40 );
Test t3 = new Test( 50, 60 );
t1.printRecord( );
t2.printRecord( );
t3.printRecord( );
}
}
page. 63
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
• There is an alternative to static blocks — you can write a
private static method:
-------------------------------------------------------------------
Some modification for understanding purpose:-
import java.util.Scanner;
/*
- To intialize non static field / instance variable we should
use constructor.
- To intialize static field / class level variable we should
use static initializer block.
- JVM execute static initializer block during class loading.
*/
class Test{
private int num1; //Non static field / Instance variable
private int num2; //Non static field / Instance variable
private static int num3;//static field / Class level variable
private static int num4;//static field / Class level variable
private static int num5;//static field / Class level variable
private static int num6;//static field / Class level variable
private static int num7;//static field / Class level variable
private static int num8;//static field / Class level variable
page. 64
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
//Static Initializer Block
static{
System.out.println("Static initlizer block#1");
Test.num3 = 500;
Test.num4 = 600;
Test.num5 = 700;
}
static{
System.out.println("Static initlizer block#2");
Test.num6 = 800;
}
static{
System.out.println("Static initlizer block#3");
Test.num7 = 900;
}
static{
System.out.println("Static initlizer block#4");
Test.num8 = 1000;
}
//Constructor
public Test( int num1, int num2){
System.out.println("constructor block#1");
this.num1 = num1;
this.num2 = num2;
// Test.num3 = 500; // OK: But not recommended
// this.num3 = 500; //OK : Warning The static field
Test.num3 should be accessed in a static way
}
//Concrete method
public void printRecord( ){ //Non static method
System.out.println("Num1 : "+this.num1);
System.out.println("Num2 : "+this.num2);
System.out.println("Num3 : "+Test.num3);
System.out.println("Num4 : "+Test.num4);
System.out.println("Num5 : "+Test.num5);
System.out.println("Num6 : "+Test.num6);
System.out.println("Num7 : "+Test.num7);
System.out.println("Num8 : "+Test.num8);
page. 65
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
//System.out.println("Num3 : "+this.num3);//OK :
Warning The static field Test.num3 should be accessed in a static
way
System.out.println("-------------------------");
}
}
class Program{
public static void main(String[] args) {
Test t1 = new Test( 10, 20 );
Test t2 = new Test( 30, 40 );
Test t3 = new Test( 50, 60 );
t1.printRecord( );
t2.printRecord( );
t3.printRecord( );
}
}
/*Output:-
-------------------------------------------------------------------
page. 66
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Sequence of execution observe the output:-
import java.util.Scanner;
/*
- To intialize non static field / instance variable we should
use constructor.
- To intialize static field / class level variable we should
use static initializer block.
- JVM execute static initializer block during class loading.
*/
class Test{
private int num1; //Non static field / Instance
variable
private int num2; //Non static field / Instance
variable
private static int num3; //static field / Class level
variable
//Constructor
public Test( int num1, int num2){
System.out.println("Inside constructor of class Test");
this.num1 = num1;
this.num2 = num2;
}
//Concrete method
public void printRecord( ){ //Non static method
System.out.println("Num1 : "+this.num1);
System.out.println("Num2 : "+this.num2);
System.out.println("Num3 : "+Test.num3);
System.out.println("-------------------------");
}
}
class Program{
static{
System.out.println("Inside static initialization block of
class Program"); 1
}
page. 67
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
public Program() {
System.out.println("Inside constructor of class Program");
}
public static void main(String[] args) throws Exception {
System.out.println("Inside main method"); 2
t1.printRecord( );
t2.printRecord( );
t3.printRecord( );
}
}
/*Output:-
-------------------------------------------------------------------
page. 68
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
class Program{
static{
System.out.println("Inside static initialization block of
class Program");
Program.myMain();
}
public static void myMain( ){
System.out.println("Hello from my main");
}
}
/*Error:- main method hona chahiye
static{
System.out.println("Inside static initialization block of class
Program");
Program.myMain();
}
*/
-------------------------------------------------------------------
/*
- Non static methods are designed to call on instance. Hence it
is also called as instance method.
- Static methods are designed to call on class name. Hence it
is called as class level method.
- In General conclusion:
1. To access non static members, method should be non
static.
2. To access static members method should be static.
- Static method do not get this reference. Why?
1. If we call, non static method on instance then method
get this reference.
2. Static methods are designed to call on class name.
3. Static method is not designed to call on instance hence
static method do not get this reference.
- Since static method do not get this reference, we can not
access non static members inside static method.
- In other words, inside static method, we can access only
static members;
- Inside non static method, we can access static as well as non
static members
- Static method do not get this reference but we can create
instance inside static method.
- Using instance, we can access non static members inside
static method.
page. 69
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
*/
class Test{
private int num1; //Non static field / instance
variable
private int num2; //Non static field / instance
variable
private static int num3; //static field / class level
variable
public Test() {
}
public void setNum1( /* Test this, */ int num1 ){ //Non static
/ Instance method
this.num1 = num1;
}
public void setNum2( /* Test this, */ int num2 ){ //Non static
/ Instance method
this.num2 = num2;
}
public static void setNum3( /* this reference is not required*/
int num3 ){ //Static Method / Class level method
Test.num3 = num3;
}
public void printRecord( /* Test this */){
System.out.println("Num1 : "+this.num1);
System.out.println("Num2 : "+this.num2);
System.out.println("Num3 : "+Test.num3);
}
public static void displayRecord( ){
Test t1 = new Test();
t1.setNum1(10); //t1.setNum1(t1, 10);
t1.setNum2(20); //t1.setNum2(t1, 20);
Test.setNum3(30);
t1.printRecord( );
}
}
class Program{
public static void main(String[] args) {
Test.displayRecord( );
}
public static void main1(String[] args) {
Test t1 = new Test();
t1.setNum1(10); //t1.setNum1(t1, 10);
t1.setNum2(20); //t1.setNum2(t1, 20);
page. 70
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Test.setNum3(30);//static method design to call on class
name.
t1.printRecord( );
}
}
-------------------------------------------------------------------
class Program{
//- Using instance, we can access non static members inside static
method.
public int num1 = 10;
public static int num2 = 20;
public static void main(String[] args) {
//System.out.println("Num1 : "+num1); //error: non-
static variable num1 cannot be referenced from a static context
Program p = new Program();
System.out.println("Num1 : "+p.num1); //Ok : 10
System.out.println("Num2 : "+num2); //OK : 20
}
}
-------------------------------------------------------------------
class B{
public static void f2( ){
System.out.println("B.f2()");
}
public static void f3( ){
f2(); //OK : B.f2()
B.f2(); //OK : B.f2()
}
}
class Program{
public static void main(String[] args) {
//f3( ); // error: cannot find symbol
B.f3(); //OK
}
}
-------------------------------------------------------------------
InstanceCounter:-
class InstanceCounter{
private static int count;
public InstanceCounter( ){
++ InstanceCounter.count;
}
page. 71
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
public static int getCount( ){
return InstanceCounter.count;
}
}
class Program{
public static void main(String[] args) {
InstanceCounter c1 = new InstanceCounter( );
InstanceCounter c2 = new InstanceCounter( );
InstanceCounter c3 = new InstanceCounter( );
System.out.println("Instance
Count : "+InstanceCounter.getCount());
}
}
-------------------------------------------------------------------
/*
- If constructor is public then we can create instance of a
class inside method of same class
as well as different class
*/
class Complex{
public Complex( ){
System.out.println("Inside constructor");
}
public static void test( ){
Complex c2 = new Complex( ); //OK
}
}
class Program{
public static void main(String[] args) {
Complex c1 = new Complex( ); //OK
Complex.test( );
}
-------------------------------------------------------------------
/*
- We can declare constructor private.
- If constructor is private then we can create instance of a
class inside method of same class only.
*/
class Complex{
private Complex( ){
System.out.println("Inside constructor");
}
public static void test( ){
page. 72
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Complex c2 = new Complex( ); //OK
}
}
class Program{
public static void main(String[] args) {
//Complex c1 = new Complex( ); //error: Complex() has
private access in Complex
Complex.test( );
}
}
-------------------------------------------------------------------
/*
- Inside method, if there is need to use this reference then
method should be non static.
- Otherwise method should be static.
*/
class Calculator{
public static int pow( int base, int index ){
int result = 1;
for( int count = 1; count <= index; ++ count )
result = result * base;
return result;
}
}
class Program{
public static void main(String[] args) {
int result = Calculator.pow(10, 2);
System.out.println("Result : "+result);
}
}
//jis method mai this reference use krne ki jarurat hai use hi non
static karo agar nhi jarurat tho static kr do method ko.
-------------------------------------------------------------------
//If we declare method static then local variable is not consodered
static.
//Non static method local variable get space once per method call.
Hence it doesn't retain last updated value.
class Program{
public static void print( ){
int count = 0; //Non static method local variables
count = count + 1;
System.out.println("Count : "+count); //1
}
page. 73
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
public static void main(String[] args) {
Program.print(); //1
Program.print(); //1
Program.print(); //1
}
}
-------------------------------------------------------------------
//In Java, we can not declare method local variable static.
// Static field and static method is also called as class level
members.
//According to oops, class level members must in class scope. Hence
we can not declare local variable static.
//In Java we can declare field, method, nested type static.
//We can not delcare local variable, constructor and top level
class static.
class Program{
public static void print( ){
static int count = 0; // error: illegal start of expression
count = count + 1;
System.out.println("Count : "+count); //1
}
public static void main(String[] args) {
Program.print();
Program.print();
Program.print();
}
}
-------------------------------------------------------------------
Singleton class
• A class from which, we can create only one instance is called
singleton class.
• Steps to define singleton class:
1. Define class and declare constructor private.
2. Define factory method and return reference of instance from it.
3. Use getter and setter to access members.
//1.Define clas
class Singleton{
private int number;
page. 74
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
}
//4. Declare static field inside class
private static Singleton reference; //null
----------
----------
page. 75
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------
class Singleton{
private static Singleton reference;
static{
reference = new Singleton();
}
private Singleton() {
}
public static Singleton getReference() {
return reference;
}
}
class Program{
public static void main(String[] args) {
Singleton s1 = Singleton.getReference( );
Singleton s2 = Singleton.getReference( );
System.out.println(s1 == s2 ); //true
}
}
-------------------------------------------------------------------
Now my requirement is I want to create dot java file in one folder
and there dot class file in another folder and by this exicute.
page. 76
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------
Package:-
Package is java Language feature which helps developer to
1.To group functionally equivalent or related types together.
2.To avoid naming clashing/collision/conflict/ambiguity in source
code.
3.To control the access to types.
4.To make types easier to find (from the perspective of java docs).
consider following class:
java.lang.object
Here java is main package,lang is sub package and object is
type name.
page. 77
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Not necessarily but as shown below,package can contain some or
types.
1.Sub package 2.Interface 3.class 4.Enum 5.Exception 6.Error
7.Annotation Type.
package is a keyword in Java.
To define type inside package, it is mandatory write package
declaration statement inside .java file.
Package declaration statement must be first statement
inside.java file
If we define any type inside package then it is called as
packaged type otherwise it will be unpackaged type.
Any type can be member of single package only.
Un-named Package
If we define any type without package then it is considered as
member of unnamed/default package.
Unnamed packages are provided by the Java SE platform
principally for convenience when developing small or temporary
applications or when just beginning development.
An unnamed package cannot have sub packages.
In following code, class Program is a part of unnamed package.
Naming Conversion:-
For small programs and casual development, a package can be
unnamed or have a simple name, but if code is to be widely
distributed, unique package names should be chosen using
qualified names.
page. 78
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Companies use their reserved internet domain name to begin
their package names. For example: com.example.mypackage
Following examples will help you in deciding name of package:
java.lang.reflect.Proxy
oracle.jdbc.driver.OracleDriver
com.mysql.jdbc.cj.Driver
org.cdac.sunbeam.dbda.utils.Date
class Program{
public static void main(String[] args) {
java.util.Scanner sc = new java.util.Scanner(System.in);
page. 79
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
import java.util.*;
class Program {
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
}
}
-------------------------------------------------------------------
page. 80
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
[ javac -d./bin ./src/Complex.java
set classpath=./bin
javac -d ./bin ./src/Program.java
java Program ]
package p1;
public class Complex{
//Packaged class agar yaha public nhi likha honga tho by default
access modifier is package level private/default. Package ke baher
used nhi kar sakte isliye usko public declare karte hai.
//name of the public file and dot java file must be same.
@Override
public String toString() {
return "TComplex.toString()";
}
}
import p1.Complex;
class Program {
public static void main(String[] args) {
//p1.Complex c1 = new p1.Complex(); //Solution 1
Complex c1 = new Complex(); //Solution 2
System.out.println( c1.toString() );
}
}
Package name is physically mapped to the folder.
Point to Remember: default access modifier of any type is
package level private which is also called as default.
If we want to use any type inside same package as well as in
different package then access modifier of type must be public.
Access modifier of type (class/interface) can be either package
level private/public only. In other words, type can not be
private or protected.
page. 81
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
//Member of default package
public class Complex{ //Unpackaged class
@Override
public String toString() {
return "TComplex.toString()";
}
}
package p1;
class Program {
public static void main(String[] args) {
Complex c1 = new Complex(); //Can not access here
System.out.println( c1.toString() );
}
}
This cannot run error gives.
----------------------------------------------------------------------
package p1;
public class Complex{
@Override
public String toString() {
return "TComplex.toString()";
}
}
package p2;
import p1.Complex;
class Program {
page. 82
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
public static void main(String[] args) {
Complex c1 = new Complex();
System.out.println( c1.toString() );
}
}
-------------------------------------------------------------------
package p1;
public class Complex{
public String toString(){
return "Complex.toString";
}
}
package p1;
//import p1.Complex; //Optional
class Program {
public static void main(String[] args) {
Complex c1 = new Complex( );
System.out.println( c1.toString() );
}
}
-------------------------------------------------------------------
page. 83
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package p1.p2;
public class Complex{
public String toString(){
return "Complex.toString";
}
}
package p1.p3;
import p1.p2.Complex;
class Program {
public static void main(String[] args) {
Complex c1 = new Complex( );
System.out.println( c1.toString() );
}
}
-------------------------------------------------------------------
//import java.lang.*; //Optional-By default imported.
class Program {
public static final double PI = 3.142;
public static float pow( float base, int index ){
float result = 1;
for( int count = 1; count <= index; count++ )
result = result * base;
return result;
}
public static void main1(String[] args) {//hardcore value
float radius = 10.5f;
float area = ( float )( 3.142 * radius * radius );
System.out.println("Area : "+area);
}
public static void main2(String[] args) {//class name pr call
kiya
float radius = 10.5f;
float area = ( float )( Program.PI * Program.pow(radius, 2)
);
System.out.println("Area : "+area);
}
public static void main(String[] args) {//sab static hai tho
directly call kr sakte
page. 84
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
float radius = 10.5f;
float area = ( float )(PI * pow(radius, 2) );
System.out.println("Area : "+area);
}
}
Its present in the dot lang package and in Math class.
To access we can used Math.PI then for pow Math.Pow
-------------------------------------------------------------------
//Use Static import for PI and pow
}
public static void main(String[] args) {
float radius = 10.5f;
float area = (float) (PI * pow(radius, 2));
System.out.println("Area : "+area);
}
}
//Eclipse shortcut
//Ctrl+ space for suggestion
//ctrl+ 1 for error soln typecast
//click on PI create constant PI
//ctrl + 1 pow and create method
-------------------------------------------------------------------
page. 86
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
This written in Employee java file
package com.sunbeaminfo.cj06.model;
public class Employee {
private String name;
private int empid;
private float salary;
public Employee() {
// TODO Auto-generated constructor stub
}
public Employee(String name, int empid, float salary) {
this.name = name;
this.empid = empid;
this.salary = salary;
}
@Override
public String toString() {
return "Employee [name=" + name + ", empid=" + empid + ",
salary=" + salary + "]";
}
}
// System.out.println(emp.toString());
System.out.println("Name : "+emp.getName());
System.out.println("Empid : "+emp.getEmpid());
System.out.println("Salary : "+emp.getSalary());
}
public static void main3(String[] args) {
Employee emp = new Employee("Sandeep", 33, 35000.50f );
System.out.println(emp); //Employee [name=Sandeep,
empid=33, salary=35000.5]
}
}
-------------------------------------------------------------------
page. 88
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Scanner used kiya bas.
package com.sunbeaminfo.cj06.model;
package com.sunbeaminfo.cj06.test;
import java.util.Scanner;
page. 89
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
import com.sunbeaminfo.cj06.model.Employee;
public class Program {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Name : "+emp.getName());
System.out.println("Empid : "+emp.getEmpid());
System.out.println("Salary : "+emp.getSalary());
}
}
//Sca ctrl+space hit enter.
-------------------------------------------------------------------
AcceptRecord PrintRecord method use kiye bas:-
package com.sunbeaminfo.cj06.model;
package com.sunbeaminfo.cj06.test;
import java.util.Scanner;
public class Program {
public static void acceptRecord( Employee emp ) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter name : ");
emp.setName( sc.nextLine() );
System.out.print("Enter empid : ");
emp.setEmpid( sc.nextInt() );
System.out.print("Enter salary : ");
emp.setSalary( sc.nextFloat() );
}
public static void printRecord( Employee emp ) {
System.out.println("Name : "+emp.getName());
System.out.println("Empid : "+emp.getEmpid());
System.out.println("Salary : "+emp.getSalary());
}
public static void main(String[] args) {
Employee emp = new Employee();
Program.acceptRecord(emp);
Program.printRecord(emp);
}
}
//this used nhi kiya tho static karna method.
page. 91
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Menu driven program make in this:-
package com.sunbeaminfo.cj06.model;
page. 92
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
import java.util.Scanner;
import com.sunbeaminfo.cj06.model.Employee
/*
Stream is abstraction which produces(write) or consume(read)
information to & from source & destnation.
// Following are standard stream object of Java associated with
console:
1. System.in => Keyborad
2. System.out => Monitor
3. System.err => Monitor ( It is error stream. It should be
used to display errors)
*/
package com.sunbeaminfo.cj06.test;
import java.util.Scanner;
import com.sunbeaminfo.cj06.model.Employee;
page. 94
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
} */
package com.sunbeaminfo.cj06.model
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@NoArgsConstructor //Annotation
@AllArgsConstructor //Annotation
@Getter @Setter //Annotation
@ToString //Annotation
page. 95
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
public class Employee {
private String name;
private int empid;
private float salary;
}
-------------------------------------------------------------------
Array
page. 96
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
• Advantage Of Array
1. We can access elements of array randomly.
• Disadvantage Of Array
1. We can not resize array at runtime.
2. It requires continuous memory.
3. Insertion and removal of element from array is a time consuming
job.
4. Using assignment operator, we can not copy array into another
array.
5. Compiler do not check array bounds( min and max index ).
Array In Java
page. 97
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
page. 98
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
page. 99
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
/*
If this class object represents a class of arrays, then the
internal form of the name consists of the name of the element type
preceded by one or more '[' characters representing the depth of
the array nesting. The encoding of element type names is as
follows:
Element Type Encoding
boolean Z
byte B
char C
class or interface Lclassname;
double D
float F
int I
long J
short S
*/
public class Program {
public static void main1(String[] args) {
int[] arr = new int[ 3 ]; //OK
System.out.println( arr[ 0 ] ); //0
System.out.println( arr[ 1 ] ); //0
System.out.println( arr[ 2 ] ); //0
}
public static void main2(String[] args) {
int[] arr = new int[ 3 ]; //OK
for( int index = 0; index < 3; ++ index )
System.out.println( arr[ index ] ); //0
}
public static void main(String[] args) {
boolean[] arr1 = new boolean[ 3 ];
System.out.println(arr1.toString()); //[Z@6d06d69c
@means hash code
page. 100
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
int[] arr5 = new int[ 3 ]; //OK
System.out.println(arr5.toString()); //[I@5c647e05
-------------------------------------------------------------------
page. 101
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
import java.util.Arrays;
import java.util.Objects;
import java.util.Scanner;
System.out.println( Arrays.toString(arr));
/* System.out.println(arr[ 0 ]);
System.out.println(arr[ 1 ]);
System.out.println(arr[ 2 ]); */
}
public static void main3(String[] args) {
int[] arr = new int[ 3 ]; //user input value
-------------------------------------------------------------------
Mavan used in eclipse like lambok jar file.
-------------------------------------------------------------------
Using toString()Method :-
package com.sunbeaminfo.cj06.test;
import java.util.Arrays;
import java.util.Objects;
import java.util.Scanner;
page. 104
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
//"{ 10, 20, 30 }" is called as initializer
element = arr[ 2 ];
System.out.println( element ); //30
element = arr[ 4 ];
System.out.println( element ); //50
}
public static void main(String[] args){
int[ ] arr = new int[ ] { 10, 20, 30, 40, 50 };
System.out.println(arr.length); //5
page. 105
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
//Thrown to indicate that an array has been accessed with an
illegal index.
//The index is either negative or greater than or equal to the
size of the array.
}
}
-------------------------------------------------------------------
Referance Copy and Instance copy:-
page. 106
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
import java.util.Arrays;
-------------------------------------------------------------------
Sorting Arrays Elements:-
page. 107
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
import java.util.Arrays;
-------------------------------------------------------------------
For each Loop:-
package com.sunbeaminfo.cj06.test;
import java.util.Arrays;
package com.sunbeaminfo.cj06.test;
import java.util.Arrays;
page. 109
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
int[] arr2 = new int[ 3 ];
System.out.println(Arrays.toString(arr2)); //[0, 0, 0]
-------------------------------------------------------------------
Array Of References and Instances :-
package com.sunbeaminfo.cj06.test;
import java.util.Arrays;
class Date{
private int day, month, year;
public void printRecord( ) {
System.out.println(this.day+" / "+this.month+" / "+this.year);
}
}
public class Program {
public static void main1(String[] args) {
Date dt1 = null;
page. 110
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Date dt2 = null;
Date dt3 = null;
page. 111
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Arrays Of references
-------------------------------------------------------------------
page. 112
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Example 1:-
package com.sunbeaminfo.cj06.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@NoArgsConstructor
@AllArgsConstructor
@Getter @Setter
public class Employee {
private String name;
private int empid;
private float salary;
@Override
public String toString() {
return String.format("%-30s%-5d%-10.2f", this.name,
this.empid, this.salary);
}
}
package com.sunbeaminfo.cj06.test;
import java.util.Arrays;
import com.sunbeaminfo.cj06.model.Employee;
-------------------------------------------------------------------
Multi Dimensional Array :-
package com.sunbeaminfo.cj06.test;
import java.util.Objects;
import java.util.Scanner;
page. 114
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
public class Program {
}
}
-------------------------------------------------------------------
page. 116
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
import java.util.Arrays;
import java.util.Objects;
import java.util.Scanner;
page. 117
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
int[][] arr = new int[ ][ ] {
{1,2,3},{4,5,6},{7,8,9},{10,11,12}}; //OK
//System.out.println(arr.toString()); //[[I@6d06d69c
//System.out.println(Arrays.toString(arr)); //[[I@6d06d69c,
[I@7852e922, [I@4e25154f, [I@70dea4e]
page. 118
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Ragged Array :-
package com.sunbeaminfo.cj06.test;
import java.util.Scanner;
Program.acceptRecord( arr );
Program.printRecord( arr );
}
}
-------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
import java.util.Arrays;
import java.util.Scanner;
page. 121
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
System.out.println(Arrays.deepToString(arr));
}
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---------------------------------
Argument Passing Methods :-
page. 122
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
• In Java programming language, we can pass argument to the method
using a way:
1. By value.
In other word, every variable of primitive type/non
primitive type is pass to the method by value only.
package com.sunbeaminfo.cj06.test;
public class Program {
public static void swap( int a, int b ) { //a & b are method
parameters / parameters
int temp = a;
a = b;
b = temp;
}
public static void main(String[] args) {
int x = 10;
int y = 20;
-------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
import java.util.Scanner;
page. 124
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
/*
- C Programming language is procedure oriented programming language.
- In C, we can not give same name to the methods.
- According to oops theory, if implementation of methods are
logically same / equivalent
then we should give same name to the method.
*/
public class Program {
private static void add(int num1, int num2) {
int result = num1 + num2;
System.out.println("Result : "+result);
}
private static void sum(double num1, double num2) {
double result = num1 + num2;
System.out.println("Result : "+result);
}
public static void main(String[] args) {
add( 10, 20 );
----------------------------------------------------------------------
Variable Arity/Argument Method:-
package com.sunbeaminfo.cj06.test;
public class Program {
//Variable argument method / variable arity method
public static void sum( int... args ) {
int result = 0;
for( int element : args )
result = result + element;
System.out.println("Result : "+result);
}
public static void main(String[] args) {
Program.sum( );
Program.sum( 10, 20 );
Program.sum( 10, 20, 30, 40, 50 );
Program.sum( 10, 20, 30, 40, 50, 60, 70 );
Program.sum( 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 );
}
}
----------------------------------------------------------------------
page. 128
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Debugging:-
package com.sunbeaminfo.cj06.test;
/*
- Logical error is called as bug.
- In other words, syntactically valid but logically invalid
statement represents bug.
- Technique of finding bug is called as debugging.
- If we want to debug code then perspective should be Debug.
- To debug the code it is mandatory to use breakpoint( also
called as stop point )
- If we debug code without breakpoint then it is same as run.
----------------------------------------------------------------------
page. 129
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Enum In C/C++ Programming Language.:-
-------------------------------------------------------------------
Enum In Java Programming language:-
• An enum is a special class that represents a group of constants.
• Enum keyword is used to create an enum. The constants declared
inside are separated by a comma and should be in upper case.
page. 130
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Enum Class Hierarchy:-
Enum API:-
page. 131
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Properties of enum:-
Application of enum 1. enum is used for values that are not going
to change e.g. names of days, colors in a rainbow, number of cards
in a deck etc. 2. enum is commonly used in switch statements and
below is an example of it:
page. 132
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------
Example 1:-
// package com.sunbeaminfo.cj06.test;
import java.util.Arrays;
enum Color{
RED, GREEN, BLUE
//RED=0, GREEN=1, BLUE=2
}
/*
final class Color extends Enum<Color> {
public static final Color RED;
page. 133
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
System.out.println("Name : "+Color.GREEN.name());
System.out.println("Ordinal : "+Color.GREEN.ordinal());
System.out.println("Name : "+Color.BLUE.name());
System.out.println("Ordinal : "+Color.BLUE.ordinal());
}
color = Color.GREEN;
System.out.println("Name : "+color.name());
System.out.println("Ordinal : "+color.ordinal());
color = Color.BLUE;
System.out.println("Name : "+color.name());
System.out.println("Ordinal : "+color.ordinal());
}
import java.util.Arrays;
import java.util.Scanner;
enum Color{
RED, GREEN, BLUE
//RED=0, GREEN=1, BLUE=2
}
public class Program {
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter color name(RED/GREEN/BLUE): ");
String colorName = sc.nextLine();
Color color = Color.valueOf(colorName.toUpperCase());
System.out.println(color.name()+" "+color.ordinal());
}
}
/*
Enter color name(RED/GREEN/BLUE): PURPLE
Exception in thread "main" java.lang.IllegalArgumentException: No enum
constant com.sunbeaminfo.cj06.test.Color.PURPLE
at java.lang.Enum.valueOf(Enum.java:238)
at com.sunbeaminfo.cj06.test.Color.valueOf(Program.java:1)
at com.sunbeaminfo.cj06.test.Program.main(Program.java:16)
*/
-------------------------------------------------------------------
Example 3:-
// package com.sunbeaminfo.cj06.test;
import java.util.Arrays;
import java.util.Scanner;
enum Day{
//MON=1,TUES=2,WED=3 //In C/C++
MON(1),TUES(2),WED(3);//It must be first statement inside enum
//if you assign name means 1 you have to write construction in
class
private int dayNumber;
page. 135
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
private Day(int dayNumber) {
this.dayNumber = dayNumber;
}
public int getDayNumber() {
return dayNumber;
}
@Override
public String toString() {
return String.valueOf(dayNumber);
}
}
package com.sunbeaminfo.cj06.test;
import java.util.Arrays;
import java.util.Scanner;
enum Day{
MON("MonDay"),TUES("TuesDay"),WED("WednesDay");
private String dayName;
private Day(String dayName) {
this.dayName = dayName;
}
public String getDayName() {
return dayName;
}
@Override
public String toString() {
page. 136
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
return this.dayName;
}
}
import java.util.Arrays;
import java.util.Scanner;
enum Day{
MON(1, "MonDay"),TUES(2, "TuesDay"),WED(3, "WednesDay");
private int dayNumber;
private String dayName;
private Day(int dayNumber, String dayName) {
this.dayNumber = dayNumber;
this.dayName = dayName;
}
public int getDayNumber() {
return dayNumber;
}
public String getDayName() {
return dayName;
}
@Override
public String toString() {
return this.dayNumber+" "+this.dayName;
}
}
page. 137
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
public class Program {
public static void main(String[] args) {
Day day = Day.MON;
System.out.println(day.name()); //MON
System.out.println(day.ordinal()); //0
System.out.println(day.getDayName()); //MonDay
System.out.println(day.getDayNumber()); //1
System.out.println(day.toString());
}
}
-------------------------------------------------------------------
Example 6:-
package com.sunbeaminfo.cj06.test;
import java.util.Arrays;
import java.util.Scanner;
enum Day{
MON(1, "MonDay"),TUES("TuesDay"),WED(3);
private int dayNumber;
private String dayName;
private Day(int dayNumber) {
this(dayNumber, null );
}
private Day(String dayName) {
this( 0, dayName );
}
private Day(int dayNumber, String dayName) {
this.dayNumber = dayNumber;
this.dayName = dayName;
}
page. 138
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
public String getDayName() {
return dayName;
}
@Override
public String toString() {
return this.dayNumber+" "+this.dayName;
}
}
public class Program {
public static void main(String[] args) {
Day[] days = Day.values();
for (Day day : days) {
System.out.println(day.name()+"
"+day.ordinal()+" "+day.getDayName()+" "+day.getDayNumber());
}
}
}
-------------------------------------------------------------------
OOPS
• 4 Major pillars
1. Abstraction
2. Encapsulation
3. Modularity
4. Hierarchy
• 3 Minor Pillars
1. Typing
2. Concurrency
3. Persistence
page. 139
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Advantages of OOPS
1. To achieve simplicity
2. To achieve data hiding and data security.
3. To minimize the module dependency so that failure in single part
should not stop complete system.
4. To achieve reusability so that we can reduce development
time/cost/efforts.
5. To reduce maintenance of the system.
6. To fully utilize hardware resources.
7. To maintain state of object on secondary storage so that failure
in system should not impact on data.
Abstraction
• It is a major pillar of oops.
• It is a process of getting essential things from object.
• It describes outer behaviour of the object.
• Abstraction focuses on some essential characteristics of object
relative to the perspective of viewer. In other words, abstraction
changes from user to user.
• Using abstraction, we can achieve simplicity.
• Abstraction in Java Complex c1 = new Complex( );
c1.acceptRecord( ); c1.printRecord( );
-------------------------------------------------------------------
page. 140
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
import java.util.Scanner;
------------------------------------------------------------------
page. 141
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Encapsulation
• It is a major pillar of oops.
• Definition:
1. Binding of data and code together is called
encapsulation.
2. To achieve abstraction, we should provide some
implementation. It is called encapsulation.
• Encapsulation represents, internal behaviour of the object.
• Using encapsulation we can achieve data hiding.
• Abstraction and encapsulation are complementary concepts:
Abstraction focuses on the observable behaviour of an object,
whereas encapsulation focuses on the implementation that gives rise
to this behaviour.
Modularity
• It is a major pillar of oops.
• It is the process of developing complex system using small parts.
• Using modularity, we can reduce module dependency.
• We can implement modularity by creating library files.
.lib/.a, .dll / .so files
.jar/.war/.ear in java
Hierarchy
• It is a major pillar of oops.
• Level / order / ranking of abstraction is called hierarchy.
• Main purpose of hierarchy is to achieve reusability.
• Advantages of code reusability
1. We can reduce development time.
page. 142
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
2. We can reduce development cost.
3. We can reduce developers effort.
• Types of hierarchy:
1. Has-a / Part-of => Association
2. Is-a / Kind-of => Inheritance / Generalization
3. Use-a => Dependency
4. Creates-a => Instantiation
Typing
• It is a minor pillar of oops.
• Typing is also called as polymorphism.
• Polymorphism is a Greek word. Polymorphism = Poly( many ) +
morphism( forms ).
• An ability of object to take multiple forms is called
polymorphism. • Using polymorphism, we can reduce maintenance of
the system.
• Types of polymorphism:
1. Compile time polymorphism
It is also calling static polymorphism / Early binding / Weak
Typing / False polymorphism.
We can achieve it using:
1. Method Overloading
Concurrency
page. 143
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Persistence
• It is a minor pillar of oops.
• It is process of maintaining state of object on secondary
storage. • In Java, we can achieve Persistence using file and
database.
--------------------------------------------------------------
Association:-
page. 144
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
page. 145
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Solution by program:
package com.sunbeaminfo.cj06.association.lib;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@NoArgsConstructor
@AllArgsConstructor
@Getter @Setter
@ToString
public class Person {
private String name; //Association
private Date birthDate; //Association
private Address currentAddress; //Association
}
package com.sunbeaminfo.cj06.association.lib;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@NoArgsConstructor
@AllArgsConstructor
@Getter @Setter
@ToString
public class Date {
private int day;
private int month;
private int year;
}
package com.sunbeaminfo.cj06.association.lib;
page. 146
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@NoArgsConstructor
@AllArgsConstructor
@Getter @Setter
@ToString
public class Address {
private String cityName;
private String stateName;
private String pincode;
}
//We create a jar file from this above three java file and used in
another so we can achieve modularity.
package com.sunbeaminfo.cj06.association.test;
import java.util.Objects;
import java.util.Scanner;
import com.sunbeaminfo.cj06.association.lib.Address;
import com.sunbeaminfo.cj06.association.lib.Date;
import com.sunbeaminfo.cj06.association.lib.Person;
page. 149
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.date.test;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.Date;
page. 151
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------
page. 152
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.date.test;
import lombok.Builder;
import lombok.Setter;
import lombok.ToString;
@Setter @ToString
class Employee{
private String name;
private int empid;
private float salary;
}
public class Program {
public static void main1(String[] args) {
Employee emp = new Employee();
emp.setName("Sandeep");
emp.setEmpid(33);
emp.setSalary(45000.50f);
System.out.println(emp.toString());
}
}
-------------------------------------------------------------------
package com.sunbeaminfo.cj06.date.test;
import lombok.Builder;
import lombok.Setter;
import lombok.ToString;
@Builder @ToString
class Employee{
private String name;
private int empid;
private float salary;
}
public class Program {
public static void main(String[] args) {
Employee emp = Employee.builder()
.name("Sandeep")
.empid(33)
.salary(45000.56f)
.build();
System.out.println(emp);
}
}---------------------------------------------------------------------
page. 153
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Inheritance:-
• If "is-a" relationship is exist between the types then we should
use inheritance.
• Inheritance is also called as generalization.
• Example
1. Manager is a employee
2. Book is a product
3. Triangle is a shape
4. SavingAccount is a account.
-------------------------------------------------------------------
page. 154
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Example 1:
// package com.sunbeaminfo.cj06.inheritance.test;
class Person{
String name;
int age;
public Person( ) {
}
public Person( String name, int age ) {
this.name = name;
this.age = age;
}
public void showRecord( ) {
System.out.println("Name : "+this.name);
System.out.println("Age : "+this.age);
}
}
public class Program {
public static void main1(String[] args) {
//Person p1 = new Person( );
Person p1 = new Person( "Sandeep", 38 );
p1.showRecord();
}
public static void main(String[] args) {
Person p1 = new Person( );
p1.name = "Sandeep";
p1.age = 38;
System.out.println("Name : "+p1.name);
System.out.println("Age : "+p1.age);
}
}
Example 2:
package com.sunbeaminfo.cj06.inheritance.test;
class Employee{
page. 155
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
String name;
int age;
int empid;
float salary;
public Employee() {
}
public Employee( String name, int age, int empid, float salary ) {
this.name = name;
this.age = age;
this.empid = empid;
this.salary = salary;
}
public void displayRecord( ) {
System.out.println("Name : "+this.name);
System.out.println("Age : "+this.age);
System.out.println("Empid : "+this.empid);
System.out.println("Salary : "+this.salary);
}
}
public class Program {
public static void main(String[] args) {
Employee emp = new Employee("Sandeep", 38, 33, 45000.50f );
emp.displayRecord();
}
public static void main1(String[] args) {
Employee emp = new Employee();
emp.name = "Sandeep";
emp.age = 38;
emp.empid = 33;
emp.salary = 45000.50f;
System.out.println("Name : "+emp.name);
System.out.println("Age : "+emp.age);
System.out.println("Empid : "+emp.empid);
System.out.println("Salary : "+emp.salary);
}
}
page. 156
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------
Example 3 :- very very important according concept point of view.
// package com.sunbeaminfo.cj06.inheritance.test;
import java.sql.PseudoColumnUsage;
System.out.println("Name : "+person.name);
System.out.println("Age : "+person.age);
}
public static void main2(String[] args) {
Person person = new Person("Sandeep", 38);
person.showRecord();
}
page. 158
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
public static void main3(String[] args) {
Employee emp = new Employee();
emp.name = "Sandeep";
emp.age = 38;
emp.empid = 33;
emp.salary = 45000.50f;
System.out.println("Name : "+emp.name);
System.out.println("Age : "+emp.age);
System.out.println("Empid : "+emp.empid);
System.out.println("Salary : "+emp.salary);
}
}
public static void main8(String[] args) {
Person person = new Person();
person.name = "Sandeep"; //OK
person.age = 38; //OK
//person.empid = 33; //NOT OK
//person.salary = 45000.50f; //NOT OK
//sub class ke member super class mai inherite nhi hote
System.out.println("Name : "+person.name);
System.out.println("Age : "+person.age);
}
}
• If we create instance of sub class then all the non static fields
declared in super class and sub class get space inside it. In other
words, non static fields of super class inherit into sub class.
page. 160
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
• All the fields of super class inherit into sub class but only non
static fields gets space inside instance of sub class.
page. 161
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
public class Date{
public void printRecord( ) {
System.out.println("Inside Date.printRecord");
}
}
}
class Employee extends Person{ // Child Class / Sub Class
}
public class Program {
public static void main(String[] args) {
Employee.Date dt1 = new Employee().new Date();
dt1.printRecord();
//super class ka nested class sub class mai inherite ho jata
jai.
}
public static void main1(String[] args) {
Person.Date dt1 = new Person().new Date();
dt1.printRecord();
}
}
--------------------------------------------------------------------
Ex:5
package com.sunbeaminfo.cj06.inheritance.test;
class Person{
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void showRecord( ) {
System.out.println("Name : "+this.name );
System.out.println("Age : "+this.age );
}
}
page. 162
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
class Employee extends Person{
private int empid;
private float salary;
public void setEmpid(int empid) {
this.empid = empid;
}
public void setSalary(float salary) {
this.salary = salary;
}
public void displayRecord( ) {
this.showRecord();
System.out.println("Empid : "+this.empid);
System.out.println("Salary : "+this.salary);
}
}
public class Program {
public static void main1(String[] args) {
Person p = new Person( );
p.setName("Sandeep");
p.setAge(38);
p.showRecord();
}
public static void main(String[] args) {
Employee emp = new Employee();
emp.setName("Sandeep");
emp.setAge(38);
emp.setEmpid(33);
emp.setSalary(45000.50f);
emp.displayRecord();
}
//private member sub class mai inherite ho jate hai.
}
-------------------------------------------------------------------
Ex: 6 same program above concept
// Testing if a subclass can access the private members of a
superclass
class Class1 {
private String name;
page. 163
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
public void setName(String name) {
this.name = name;
System.out.println("The name has been set successfully.");
}
class InheritanceTest {
public static void main(String[] args) {
c1.setName("Name_C1");
c2.setName("Name_C2"); //No error, setName() is a public
member of the superclass which indirectly gives access to the private
member "name".
page. 164
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
c1.showName();
c2.showName(); //No error, showName() is a public member of
the superclass which indirectly gives access to the private member
"name".
c2.setAge(25);
c2.showAge();
//c2.displayName(); //error
}
}
Conclusion
Yes, a subclass can indirectly access the private members of a
superclass. A subclass can't directly access the private members of
a superclass.
All the public, private and protected members (i.e. all the fields
and methods) of a superclass are inherited by a subclass but the
subclass can directly access only the public and protected members
of the superclass. If an inherited member from a superclass gives
access to a private member of the superclass then the subclass can
use this inherited member to access the private member of the
superclass.
-------------------------------------------------------------------
Ex.7
package p1;
public class A {
private int num1 = 10;
int num2 = 20;
protected int num3 = 30;
public int num4 = 40;
public void showRecord( ) {
//System.out.println("Num1 : "+this.num1); //OK
//System.out.println("Num2 : "+this.num2); //OK
//System.out.println("Num3 : "+this.num3); //OK
//System.out.println("Num4 : "+this.num4); //OK
}
}
page. 165
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package p
public class B extends A{
public void displayRecord( ) {
//System.out.println("Num1 : "+this.num1); //The field
A.num1 is not visible
// private member inhirate hote hai pr access nhi hote
package p2;
import p1.A;
public class C extends A{
public void printRecord( ) {
//System.out.println("Num1 : "+this.num1); //The field
A.num1 is not visible
//System.out.println("Num1 : "+this.num2); //The field
A.num1 is not visible
//System.out.println("Num3 : "+this.num3); //OK
System.out.println("Num4 : "+this.num4); //OK
}
}
package p2;
import p1.A;
public class D {
public void printRecord( ) {
A a = new A( );
//System.out.println("Num1 : "+a.num1); //The field A.num1
is not visible
//System.out.println("Num2 : "+a.num2); //The field A.num1
is not visible
//System.out.println("Num3 : "+a.num3); //The field A.num3
is not visible
System.out.println("Num4 : "+a.num4); //OK
page. 166
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
}
}
package p1;
import p2.C;
import p2.D;
D d = new D( );
d.printRecord();
}
public static void main2(String[] args) {
//Private
/* A a = new A( );
System.out.println("Num1 : "+a.num1);*/ //The field
A.num1 is not visible
/* A a = new A( );
System.out.println("Num2 : "+a.num2); //OK */
---------------------------------------------------------------------
Ex.8
package com.sunbeam.cj06.inheritance.parent;
package com.sunbeaminfo.cj06.inheritance.child;
import com.sunbeam.cj06.inheritance.parent.Person;
/*
- According to clients requirement , if implementation of super class
method is
partially complete / logically incomplete then we should redefine /
override that method
page. 168
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
inside sub class.
- Process of redefining method of super class inside sub class is
called method overriding.
*/
class Employee extends Person{
private int empid;
private float salary;
public Employee() {
}
public Employee(String name, int age, int empid, float salary) {
super(name, age);
this.empid = empid;
this.salary = salary;
}
//super class aur sub class method ka naam same ho tho
//super keyword pr method call karna pdta hai
public void printRecord( ) {
super.printRecord();
System.out.println("Empid : "+this.empid);
System.out.println("Salary : "+this.salary);
}
}
import java.util.Scanner;
class Person{
private String name;
private int age;
public Person() {
}
page. 169
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
class Employee extends Person{
private int empid;
private float salary;
public Employee() {
}
public Employee(String name, int age, int empid, float salary) {
super(name, age);
this.empid = empid;
this.salary = salary;
}
public int getEmpid() {
return empid;
}
public void setEmpid(int empid) {
this.empid = empid;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
}
page. 170
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
class InheritanceTest{
private static Scanner sc = new Scanner(System.in);
Person person = new Person();
Employee emp = new Employee();
public void acceptPersonRecord( ) {
System.out.print("Name : ");
person.setName(sc.nextLine());
System.out.print("Age : ");
person.setAge(sc.nextInt());
}
public void acceptEmployeeRecord( ) {
System.out.print("Name : ");
emp.setName(sc.nextLine());
System.out.print("Age : ");
emp.setAge(sc.nextInt());
System.out.print("Empid : ");
emp.setEmpid(sc.nextInt());
System.out.print("Salary : ");
emp.setSalary(sc.nextFloat());
}
public void printPersonRecord( ) {
System.out.println("Name : "+person.getName());
System.out.println("Age : "+person.getAge());
}
public void printEmployeeRecord( ) {
System.out.println("Name : "+emp.getName());
System.out.println("Age : "+emp.getAge());
System.out.println("Empid : "+emp.getEmpid());
System.out.println("Salary : "+emp.getSalary());
}
}
public class Program {
public static void main(String[] args) {
InheritanceTest test = new InheritanceTest();
//test.acceptPersonRecord();
//test.printPersonRecord();
test.acceptEmployeeRecord();
test.printEmployeeRecord();
}
page. 171
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
}
//I don’t want multiple printzRecord and acceptRecord. Here only two
class but if we have more.
----------------------------------------------------------------------
package com.sunbeaminfo.cj06.inheritance.test;
import java.util.Scanner;
class Person{
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
class Employee extends Person{
private int empid;
private float salary;
public Employee() {
}
public Employee(String name, int age, int empid, float salary) {
super(name, age);
this.empid = empid;
this.salary = salary;
}
public int getEmpid() {
return empid;
page. 172
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
}
public void setEmpid(int empid) {
this.empid = empid;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
}
class InheritanceTest{
private static Scanner sc = new Scanner(System.in);
private Person person; //null
public void setPerson(Person person) {
this.person = person;
}
public void acceptRecord( ) {
if( this.person != null ) {
//TODO
}
}
public void printRecord( ) {
if( this.person != null ) {
//TODO
}
}
}
public class Program {
public static void main(String[] args) {
InheritanceTest test = new InheritanceTest();
test.setPerson( new Person() );
//test.acceptRecord();
//test.printRecord();
import java.awt.image.ReplicateScaleFilter;
import java.util.Scanner;
class Person{
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void showRecord( ) {
System.out.println("Name : "+this.name);
System.out.println("Age : "+this.age);
}
public void printRecord( ) {
System.out.println("Name : "+this.name);
System.out.println("Age : "+this.age);
}
}
class Employee extends Person{
private int empid;
private float salary;
public Employee() {
}
public Employee(String name, int age, int empid, float salary) {
super(name, age);
this.empid = empid;
this.salary = salary;
}
public void printRecord( ) {
super.printRecord();
System.out.println("Empid : "+this.empid);
System.out.println("Salary : "+this.salary);
}
page. 174
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
• If name of super class and sub class method is same and if we try
to call such method on instance of sub class then preference is
given to the method of sub class. This is called shadowing.
• Using super keyword, we can access members of super class inside
method of sub class.
• During inheritance, members of sub class do not inherit into
super class. Hence using super class instance, we can access
members of super class only.
• During inheritance, members of super class, inherit into sub
class. Hence using sub class instance, we can access members of
super class as well as sub class.
page. 176
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
page. 177
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
page. 179
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
• Process of converting reference of sub class into reference of
super class is called as upcasting.
• Using upcasting, we can minimize object dependency in the code.
In other words, we can reduce maintenance of the code.
• During upcasting, explicit type casting is optional.
• Super class reference variable can contain reference of sub class
instance. It is also called as upcasting.
Person p = new Employee( ); //Upcasting
• In case of upcasting, using super class reference variable, we
can access:
1. Fields of super class 2. Methods of super class 3. overridden
methods of sub class
• In case of upcasting, using super class reference variable, we
can not access:
1. fields of sub class 2. Non overridden methods of sub class.
• If we want to access fields and non overridden methods of sub
class then we should do down casting.
page. 180
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
• Process of converting reference of super class into reference of
sub class is called down casting.
• Only in case of upcasting, we should do down casting. Otherwise
JVM will throw ClassCastException.
• In case of upcasting, using super class reference variable, we
can access overridden method of sub class. It is also called as
dynamic method dispatch.
Ex.
// package com.sunbeaminfo.cjo6.inheritance.test;
/*
- Process of redefining method of super class inside sub class is
called method overriding
page. 181
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
- In case of upcasting, process of calling method of sub class
using reference of super class
is called dynamic method dispatch.
*/
class A{ //Super Class
public void f1( ) {
System.out.println("A.f1");
}
public void f2( ) {
System.out.println("A.f2");
}
}
class B extends A{ //Sub Class
public void f2( ) {
System.out.println("B.f2");
}
public void f3( ) {
System.out.println("B.f3");
}
}
public class Program {
public static void main(String[] args) {
A a = new B( ); //Upcastng
a.f2(); //OK : B.f2 => Dynamic Method Dispatch
}
public static void main1(String[] args) {
A a = new B( ); //Upcastng
a.f1(); //OK : A.f1
//a.f3(); //Not OK
B b = (B) a; //Downcasting
b.f3();//OK : B.f3
}
}---------------------------------------------------------------------
Ex.
package com.sunbeaminfo.cjo6.inheritance.test;
//In Java, all the methods are by default virtual.
class A{ //Super Class
public void f2( ) {
page. 182
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
System.out.println("A.f2");
}
}
class B extends A{ //Sub Class
public void f2( ) {
System.out.println("B.f2");
}
public void f3( ) {
System.out.println("B.f3");
}
}
public class Program {
public static void main(String[] args) {
A a = new B( );
a.f2();//OK : B.f2
//a.f3( ); //NOT OK
}
}
----------------------------------------------------------------------
Overriding:-
• Process of redefining method of super class inside sub class is
called method overriding.
• Method redefined in sub class is called overrided method.
• When we call method of sub class using reference of super class
then it is called dynamic method dispatch.
• If implementation of super class method is partially complete
then we should redefine/override method inside sub class.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
--------------------------------------------------
package com.sunbeaminfo.cjo6.inheritance.test;
abstract class A{
public abstract void f1( );
public abstract void f2( );
public abstract void f3( );
}
abstract class Helper extends A{
@Override public void f1( ) { }
@Override public void f2( ) { }
@Override public void f3( ) { }
}
class B extends Helper{
@Override
public void f1() {
System.out.println("A.f1");
}
}
class C extends Helper{
@Override
page. 184
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
public void f2() {
System.out.println("B.f2");
}
}
class D extends Helper{
@Override
public void f3() {
System.out.println("C.f3");
}
}
public class Program {
public static void main(String[] args) {
A a = null;
a = new B( );
a.f1();
a = new C( );
a.f2();
a = new D( );
a.f3();
}
}
-------------------------------------------------------------------
package com.sunbeaminfo.cjo6.inheritance.test;
abstract class A{
private int num1;
private int num2;
public A( int num1, int num2 ) { //Sole Constructor
this.num1 = num1;
this.num2 = num2;
}
public void print( ) {
System.out.println("Num1 : "+this.num1);
System.out.println("Num2 : "+this.num2);
}
}
page. 185
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
class B extends A{
private int num3;
public B(int num1, int num2, int num3) {
super(num1, num2); //Look Here
this.num3 = num3;
}
@Override
public void print() {
super.print();
System.out.println("Num3 : "+this.num3);
}
}
public class Program {
public static void main(String[] args) {
A a = new B( 10, 20, 30 );
a.print();
}
}
-------------------------------------------------------------------
package com.sunbeaminfo.cjo6.inheritance.test;
class Account{
private String name;
private int number;
private String type;
private float balance;
public Account() {
}
public Account(String name, int number, String type, float
balance) {
this.name = name;
this.number = number;
this.type = type;
this.balance = balance;
}
public String getName() {
return name;
}
public void setName(String name) {
page. 186
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public float getBalance() {
return balance;
}
public void setBalance(float balance) {
this.balance = balance;
}
@Override
public String toString() {
return "Account [name=" + name + ", number=" + number + ",
type=" + type + ", balance=" + balance + "]";
}
}
abstract class Service{
public abstract void sendMessage( String message );
}
class EmailService extends Service{
@Override
public void sendMessage( String message ){
System.out.println( "Email: "+message );
}
}
class SMSService extends Service{
@Override
public void sendMessage( String message ){
System.out.println( "SMS: "+message );
page. 187
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
}
}
class Bank{
private Account[] accounts;
public Bank( ) {
this.accounts = new Account[ 3 ]; //Array of references
this.accounts[ 0 ] = new Account("Amit", 123,"Saving",
50000.50f);
this.accounts[ 1 ] = new Account("Digvijay",456,"Current",
42000.50f);
this.accounts[ 2 ] = new Account("Rajiv",789,"Loan",
59000.50f);
}
//private EmailService service = new EmailService();
//private SMSService service = new SMSService();
}
}
----------------------------------------------------------------------
package com.sunbeaminfo.cjo6.inheritance.test;
class Rectangle{
private float area;
private float length;
private float breadth;
public Rectangle() {
}
public void setLength(float length) {
this.length = length;
}
public void setBreadth(float breadth) {
this.breadth = breadth;
}
public void calculateArea( ) {
this.area = this.length * this.breadth;
}
public float getArea() {
return this.area;
}
}
class Circle{
private float area;
private float radius;
public Circle() {
}
public void setRadius(float radius) {
this.radius = radius;
}
public void calculateArea( ) {
this.area = (float) (Math.PI * Math.pow(this.radius, 2));
}
page. 189
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
public float getArea() {
return this.area;
}
}
public class Program {
public static void main(String[] args) {
Circle c = new Circle();
c.setRadius(10);
c.calculateArea();
System.out.println("Area : "+c.getArea());
}
public static void main1(String[] args) {
Rectangle rect = new Rectangle();
rect.setLength(10);
rect.setBreadth(20);
rect.calculateArea();
System.out.println("Area : "+rect.getArea());
}
}
---------------------------------------------------------------------
package com.sunbeaminfo.cjo6.inheritance.test;
class Shape{
protected float area;
public Shape() {
}
public final float getArea() {
return this.area;
}
}
class Rectangle extends Shape{
private float length;
private float breadth;
public Rectangle() {
}
public void setLength(float length) {
this.length = length;
}
public void setBreadth(float breadth) {
page. 190
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
this.breadth = breadth;
}
public void calculateArea( ) {
this.area = this.length * this.breadth;
}
}
class Circle extends Shape{
private float radius;
public Circle() {
}
public void setRadius(float radius) {
this.radius = radius;
}
public void calculateArea( ) {
this.area = (float) (Math.PI * Math.pow(this.radius, 2));
}
}
public class Program {
public static void main1(String[] args) {
Circle c = new Circle();
c.setRadius(10);
c.calculateArea();
System.out.println("Area : "+c.getArea());
}
public static void main2(String[] args) {
Rectangle rect = new Rectangle();
rect.setLength(10);
rect.setBreadth(20);
rect.calculateArea();
System.out.println("Area : "+rect.getArea());
}
}
----------------------------------------------------------------------
package com.sunbeaminfo.cjo6.inheritance.test;
import java.util.Scanner;
class Shape{
protected float area;
public Shape() {
page. 191
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
}
public final float getArea() {
return this.area;
}
}
class Rectangle extends Shape{
private float length;
private float breadth;
public Rectangle() {
}
public void setLength(float length) {
this.length = length;
}
public void setBreadth(float breadth) {
this.breadth = breadth;
}
public void calculateArea( ) {
super.area = this.length * this.breadth;
}
}
class Circle extends Shape{
private float radius;
public Circle() {
}
public void setRadius(float radius) {
this.radius = radius;
}
public void calculateArea( ) {
super.area = (float) (Math.PI * Math.pow(this.radius, 2));
}
}
public class Program {
private static Scanner sc = new Scanner(System.in);
private static void acceptRecord(Rectangle rect) {
System.out.print("Length : ");
rect.setLength(sc.nextFloat());
System.out.print("Breadth : ");
rect.setBreadth(sc.nextFloat());
}
private static void acceptRecord(Circle c) {
page. 192
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
System.out.print("Radius : ");
c.setRadius(sc.nextFloat());
}
private static void printRecord(Rectangle rect) {
System.out.println("Area : "+rect.getArea());
}
private static void printRecord(Circle c) {
System.out.println("Area : "+c.getArea());
}
public static int menuList( ) {
System.out.println("0.Exit");
System.out.println("1.Rectangle");
System.out.println("2.Circle");
System.out.print("Enter choice : ");
return sc.nextInt();
}
public static void main(String[] args) {
int choice;
while( ( choice = Program.menuList( ) ) != 0 ) {
switch( choice ) {
case 1:
Rectangle rect = new Rectangle();
Program.acceptRecord( rect );
rect.calculateArea();
Program.printRecord( rect );
break;
case 2:
Circle c = new Circle();
Program.acceptRecord( c );
c.calculateArea();
Program.printRecord( c );
break;
}
}
}
}
----------------------------------------------------------------------
package com.sunbeaminfo.cjo6.inheritance.test;
import java.util.Scanner;
page. 193
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------
package com.sunbeaminfo.cjo6.inheritance.test;
import java.util.Scanner;
----------------------------------------------------------------------
package com.sunbeaminfo.cjo6.inheritance.test;
import java.util.Scanner;
/*
- If we want to compare state of instances then we should use
equals method.
- equals is non final method of java.lang.Object class.
- If we do not define equals method inside class then its super
class's equals method gets called.
- If any class do not contain equals method then Object class's
equals method gets called.
- Consider code of Object class's equals method:
public boolean equals(Object obj) {
return (this == obj);
}
- equals method of Object class compares state of references.
- If we want to compare state of instances of non primitive type
then we should override equals method inside class.
*/
class Employee{
private String name;
private int empid;
private float salary;
public Employee(String name, int empid, float salary) {
this.name = name;
this.empid = empid;
this.salary = salary;
}
}
public class Program {
public static void main1(String[] args) {
int num1 = 10;
int num2 = 10;
if( num1 == num2 )
System.out.println("Equal");
else
System.out.println("Not Equal");
page. 201
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
//Output : Equal
//If we want to compare state of variable of primitive type
then we should use operator ==
}
public static void main2(String[] args) {
/* int num1 = 10;
int num2 = 10;
if( num1.equals(num2) ) //Cannot invoke equals(int) on the
primitive type int
System.out.println("Equal");
else
System.out.println("Not Equal"); */
page. 203
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------
package com.sunbeaminfo.cjo6.inheritance.test;
t.print();
}
}
---------------------------------------------------------------------
EXCEPTION HANDLING
page. 204
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------
Throwable Class
• It is a class declared in java.lang package.
• The Throwable class is the super class of all errors and exceptions in the Java language.
page. 205
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
• Only instances that are instances of Throwable class (or one of its subclasses) are thrown
by the Java Virtual Machine or can be thrown by the Java throw statement.
// package com.sunbeaminfo.cj06.exception.test;
import java.util.Scanner;
System.out.print("Num1 : ");
int num1 = sc.nextInt();
System.out.print("Num2 : ");
int num2 = sc.nextInt();
try {
int result = num1 / num2;
System.out.println("Result : "+result);
}catch(ArithmeticException ex ) {
//System.out.println(ex.getMessage());
ex.printStackTrace();//devloper used this for message
}
System.out.println("Closing resource");
sc.close();
}
}
--------------------------------------------------------------
package com.sunbeaminfo.cj06.exception.test;
import java.util.InputMismatchException;
import java.util.Scanner;
page. 206
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
System.out.println("Opening resource");
Scanner sc = null;
try {
sc = new Scanner(System.in);
System.out.print("Num1 : ");
int num1 = sc.nextInt();
System.out.print("Num2 : ");
int num2 = sc.nextInt();
int result = num1 / num2;
System.out.println("Result : "+result);
}catch(ArithmeticException ex ) {
//System.out.println(ex.getMessage());
//ex.printStackTrace();
System.out.println("ArithmeticException");
}catch( InputMismatchException ex ) {
System.out.println("InputMismatchException");
}
System.out.println("Closing resource");
sc.close();
}
}
------------------------------------------------------------
package com.sunbeaminfo.cj06.exception.test;
import java.util.InputMismatchException;
import java.util.Scanner;
page. 207
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
System.out.println("Result : "+result);
}catch(ArithmeticException | InputMismatchException ex ) {
//Multi Catch Block
System.out.println(ex.getClass().getSimpleName());
}
System.out.println("Closing resource");
sc.close();
}
}
-----------------------------------------------------------------
-----------------------------------------------------------------
package com.sunbeaminfo.cj06.exception.test;
import java.util.Scanner;
page. 208
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
}
System.out.println("Closing resource");
sc.close();
}
}
-------------------------------------------------------------------
package com.sunbeaminfo.cj06.exception.test;
import java.util.Scanner;
-------------------------------------------------------------------
page. 209
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------
package com.sunbeaminfo.cj06.exception.test;
import java.util.Scanner;
page. 211
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
public class Program {
public static void main(String[] args) {
System.out.println("Opening resource");
Scanner sc = null;
try {
sc = new Scanner(System.in);
System.out.print("Num1 : ");
int num1 = sc.nextInt();
System.out.print("Num2 : ");
int num2 = sc.nextInt();
if( num2 == 0 )
//throw 0; //No exception of type int can be thrown;
an exception type must be a subclass of Throwable
//throw new Program(); //No exception of type Program
can be thrown; an exception type must be a subclass of Throwable
throw new ArithmeticException("Divide by zero
exception");
int result = num1 / num2;
System.out.println("Result : "+result);
page. 212
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
int num1 = sc.nextInt();
System.out.print("Num2 : ");
int num2 = sc.nextInt();
if( num2 == 0 )
//throw 0; //No exception of type int can be thrown;
an exception type must be a subclass of Throwable
//throw new Program(); //No exception of type Program
can be thrown; an exception type must be a subclass of Throwable
throw new ArithmeticException("Divide by zero
exception");
int result = num1 / num2;
System.out.println("Result : "+result);
}catch( ArithmeticException ex ) {
System.out.println("Inside catch block");
ex.printStackTrace();
}finally {
System.out.println("Inside finally block");
System.out.println("Closing resource");
sc.close();
}
}
}
-------------------------------------------------------------------
package com.sunbeaminfo.cj06.exception.test;
import java.util.Scanner;
-------------------------------------------------------------------
page. 214
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.exception.test;
import java.util.Iterator;
import java.util.Scanner;
}
public static void main2(String[] args) {
//Program.showRecord();
try {
Program.displayRecord();
} catch (InterruptedException e) {
page. 215
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
e.printStackTrace();
}
}
}
-------------------------------------------------------------------
page. 216
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Custom Exception:-
package com.sunbeaminfo.cj06.exception.test;
/* @SuppressWarnings("serial")
class StackUnderflowException extends RuntimeException{ //UnChecked
Exception
public StackUnderflowException(String message) {
super(message);
}
}
@SuppressWarnings("serial")
class StackOverflowflowException extends
RuntimeException{ //UnChecked Exception
public StackOverflowflowException(String message) {
super(message);
}
} */
@SuppressWarnings("serial")
class StackUnderflowException extends Exception{ //Checked
Exception
public StackUnderflowException(String message) {
super(message);
}
}
@SuppressWarnings("serial")
class StackOverflowflowException extends Exception{ //Checked
Exception
public StackOverflowflowException(String message) {
super(message);
}
}
------------------------------------------------------------------
page. 217
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.exception.test;
import java.util.Scanner;
@SuppressWarnings("serial")
class StackUnderflowException extends Exception{ //Checked
Exception
public StackUnderflowException(String message) {
super(message);
}
}
@SuppressWarnings("serial")
class StackOverflowException extends Exception{ //Checked Exception
public StackOverflowException(String message) {
super(message);
}
}
class Stack{
private int top = -1;
private int[] arr;
public Stack( ) {
this( 5 );
}
public Stack( int size ) {
this.arr = new int[ size ];
}
public boolean empty( ) {
return this.top == -1;
}
public boolean full( ) {
return this.top == this.arr.length - 1 ;
}
public void push(int element) throws StackOverflowException {
if( this.full() )
throw new StackOverflowException("Stack is full");
this.arr[ ++ this.top ] = element;
}
public int peek( ) throws StackUnderflowException {
if( this.empty() )
page. 218
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
throw new StackUnderflowException("Stack is empty");
return this.arr[ this.top ];
}
public void pop( ) throws StackUnderflowException {
if( this.empty() )
throw new StackUnderflowException("Stack is empty");
-- this.top;
}
}
public class Program {
static Scanner sc = new Scanner(System.in);
private static void acceptRecord(int[] element) {
System.out.print("Enter element : ");
element[ 0 ] = sc.nextInt();
}
private static void printRecord(int[] element) {
System.out.println("Removed element : "+element[ 0 ]);
}
public static int menuList( ) {
System.out.println("0.Exit");
System.out.println("1.Push");
System.out.println("2.Pop");
System.out.print("Enter choice : ");
return sc.nextInt();
}
public static void main(String[] args) {
int choice;
int[] element = new int[ 1 ];
Stack stk = new Stack( 5 );
while( ( choice = Program.menuList( ) ) != 0 ) {
try {
switch( choice ) {
case 1:
Program.acceptRecord( element );
stk.push( element[ 0 ] );
break;
case 2:
element[ 0 ] = stk.peek();
Program.printRecord(element);
stk.pop();
page. 219
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
break;
}
} catch (StackOverflowException |
StackUnderflowException e) {
System.out.println(e.getMessage());
}
}
}
}
----------------------------------------------------------------------
Day- 14
package com.sunbeaminfo.cj06.test;
import java.util.Date;
//T : Type
//E : Element
//N : Number
//K : Key
//V : Value
b1.setObject(new Date());
System.out.println(date.toString());
}
public static void main2(String[] args) {
//Box<Date> b1 = new Box<Date>();
b1.setObject(new Date());
System.out.println(date.toString());
}
b1.setObject(new Date());
String str = (String) b1.getObject(); //ClassCastException
System.out.println(str);
page. 221
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
public static void main(String[] args) {
//Box<int> b1 = new Box<int>(); //NOT OK
Box<Integer> b1 = new Box<>(); //OK
}
}
-------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
class Pair<K, V>{
private K key;
private V value;
public void put( K key, V value ) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
}
public class Program {
public static void main(String[] args) {
Pair<Integer, String> p = new Pair<>( );
p.put(1, "DAC");
System.out.println("Key : "+p.getKey());
System.out.println("Value : "+p.getValue());
}
}
-------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
import java.util.Date;
class Box<T extends Number>{//T => Bounded Type Parameter
private T object;
public T getObject() {
return object;
}
public void setObject(T object) {
this.object = object;
page. 222
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
}
}
class Box1<T>{
private T object;
public T getObject() {
return object;
}
public void setObject(T object) {
this.object = object;
}
}
public class Program {
public static void main1(String[] args) {
Box1<Number> b1 = new Box1< >( ); //OK
page. 223
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Box<Date> b7 = new Box< >( ); //Not OK
}
}
-------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
import java.util.ArrayList;
page. 225
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
ArrayList<String> stringList = Program.getStringList();
Program.printStringList( stringList );
}
}
-------------------------------------------------------------------
Wild Card
• In generics "?" is called as wild card which represents unknown type.
• Types of wild card:
1. Unbounded wild card
2. Upper bounded wild card
3. Lower bounded wilds card.
package com.sunbeaminfo.cj06.test;
import java.util.ArrayList;
public class Program {
private static ArrayList<Integer> getIntegerList( ) {
ArrayList<Integer> list = new ArrayList< >( );
list.add(10);
list.add(20);
list.add(30);
return list;
}
private static ArrayList<Double> getDoubleList( ) {
ArrayList<Double> list = new ArrayList< >( );
list.add(10.1);
list.add(20.2);
list.add(30.3);
return list;
}
private static ArrayList<String> getStringList( ) {
ArrayList<String> list = new ArrayList< >( );
list.add("Java");
list.add("Python");
list.add("Ruby");
return list;
}
//UnBounded Wild Card
private static void printList( ArrayList<?> list ) {
page. 226
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
System.out.println(list);
}
public static void main(String[] args) {
ArrayList<Integer> integerList = Program.getIntegerList( );
Program.printList( integerList );
}
}
----------------------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
import java.util.ArrayList;
}
}
-------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
import java.util.ArrayList;
import java.util.Date;
page. 229
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
ArrayList<Object> objectList = Program.getObjectList();
Program.printList(objectList); //OK
}
}
-------------------------------------------------------------------
page. 230
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
import java.util.Date;
public class Program {
//Generic Method
private static void print(Object obj) {
System.out.println(obj);
}
public static void main(String[] args) {
Program.print( true );
Program.print( 'A' );
Program.print( 123 );
Program.print( 3.142 );
Program.print( "Hello" );
Program.print( new Date( ));
}
}
-------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
import java.util.Date;
public class Program {
/* private static <T> void print(T obj) {
page. 231
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
System.out.println(obj);
} */
package com.sunbeaminfo.cj06.test;
import java.util.ArrayList;
import java.util.List;
-------------------------------------------------------------------
page. 233
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
public class Program {
//String is a class hence it is non primitive type
//It is a final class declared in java.lang package.
// String is collection of Character objects
page. 234
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
/* char[] data = { 'S','u','n','B','e','a','m'}; //internally
conversion
String s1 = new String(data); */
}
page. 235
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
public class Program {
public static void main(String[] args) {
String s1 = "Sun";
String s2 = s1 +"Beam";
System.out.println( s1 == s2 ); //false : Because String
instances are immutable
}
}
--------------------------------------------------------------
page. 236
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
import java.util.Date;
page. 238
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Don't share references to the mutable objects. Never store references to external,
mutable objects passed to the constructor; if necessary, create copies, and store
references to the copies. Similarly, create copies of your internal mutable objects
when necessary to avoid returning the originals in your methods.
-----------------------------------------------------------------
String Introduction
• Strings, which are widely used in Java programming, are a sequence of characters. to
manipulate string:
• In the Java programming language, strings are objects.
• We can use following classes
1. java.lang.String : immutable character sequence
2. java.lang.StringBuffer : mutable
3. java.lang.StringBuilder : mutable character sequence
4. java.util.StringTokenizer
5. java.util.regex.Pattern
6. java.util.regex.Matcher
java.lang.Character
• It is a final class declared in java.lang package.
• The Character class wraps a value of the primitive type char in an object.
• This class provides a large number of static methods for character's category (lowercase
letter, digit, etc.) and characters from uppercase to lowercase and vice versa.
determining a for converting
• The fields and methods of class Character are defined in terms of character information
from the Unicode Standard.
• The char data type are based on the original Unicode specification, which defined
characters as fixed-width 16-bit entities.
page. 239
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
• The range of legal code points is now U+0000 to U+10FFFF, known as Unicode scalar
value.
• The set of characters from U+0000 to U+FFFF is sometimes referred to as the Basic
Multilingual Plane (BMP).
• Characters whose code points are greater than U+FFFF are called supplementary
characters.
• The Java platform uses the UTF-16 representation in char arrays and in the String and
StringBuffer classes.
• A char value, therefore, represents Basic Multilingual Plane (BMP) code point
-------------------------------------------------------------------------------------------------------------------
Split String:-
StringTokenizer
• The string tokenizer class allows an application to break a string into tokens.
• Methods of java.util.Enumeration interface
1. boolean hasMoreElements( )
2. E nextElement()
• Methods of java.util.StringTokenizer int countTokens() boolean hasMoreTokens() String
nextToken() class
1. public 2. public 3. public 4. public String nextToken(String delim)
package com.sunbeaminfo.cj06.test;
import java.util.StringTokenizer;
while( stk.hasMoreTokens()) {
arr[ index ++ ] = stk.nextToken();
}
System.out.println(arr[ 0 ]);
System.out.println(arr[ arr.length - 1 ]);
}
public static void main5(String[] args) {
String str = "https://docs.oracle.com/javase/8/docs/api/";
StringTokenizer stk = new StringTokenizer(str, "./:");
System.out.println(stk.countTokens());
String token = null;
while( stk.hasMoreTokens()) {
token = stk.nextToken();
System.out.println(token);
}
}
public static void main4(String[] args) {
String str = "www.sunbeaminfo.com";
StringTokenizer stk = new StringTokenizer(str, ".");
System.out.println(stk.countTokens());
String token = null;
while( stk.hasMoreTokens()) {
token = stk.nextToken();
System.out.println(token);
}
}
public static void main3(String[] args) {
String str = "SunBeam Infotech Pune";
StringTokenizer stk = new StringTokenizer(str);
String token = null;
while( stk.hasMoreTokens()) {
token = stk.nextToken();
System.out.println(token);
}
}
public static void main2(String[] args) {
String str = "SunBeam Infotech Pune";
StringTokenizer stk = new StringTokenizer(str);
page. 241
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
String token = null;
while( stk.hasMoreElements()) {
token = (String) stk.nextElement();
System.out.println(token);
}
}
public static void main1(String[] args) {
String str = "SunBeam Infotech Pune";
StringTokenizer stk = new StringTokenizer(str);
System.out.println(stk.countTokens()); //3
}
}
------------------------------------------------------------------
Regex Expression:-
Pattern and Matcher
• Java.util.regex.Pattern and Matcher Classes are used for matching character sequences
against patterns specified by regular expressions.
• An instance of the Pattern class represents a regular expression that is specified in string
form in a syntax similar to that used by Perl.
• Instances of the Matcher class are used to match character sequences against a given
pattern.
package com.sunbeaminfo.cj06.test;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Validator{
public static final String NAME_PATTERN ="";
public static boolean validateName( String name ) {
return name.matches(NAME_PATTERN);
}
page. 242
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
public static final String EMAIL_PATTERN = "";
public static boolean validateEmail( String email ) {
return email.matches(EMAIL_PATTERN);
}
}
public class Program {
public static void main1(String[] args) {
String email = "[email protected]";
String regex = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-
z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
package com.sunbeaminfo.cj06.test;
import java.util.Scanner;
page. 244
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
System.out.println("Equal");
else
System.out.println("Not Equal");
//Output : Not Equal
}
public static void main3(String[] args) {
StringBuffer sb1 = new StringBuffer("SunBeam");
StringBuffer sb2 = new StringBuffer("SunBeam");
if( sb1.toString().equals(sb2.toString()))
System.out.println("Equal");
else
System.out.println("Not Equal");
//Output : Equal
}
public static void main4(String[] args) {
StringBuffer sb = new StringBuffer("SunBeam");
sb.append("Pune/");
sb.append("Karad");
System.out.println(sb.toString());
}
page. 246
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
page. 247
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Types of inheritance
• Interface Inheritance
During inheritance if super type and sub type is interface then it is called interface
inheritance.
1. Single Inheritance( Valid in Java)
2. Multiple Inheritance( Valid in Java)
3. Hierarchical Inheritance( Valid in Java)
4. Multilevel Inheritance( Valid in Java)
• Implementation Inheritance
During inheritance if super type and sub type is class then it is called implementation
inheritance.
1. Single Inheritance( Valid in Java)
2. Multiple Inheritance( Invalid in Java)
3. Hierarchical Inheritance( Valid in Java)
4. Multilevel Inheritance( Valid in Java)
page. 248
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------
1. If "is-a" relationship is not exist between super type and sub type and if we want same
method design in all the sub types then super type must be interface.
2. Using interface, we can group instances of unrelated type together.
3. Interface can extend more than one interfaces.
4. We can not define constructor inside interface.
5. By default methods of interface are abstract.
• Hint : In case of inheritance if state is not involved in super type then it should be
interface.
----------------------------------------------------------------------------------------------------------
page. 249
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Comparable
• It is interface declared in java.lang package.
• "int compareTo(T other)" is a method of java.lang.Comparable interface.
• If state of current object is less than state of other object then compareTo()
method should return negative integer( -1 ).
• If state of current object is greater than state of other object then
compareTo() method should return positive integer( +1 ).
• If state of current object is equal to state of other object then compareTo()
method should return zero( 0 ).
• If we want to sort, array of non primitive type which contains all the instances
of same type then we should implement Comparable interface
Comparator
• It is interface declared in java.util package.
• "int compare(T o1, T o2)" is a method of java.util.Comparator interface.
• If state of current object is less than state of other object then compare()
method should return negative integer( -1 ).
• If state of current object is greater than state of other object then compare()
method should return positive integer( +1 ).
• If state of current object is equal to state of other object then compare()
method should return zero( 0 ).
• If we want to sort, array of instances of non primitive of different type then
we should implement Comparator interface.
page. 250
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Cloneable Interface Implementation
• If we want to create new instance from existing instance then we should use
clone method.
• clone( ) is non final native method of java.lang.Object class.
• Syntax: Ø protected native Object clone( ) throws
CloneNotSupportedException
• Inside clone() method, if we want to create shallow copy instance then we
should use super.clone( ) method.
• Cloneable is interface declared in java.lang package.
• Without implementing Cloneable interface, if we try to create clone of the
instance then clone() method throws CloneNotSupportedException.
-----------------------------------------------------------
Marker Interface
• An interface which do not contain any member is called marker interface. In
other words, empty interface is called as marker interface.
• Marker interface is also called as tagging interface.
• If we implement marker interface then Java compiler generates metadata for
the JVM, which help JVM to clone/serialize or marshal state of object.
• Example:
1. java.lang.Cloneable
2. java.util.EventListener
3. java.util.RandomAccess 4. java.io.Serializable 5. java.rmi.Remote.
page. 251
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Iterable and Iterator Implementation
• Iterable is interface declared in java.lang package.
• Implementing this interface allows an object to be the target of the "for-each
loop" statement.
• It is introduced in JDK 1.5
• Methods of java.lang.Iterable interface:
1. Iterator iterator() 2. default Spliterator spliterator() 3. default void
forEach(Consumer action)
• Iterator is interface declared in java.util package.
• It is used to traverse collection in forward direction only.
• It is introduced in JDK 1.2
• Methods of java.util.Iterator interface:
1. boolean hasNext() 2. E next() 3. default void remove() 4. default void
forEachRemaining(Consumer action).
---------------------------------------------------------------------------------------------------------
page. 252
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
page. 253
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Local Class
• In Java, we can define class inside scope of another method. It is called local class /
method local class.
• Types of local class:
1. Method local inner class
2. Method local anonymous inner class.
page. 254
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
page. 255
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------
page. 256
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Multithreading: -
-Process
1.Program in execution is called process.
2.Running instance of a program is called process.
3.Process is also called as task.
-Thread
1.Process may contain sub process. It also called as thread.
2.Lightweight process is called thread.
3.Thread is a separate path of execution which runs independently.
-Single tasking: -
1.An ability of OS to execute single task/process at a time is called single tasking.
e.g MS DOS is single user and single tasking OS.
-Multi tasking: -
1.An ability of OS to execute multiple task/process at a time is called single tasking.
e.g Mac OS, ubuntu 20.04, windows 10 etc.
Main objective: -
1.To utilise hardware resources (CPU) efficiently.
-If we develop application using single thread then it is called single threaded
application(STA).
-If we develop application using multiple threads then it is called multi threaded
application.
-java is multithreaded programming language.
1.When JVM starts execution of java application it starts execution of main thread
and garbage collector.
Because of these two threads every java application is multithreaded.
page. 257
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Main thread :-
1.It is user thread /non daemon thread.
2.It is responsible for invoking main method.
3.It’s default priority is Thread.NORM_PRIORITY.
Type Of Thread :-
page. 258
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
If we want to used thread in java program then it is necessary to use
-Types declared in java.lang package.
-Interface
1.Runnable
-Class(es)
1.Thread
2.ThreadGroup
3.ThreadLocal
-Enum
1.Thread State
-Exception
1.IlleagalThreaddStateException
2.IllegalMonitorStateException
3.InterruptedException.
-An interface which is having single abstract method is called functional interface/SAM
interface.
-Runnable
1.It is a functional interface declared in java.lang package
2.void run() is method of runnable interface
3.This method is called B.L method.
Thread is operating system resource.
Java.lang. Thread is java class whose instance represent
OS thread.
Object Runnable
Thread
page. 259
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
-Nested Type
1.State [ Enum]
-Fields
1.MIN_PRIORITY(1)
2.NORM_PRIORITY(5)
3.MAX_PRIORITY(10)
page. 260
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
page. 261
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
page. 262
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Collection Framework: -
• Every value/data stored in data structure is called element.
• Framework is library of reusable classes/interfaces that is used to develop
application.
• Library of reusable data structure classes that is used to develop java
application is called collection framework.
• Main purpose of collection framework is to manage data in RAM efficiently.
• Consider following Example: 1. Person has-a birthdate 2. Employee is a person
• In java, collection instance do not contain instances rather it contains
reference of instances.
• If we want to use collection framework them we should import java.util
package.
Iterable<T>
• It is a interface declared in java.lang package.
• All the collection classes implements Iterable interface hence we can traverse
it using for each loop
• Methods of Iterable interface:
1. Iterator<T> iterator()
2. default Spliterator<T> spliterator()
3. default void forEach(Consumer<? Super T> action)
page. 263
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Collection<E>
• Collection<E> is interface declared in java.util package.
• It is sub interface of Iterable interface.
• It is root interface in collection framework interface hierarchy.
• Default methods of Collection interface
1. default Stream<E> stream()
2. default Stream<E> parallelStream()
3. default boolean removeIf(Predicate<? super E> filter)
List<E>
• It is sub interface of java.util.Collection interface.
• It is ordered/sequential collection.
• ArrayList, Vector, Stack, LinkedList etc. implements List interface. It generally
referred as "List collections".
• List collection can contain duplicate element as well multiple null elements.
• Using integer index, we can access elements from List collection.
• We can traverse elements of List collection using Iterator as well as
ListIterator.
• It is introduced in jdk 1.2.
page. 264
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
• Note: If we want to manage elements of non final type inside List collection
then non final type should override "equals" method.
List<E>
• Abstract methods of List Interface
1. void add(int index, E element)
2. boolean addAll(int index, Collection<? Extends E> c)
3. E get(int index)
4. int indexOf(Object o)
5. int lastIndexOf(Object o)
6. ListIterator<E> listIterator()
7. ListIterator<E> listIterator(int index)
8. E remove(int index)
9. E set(int index, E element)
10. List<E> subList(int fromIndex, int toIndex)
page. 265
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
ArrayList <E>
• It is resizable array.
• It implements List, RandomAccess, Cloneable, Serializable interfaces.
• It is List collection.
• It is unsynchronized collection. Using"Collections.synchronizedList” method,
we can make it synchronized.
List list = Collections.synchronizedList(new ArrayList(...));
• Initial capacity of ArrayList is 10. If ArrayList is full then its capacity gets
increased by half of its existing capacity.
• It is introduced in jdk 1.2
• Note: If we want to manage elements of non final type inside ArrayList then
non final type should override "equals" method.
page. 266
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.collection.test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
page. 270
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
public class Program {
public static List<Integer> getList( ){
List<Integer> list = new ArrayList<>();
list.add( 10 );
list.add( 20 );
list.add( 50 );
return list;
}
public static void main1(String[] args) {
List<Integer> list = Program.getList();
list.add(60);
list.add(70);
list.forEach(System.out::println);
}
public static void main2(String[] args) {
List<Integer> list = Program.getList();
Collection<Integer> c = new ArrayList<Integer>();
c.add(60);
c.add(70);
list.addAll( c );
list.forEach(System.out::println);
}
public static void main3(String[] args) {
List<Integer> list = Program.getList();
list.addAll( Arrays.asList(60,70) );
list.forEach(System.out::println);
}
public static void main4(String[] args) {
List<Integer> list = Program.getList();
list.add(2, 30);
list.add(3, 40);
list.forEach(System.out::println);
}
public static void main5(String[] args) {
List<Integer> list = Program.getList();
list.addAll(2, Arrays.asList(30,40));
list.forEach(System.out::println);
}
}
---------------------------------------------------------------------------------------------------------
page. 271
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.collection.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@NoArgsConstructor
@AllArgsConstructor
@Getter @Setter
@EqualsAndHashCode
//@ToString
public class Employee {
@EqualsAndHashCode.Exclude private String name;
@EqualsAndHashCode.Include private int empid;
@EqualsAndHashCode.Exclude private float salary;
/*@Override
public boolean equals(Object obj) {
if( obj != null ) {
Employee other = (Employee) obj;
if( this.empid == other.empid)
page. 274
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
return true;
}
return false;
}*/
@Override
public String toString() {
return String.format("%-15s%-5d%-10.2f", this.name,
this.empid, this.salary);
}
}
package com.sunbeaminfo.cj06.collection.test;
import java.util.ArrayList;
import com.sunbeaminfo.cj06.collection.model.Employee;
package com.sunbeaminfo.cj06.collection.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
page. 276
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
import java.util.List;
import java.util.Scanner;
import javax.lang.model.element.Element;
import com.sunbeaminfo.cj06.collection.model.Employee;
----------------------------------------------------------------------
Compare by Name , Salary , Empid Program.
package com.sunbeaminfo.cj06.collection.model;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
page. 278
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@NoArgsConstructor
@AllArgsConstructor
@Getter @Setter
@EqualsAndHashCode
//@ToString
public class Employee implements Comparable<Employee> {
@EqualsAndHashCode.Exclude private String name;
@EqualsAndHashCode.Include private int empid;
@EqualsAndHashCode.Exclude private float salary;
/*@Override
public boolean equals(Object obj) {
if( obj != null ) {
Employee other = (Employee) obj;
if( this.empid == other.empid)
return true;
}
return false;
}*/
@Override
public String toString() {
return String.format("%-15s%-5d%-10.2f", this.name,
this.empid, this.salary);
}
@Override
public int compareTo(Employee other) {
return this.empid - other.empid;
}
}
package com.sunbeaminfo.cj06.collection.test;
import java.util.ArrayList;
page. 279
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
import java.util.Collections;
import java.util.Comparator;
import com.sunbeaminfo.cj06.collection.model.Employee;
package com.sunbeaminfo.cj06.collection.util;
import java.util.Comparator;
import com.sunbeaminfo.cj06.collection.model.Employee;
package com.sunbeaminfo.cj06.collection.util;
import java.util.Comparator;
import com.sunbeaminfo.cj06.collection.model.Employee;
package com.sunbeaminfo.cj06.collection.util;
import java.util.Comparator;
import com.sunbeaminfo.cj06.collection.model.Employee;
package com.sunbeaminfo.cj06.collection.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
import javax.lang.model.element.Element;
import com.sunbeaminfo.cj06.collection.model.Employee;
import com.sunbeaminfo.cj06.collection.util.CompareByEmpid;
import com.sunbeaminfo.cj06.collection.util.CompareByName;
import com.sunbeaminfo.cj06.collection.util.CompareBySalary;
----------------------------------------------------------------------
page. 284
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Generic Program of above code.
package com.sunbeaminfo.cj06.collection.model;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@NoArgsConstructor
@AllArgsConstructor
@Getter @Setter
@EqualsAndHashCode
//@ToString
public class Employee implements Comparable<Employee> {
@EqualsAndHashCode.Exclude private String name;
@EqualsAndHashCode.Include private int empid;
@EqualsAndHashCode.Exclude private float salary;
/*@Override
public boolean equals(Object obj) {
if( obj != null ) {
Employee other = (Employee) obj;
if( this.empid == other.empid)
return true;
}
return false;
}*/
@Override
public String toString() {
return String.format("%-15s%-5d%-10.2f", this.name,
this.empid, this.salary);
}
@Override
public int compareTo(Employee other) {
page. 285
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
return this.empid - other.empid;
}
}
package com.sunbeaminfo.cj06.collection.test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
import com.sunbeaminfo.cj06.collection.model.Employee;
package com.sunbeaminfo.cj06.collection.util;
import java.util.Comparator;
import com.sunbeaminfo.cj06.collection.model.Employee;
page. 287
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.collection.util;
import java.util.Comparator;
import com.sunbeaminfo.cj06.collection.model.Employee;
package com.sunbeaminfo.cj06.collection.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.Vector;
import javax.lang.model.element.Element;
import com.sunbeaminfo.cj06.collection.model.Employee;
import com.sunbeaminfo.cj06.collection.util.CompareByEmpid;
import com.sunbeaminfo.cj06.collection.util.CompareByName;
import com.sunbeaminfo.cj06.collection.util.CompareBySalary;
Synchronized Collections
• 1. Vector
• 2. Stack(Sub class of Vector)
• 3. Hashtable
• 4. Properties( Sub class of Hashtable )
Enumeration<E>
• It is interface declared in java.util package.
• Methods of Enumeration I/F
1. boolean hasMoreElements()
2. E nextElement()
• It is used to traverse collection only in forward direction. During traversing, we
can not add, set or remove element from collection.
• It is introduced in jdk 1.0.
• "public Enumeration<E> elements()" is a method of Vector class.
page. 291
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
page. 292
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
page. 293
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Iterator<E>
• It is a interface declared in java.util package.
• It is used to traverse collection only in forward direction. During traversing, we
can not add or set element but we can remove element from collection.
• Methods of Iterator
1. boolean hasNext()
2. E next()
3. default void remove()
4. default void forEachRemaining(Consumer<? Super E> action)
• It is introduced in jdk 1.2
ListIterator<E>
• It is sub interface of Iterator interface.
• It is used to traverse only List Collection in bidirectional.
• During traversing, we can add, set as well as remove element from collection.
• It is introduced in jdk 1.2
• Methods of ListIterator
1. boolean hasNext()
2. E next()
3. boolean hasPrevious()
4. E previous()
5. void add(E e)
6. void set(E e)
7. void remove()
Types of Iterator
1. Fail Fast Iterator
• During traversing, using collection reference, if we try to modify state of
collection and if iterator do not allows us to do the same then such
iterator is called "Fail Fast" Iterator. In this case JVM throws
ConcurrentModificationException.
page. 294
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Stack<E>
• It is linear data structure which is used to manage elements in Last In First Out
order.
• It is sub class of Vector class.
• It is synchronized collection.
• It is List Collection.
• Methods of Stack class
1. public boolean empty()
2. public E push(E item)
page. 295
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
3. public E peek()
4. public E pop()
5. public int search(Object o)
• * Since it is synchronized collection, it slower in performance.
• * For high performance we should use ArrayDeque class.
page. 296
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
LinkedList<E>
• It is a List collection.
• It implements List<E>, Deque<E>, Cloneable and Serializable interface.
• Its implementation is depends on Doubly linked list.
• It is unsynchronized collection. Using Collections.synchronizedList() method,
we can make it synchronized.
List list = Collections.synchronizedList(new LinkedList(...));
• It is introduced in jdk 1.2.
• Note : If we want to manage elements of non-final type inside LinkedList then
non final type should override "equals" method.
• Instantiation
List <integer> list = new LinkedList<>();
----------------------------------------------------------------------------------------------------------
Queue Interface Hierarchy:-
page. 297
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.collection.test;
import java.util.ArrayDeque;
import java.util.Queue;
public class Program {
public static void main1(String[] args) {
Queue<Integer> que = new ArrayDeque<>();
que.add(10);
que.add(20);
que.add(30);
Priority Queue
• PriorityQueue class provides the functionality of the heap data structure.
• The PriorityQueue class provides the facility of using a queue.
• It does not order the elements in a FIFO manner.
• It is based on Priority Heap.
page. 299
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
• The elements of the priority queue are ordered according to the natural
ordering, or by a Comparator provided at queue construction time, depending
on which constructor is used.
// package com.sunbeaminfo.cj06.collection.test;
import java.util.ArrayDeque;
import java.util.Deque;
----------------------------------------------------------------------------------------------------------
page. 301
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Set Interface Hierarchy :-
page. 302
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
TreeSet<E>
• It is Set collection.
• It can not contain duplicate element as well as null element.
• It is sorted collection.
• Its implementation is based on TreeMap
• It is unsynchronized collection.
• Using "Collections.synchronizedSortedSet()” method we can make it
synchronized. SortedSet s = Collections.synchronizedSortedSet(new
TreeSet(...));
• It is introduced in jdk 1.2
• Note : If we want to manage elements of non final type inside TreeSet then
non final type should implement Comparable interface.
• Instantiation Set set = new TreeSet<>( );
Hashing :-
• Hashing is a searching algorithm which is used to search element in constant
time( faster searching).
• In case array, if we know index of element then we can locate it very fast.
• Hashing technique is based on "hashcode".
• Hashcode is not a reference or address of the object rather it is a logical
integer number that can be generated by processing state of the object.
• Generating hashcode is a job of hash function/method.
• Generally hashcode is generated using prime number. Hashing.
• If state of object/instance is same then we will get same hashcode.
• Hashcode is required to generate slot.
• If state same. of objects are same then their hashcode and slot will be
• By processing state of two different object's , if we get same slot then it is
called collision.
page. 303
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
• Collision resolution technique:
Seperate Chaining/ Open Hashing
Open Addressing / Close Hashing
1. Linear Probing
2. Quadratic Probing
3. Double Hashing / Rehashing
• Collection(LinkedList/Tree) maintained per slot is called bucket.
• Load Factor = ( Count of bucket / Total elements );
• In hashcode based collection, if we want manage elements of non final type
then reference type should override equals() and hashcode() method.
• we want to generate hashcode then in sub class.
• hashCode() is non final method of java.lang.Object class.
• Syntax: public native int hashCode( );
• On the basis of state of the object, we should override hashCode() method
• The hashCode method defined by class Object does return distinct integers for
distinct objects. This is typically implemented by converting the internal address
of the object into an integer.
HashSet<E>
• It Set Collection.
• It can not contain duplicate elements but it can contain null element.
• It's implementation is based on HashTable.
• It is unordered collection.
• It is unsynchronized collection. Using Collections.synchronizedSet() method,
we can make it synchronized.
• It is introduced in jdk 1.2
• Note : If we want to manage elements of non final type inside HashSet then
non final type should override equals and hashCode() method.
• Instantiation: - Set <Integer> set = new HashSet<>();
LinkedHashSet<E>
• It is sub class of HashSet class.
• Its implementation is based on linked list and Hashtable.
• It is ordered collection.
page. 304
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
• It is unsynchronized collection. Using Collections.synchronizedSet() method
we can make it synchronized:-
Set s = Collections.synchronizedSet(new LinkedHashSet(...));
• It is introduced in jdk 1.4
• It can not contain duplicate element but it can contain null element.
// package com.sunbeaminfo.cj06.collection.test;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;
set.add(234);
page. 306
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
set.add(9823);
set.add(1863);
set.add(754);
set.add(50);
----------------------------------------------------------------------------------------------------------
page. 307
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Map Interface Hierarchy :-
Dictionary<K,V>
• It is abstract class declared in java.util package.
• It is is super class of Hashtable.
• It is used to store data in key/value pair format.
• It is not a part of collection framework
• It is introduced in jdk 1.0
• Methods:
1. public abstract boolean isEmpty()
2. public abstract V put(K key, V value)
3. public abstract int size()
4. public abstract V get(Object key)
5. public abstract V remove(Object key)
6. public abstract Enumeration<K> keys()
7. public abstract Enumeration<V> elements()
• Implementation of Dictionary is Obsolete.
page. 308
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Map<K,V>
• It is part of collection framework but it doesn't extend Collection interface.
• This interface takes the place of the Dictionary class, which was a abstract
class rather than an interface. totally
• HashMap, Hashtable, TreeMap etc are Map collection’s.
• Map collection stores data in key/value pair format.
• In map we can not insert duplicate keys but we can insert
• It is introduced in jdk 1.2
• Map.Entry<K,V> is nested interface of Map<K,V>.
• Following are abstract methods of Map.Entry interface. duplicate values.
1. K getKey()
2. V getValue()
3. V setValue(V value)
Map<K,V>
• Abstract Methods of Map<K,V>
1. boolean isEmpty()
2. V put(K key, V value)
3. void putAll(Map keySet()
4.int Size()
5.boolean containsKey(Object Key)
6.boolean containsValue(Object value)
7.V.get(Object Key)
8.V remove(Object Key)
9.Void clear()
10.Set<K> KeySet()
11.Collection values()
12.Set<Map.Entry> entrySet() V> m)
• An instance, whose type implements Map.Entry interface is called enrty
instance.
page. 309
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Hashtable<K,V>
• It is Map collection which extends Dictionary class.
• It can not contain duplicate keys but it can contain duplicate
• In Hashtable, Key and value can not be null.
• It is synchronized collection.
• It is introduced in jdk 1.0
• In Hashtable, if we want to use instance non final type as key should override
equals and hashCode method.
HashMap<K,V>
• It is map collection
• It's implementation is based on Hashtable.
• It can not contain duplicate keys but it can contain duplicate values.
• In HashMap, key and value can be null.
• It is unsynchronized collection. Using Collections.synchronizedMap() method,
we can make it synchronized. :-
Map m = Collections.synchronizedMap(new HashMap(...));
• It is introduced in jdk 1.2.
• Instantiation
Map map = new HashMap<>( );
• Note : In HashMap, if we want to use element of non final type as a key then it
should override equals() and hashCode() method.
LinkedHashMap<K,V>
• It is sub class of HashMap class
• Its implementation is based on LinkedList and Hashtable.
• It is Map collection hence it can not contain duplicate keys but it can contain
duplicate values.
• In LinkedHashMap, key and value can be null.
• It is unsynchronized collection. Using Collections.synchronizedMap() method
we can make it synchronized:-
Map m = Collections.synchronizedMap(new LinkedHashMap(...));
• LinkedHashMap maintains order of entries according to the key.
page. 310
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
• Instantiation:-
Map map = new LinkedHashMap<>();
• It is introduced in jdk 1.4
TreeMap<K,V>
• It is map collection.
• It can not contain duplicate keys but it can contain duplicate values.
• It TreeMap, key not be null but value can be null.
• Implementation of TreeMap is based on Red-Black Tree.
• It maintains entries in sorted form according to the key.
• It is unsynchronized collection. Using Collections.synchronizedSortedMap()
method, we can make it synchronized.
SortedMap m = Collections.synchronizedSortedMap(new
TreeMap(...));
• Instantiation:
Map map = new TreeMap<>();
• It is introduced in jdk 1.2
• Note : In TreeMap, if we want to use element of non final type as a key then it
should implement Comparable interface
Programs:-
package com.sunbeaminfo.cj06.collection.test;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
}
public static void main(String[] args) {
Map<Integer, String> map = Program.getMap();
//Program.printKeys( map );
//Program.printValues( map );
//Program.printEntries( map );
//Program.findEntry( map, 1234 );
Program.removeEntry( map, 1234 );
}
}
-------------------------------------------------------------------------------------------------------
page. 313
freelance_Project available to buy contact on 8007592194
SR.NO Project NAME Technology
1 E-Learning HUB React+Springboot+MySql
2 PG MATES React+Springboot+MySql