Core Java Notes by Ashok Pate
Core Java Notes by Ashok Pate
94
2 PG Mates / RoomSharing / Flat Mates React+Springboot+MySql
21
3 Tour and Travel management System React+Springboot+MySql
59
5 HomeRental Booking System React+Springboot+MySql
07
6 Event Management System React+Springboot+MySql
80
8 Agriculture web Project React+Springboot+MySql
9 AirLine Reservation System / Flight booking System React+Springboot+MySql
.in
10 E-commerce web Project React+Springboot+MySql
ys
11 Hospital Management System React+Springboot+MySql
ra
12 E-RTO Driving licence portal React+Springboot+MySql
13 Transpotation Services portal
ar
React+Springboot+MySql
14 Courier Services Portal / Courier Management System React+Springboot+MySql
ith
15 Online Food Delivery Portal React+Springboot+MySql
w
16 Muncipal Corporation Management React+Springboot+MySql
17 Gym Management System de React+Springboot+MySql
co
18 Bike/Car ental System Portal React+Springboot+MySql
19 CharityDonation web project React+Springboot+MySql
20 Movie Booking System React+Springboot+MySql
freelance_Project available to buy contact on 8007592194
21 Job Portal web project React+Springboot+MySql
22 LIC Insurance Portal React+Springboot+MySql
23 Employee Management System React+Springboot+MySql
94
24 Payroll Management System React+Springboot+MySql
25 RealEstate Property Project React+Springboot+MySql
21
26 Marriage Hall Booking Project React+Springboot+MySql
27 Online Student Management portal React+Springboot+MySql
59
28 Resturant management System React+Springboot+MySql
29 Solar Management Project React+Springboot+MySql
07
30 OneStepService LinkLabourContractor React+Springboot+MySql
31 Vehical Service Center Portal React+Springboot+MySql
80
32 E-wallet Banking Project React+Springboot+MySql
33 Blogg Application Project React+Springboot+MySql
34 Car Parking booking Project React+Springboot+MySql
.in
35 OLA Cab Booking Portal React+Springboot+MySql
36 Society management Portal React+Springboot+MySql
ys
37 E-College Portal React+Springboot+MySql
38 FoodWaste Management Donate System React+Springboot+MySql
ra
39 Sports Ground Booking React+Springboot+MySql
ar
40 BloodBank mangement System React+Springboot+MySql
41 Bus Tickit Booking Project React+Springboot+MySql
ith
42 Fruite Delivery Project React+Springboot+MySql
43 Woodworks Bed Shop React+Springboot+MySql
w
44 Online Dairy Product sell Project React+Springboot+MySql
45
46
Online E-Pharma medicine sell Project
FarmerMarketplace Web Project
de
React+Springboot+MySql
React+Springboot+MySql
co
47 Online Cloth Store Project React+Springboot+MySql
48 React+Springboot+MySql
49 React+Springboot+MySql
50 React+Springboot+MySql
https://www.youtube.com/@codewitharrays
94
https://www.instagram.com/codewitharrays/
21
59
07
https://t.me/codewitharrays Group Link: https://t.me/cceesept2023
80
.in
+91 8007592194 +91 9284926333
ys
ra
ar
ith
codewitharrays@gmail.com
w
de
co
https://codewitharrays.in/project
Core Java Notes 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
94
session, they came up with several names such as JAVA, DNA, SILK,
RUBY, etc.
21
• Sun Microsystems released the first public implementation as Java
59
1.0 in 1996.
07
Version History:-
80
.in
ys
ra
ar
ith
w
de
co
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.
94
4. Java Card
A technology that allows small Java-based applications
21
(applets) to be run securely on smart cards and similar
59
small-memory devices.
Components Of Java Platform:-
07
• SDK = Development Tools + Documentation + Libraries + Runtime
80
Environment.
• JDK = Java Development Tools + Java Docs + rt.jar + JVM.
JDK : Java Development Kit.
.in
It is a software, that need to be install on developers
machine.
ys
machine.
• rt.jar file contains core Java API in compiled form.
co
94
21
59
07
Java terminologies:-
80
.in
C++ terminologies Java terminologies
ys
Class Class
Data member Field
ra
Object Instance
Pointer Reference
ith
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
94
method.
5.A class, that we can not extend is called final class
21
6.A method that we can not redefine/override it inside sub class
59
is called final method.
07
class Program_1 {
//Entry point method
80
public static void main(String args[])
{
//Printf("Hello world"); in C
.in
//Std::cout<<"Hello world"<<std::endl; in C++
System.out.println("Hello world"); //in Java
ys
ra
out is java.io.printstream.
ith
java.io.printstream class.
de
//By using Java D compiler you can convert .class file into java
file.
}
}
-------------------------------------------------------------------
page. 4
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Flow of Execution program:-
94
Component of JVM
1.ClassLoader Subsystem
21
a. Bootstrap class loader
b. Extension class loader
59
c. Application class loader
d. User defined class loader
07
80
2.Runtime Data Area
a. Method Area
b. Heap
.in
c. Java stack
d. Pc register
ys
3.Execution Engine
ar
a. Interpreter
ith
The Bytecode is object oriented assembly lang code design for JVM
If we create blank java file then it wont give me compile time
co
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");
94
}
}//Error
21
main method mai access modifier compulsory public hi hona chahiye.
59
main method compulsory static hi hona chahiye.
07
class Program_2 {
public void main(String[] args) {
80
System.out.println("Hello world");
}
}//Error
.in
main method se compulsory return type void hi hona chahiye.
ys
class Program_2 {
ra
}
ith
}//Error
class Program_2 {
public static void MAIN(String[] args) {
co
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");
94
}
}
21
class B{
public static void main(String[] args) {
59
System.out.println("B.main");
}
07
}
class Program_3 {
80
public static void main(String[] args) {
System.out.println("Program.main");
}
.in
}
-->yaha pr three class likhe hai aur three main hai .class file pr
ys
Ans:- no we can not defined more than one main method ,but we can
ith
class Program_4 {
de
System.out.println("Program.main");
}
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 )
94
2. public static void main( String... args )
• Java compiler do not check/invoke main method. JVM invoke main
21
method.
• When we start execution of Java application then JVM starts
59
execution of two threads:
1. Main thread : responsible for invoking main method.
07
2. Garbage Collector : responsible for deallocating memory of
80
unused object.
• We can overload main method in Java.
• We can define main method per class. But only one main can be
.in
considered as entry point method.
ys
Comments
ra
• Types of Comments:
de
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
94
that is known at compile time.
o Types of data type:
21
1. Primitive type(also called as value type )
boolean type
59
Numeric type
1. Integral types(byte, char, short, int, long)
07
2. Floating point types(float, double
80
2. Non primitive type(also called as reference type)
Interface, Class, Type variable, Array
-------------------------------------------------------------------
.in
Wrapper Class
• In Java, primitive types are not classes. But for every primitive
ys
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
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
80
.in
ys
ra
ar
class Program{
ith
}
co
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{
94
public static void main1(String[] args) {
21
//int num1; //declaration of Num1
//During declaration, process of storing values inside variable is
59
called initialization
07
int num1 = 10; //Initialization
int num2 = num1; //Initialization data type hai tho Initialization
80
// num2=num1 this is assignment
System.out.println("Num2 : "+num2);
}
.in
}
-------------------------------------------------------------------------
ys
Widening
ra
class Program{
w
System.out.println("Num2 : "+num2);
}
}
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);
94
}
public static void main(String[] args) {
21
double num1 = 10.5; //Initialization
//int num2 = num1; //error: incompatible types: possible lossy
59
conversion from double to int
int num2 = (int)num1; //Narrowing //OK : 10
07
System.out.println("Num2 : "+num2);
}
80
}
.in
ys
ra
ar
ith
w
de
co
-------------------------------------------------------------------
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
94
Employee *ptr = new Employee(); //Dynamic memory allocation
*/
21
//String is a class declared in java.lang package.
59
String s1 = new String("SunBeam"); //OK
System.out.println(s1);
07
String s2 = "Pune"; //OK
80
System.out.println(s2);
}
.in
public static void main2(String[] args) {
ys
System.out.println("Number : "+number);
}
ith
System.out.println("Number : "+number);
}
co
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);
}
}
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
-------------------------------------------------------------------
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);
}
94
public static void main1(String[] args) {
String str;
21
int num1 = 10;
59
str = String.valueOf(num1); //Boxing
System.out.println("Num1 : "+str);
07
float num2 = 20.5f;
80
str = String.valueOf(num2); //Boxing
System.out.println("Num2 : "+str);
.in
double num3 = 30.5d;
str = String.valueOf(num3); //Boxing
ys
System.out.println("Num3 : "+str);
ra
}
}
ar
//Is program mai hum primitive to non primitive convert kar rahe
ith
page. 15
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
-------------------------------------------------------------------
80
.in
class Program{
public static void sum( int a, int b ){ //a, b => Method Parameters
ys
/ Parameters
ra
}
ith
Assignments
co
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]);
94
int result = num1 + num2;
System.out.println("Result : "+result);
21
}
public static void main(String[] args) {
59
int num1 = Integer.parseInt(args[0]);
07
float num2 = Float.parseFloat(args[1]);
80
double num3 = Double.parseDouble(args[2]);
}
ra
}
//args ka type non primitive hai.so parsing karna padenga.
ar
/*
ith
*/
de
//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
94
System.out.println("World"); //World
System.out.println("!!"); //!!
21
System.out.println("\n"); //print in different line
}
59
public static void main(String[] args) {
String name1 = "Amit Pol";
07
int empid1 = 1122;
float salary1 = 125345.50f;
80
//System.out.println(name1+" "+empid1+" "+salary1);
System.out.printf("%-20s%-5d%-10.2f\n", name1, empid1, salary1);
.in
String name2 = "Mukesh Salunkhe";
int empid2 = 714;
ys
}
ith
}
w
de
co
page. 18
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
80
.in
ys
------------------------------------------------------------------
Console class:-
ra
import java.io.Console;
ar
class Program{
public static void main(String[] args) {
ith
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:-
94
import java.util.Scanner;
class Program{
21
//System.in => Keyboard
//System.out => Monitor
59
//System.err => Error Stream => Monitor
07
public static void main(String[] args) {
//java.util.Scanner sc = new java.util.Scanner( System.in );
80
Scanner sc = new Scanner( System.in);
System.out.print("Enter name : ");
.in
String name = sc.nextLine();
System.out.print("Enter empid : ");
ys
System.out.println("Name : "+name);
ith
System.out.println("Empid : "+empid);
System.out.println("Salary : "+salary);
w
}
de
}
co
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.
94
-----------------------------------------------------------------------
jOptionPane :-
21
//jOptionPane is class include in jvac.swing pacakge
59
//mostly used for GUI
import javax.swing.JOptionPane;
07
class Program{
public static void main(String[] args) {
80
String name = JOptionPane.showInputDialog("Enter name.");
int empid = Integer.parseInt(JOptionPane.showInputDialog("Enter
empid."));
.in
float salary = Float.parseFloat(JOptionPane.showInputDialog("Enter
salary."));
ys
System.out.println("Name : "+name);
ra
System.out.println("Empid : "+empid);
ar
System.out.println("Salary : "+salary);
}
ith
}
w
de
co
-----------------------------------------------------------------------
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));
94
String name = reader.readLine( );
System.out.print("Enter Empid : ");
21
int empid = Integer.parseInt(reader.readLine());
System.out.print("Enter salary : ");
59
float salary = Float.parseFloat(reader.readLine());
07
System.out.println("Name : "+name);
System.out.println("Empid : "+empid);
80
System.out.println("Salary : "+salary);
}
}
.in
/*error: unreported exception IOException; must be caught or declared to
be thrown
ys
*/
ith
w
de
co
-----------------------------------------------------------------------
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
94
use/define class in Java.
• class is a non primitive/reference type in Java.
21
• If we want create object/instance of a class then it is mandatory
to use new operator.
59
• If we create instance using new operator then it gets space on
heap section.
07
• Only fields of the get space once per instance according to order
of their declaration inside class.
80
//day, month, year are realated to Date
class Date{
.in
//Variable declared inside class is called field
//int day, month, year; //OK
ys
}
ith
class Color{
de
int red;
int green;
co
int blue;
}
//xPosition, yPosition related to Point
class Point{
int xPosition;
int yPosition;
}
//real, imag related to Complex
class Complex{
int real;
int imag;
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;
94
int empid;
float salary;
21
}
-----------------------------------------------------------------------
59
import java.util.Scanner;
class Program{
07
public static void main(String[] args) {
Scanner sc = new Scanner( System.in );
80
System.out.print("Name : ");
String name = sc.nextLine( );
.in
System.out.print("Empid : ");
int empid = sc.nextInt();
ys
System.out.print("Salary : ");
ra
}
}
w
-----------------------------------------------------------------------
Referance/Instance:-
• Field
A variable declared inside class / class scope is called a
field.
Field is also called as attribute or property.
• Method
A function implemented inside class/class scope is called as
method.
Method is also called as operation, behavior or message.
• Class
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;
94
class Program{
public static void main(String[] args) {
21
Scanner sc = new Scanner( System.in );
59
class Employee{
String name; //Field => Default value null
07
int empid; //Field => Default value 0
float salary; //Field => Default value 0.0f
80
}
Heap.
de
page. 25
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
page. 26
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
80
.in
-------------------------------------------------------------------
ys
import java.util.Scanner;
ra
class Program{
public static void main(String[] args) {
ar
class Employee{
String name; //Field => Default value null
w
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
94
}
//Employee emp = new Employee();
21
// Employee emp;//error: variable emp might not have been
59
initialized emp.name = "Sandeep";
07
Employee emp;
emp = new Employee();
80
emp.name = "Sandeep";
emp.empid = 33;
.in
emp.salary = 12345.50f;
ys
System.out.println("Name : "+emp.name);
ra
System.out.println("Empid : "+emp.empid);
System.out.println("Salary : "+emp.salary);
ar
}
ith
}
-------------------------------------------------------------------------
w
import java.util.Scanner;
class Program{
co
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(); */
94
//process of calling method on instance is called as message
21
passing
59
/* System.out.println("Name : "+emp.name);
07
System.out.println("Empid : "+emp.empid);
System.out.println("Salary : "+emp.salary); */
80
}
}
.in
-------------------------------------------------------------------
ys
class Program{
public static void main(String[] args) {
ar
class Employee{
//Field / Attribute / Property
w
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);
}
}
94
//Function implemented inside class is called method.
//process of calling method on instance is called as message
21
passing
59
emp.acceptRecord( ); //Message Passing
//Here acceptRecord method is called on emp
07
emp.printRecord( ); //Message Passing
//Here printRecord method is called on emp.
80
}
}
-------------------------------------------------------------------
.in
Local Class:-
import java.util.Scanner;
ys
/*
ith
4. Constructor
*/
//if we define class inside method then it is called method local
class
class Employee{ //Program$1Employee.class
String name;
int empid;
float 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);
94
System.out.println("Salary : "+salary);
}
21
}//End of class Employee
Employee emp = new Employee();
59
emp.acceptRecord( );
emp.printRecord( );
07
}
}
80
------------------------------------------------------------------- .in
ys
ra
ar
ith
w
de
co
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
94
called instance method.
class Employee{ //Concrete class
21
String name; //instance variable
int empid; //instance variable
59
float salary; //instance variabl
07
//A method of a class which is having body is called concrete
method
80
//Concrete Method
void acceptRecord( ){ //instance method
Scanner sc = new Scanner( System.in );
.in
System.out.print("Name : ");
ys
name = sc.nextLine();
System.out.print("Empid : ");
ra
empid = sc.nextInt();
System.out.print("Salary : ");
ar
salary = sc.nextFloat();
ith
}
//Concrete Method
w
System.out.println("Name : "+name);
System.out.println("Empid : "+empid);
co
System.out.println("Salary : "+salary);
}
}//End of class Employee
/*
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
}
}
94
21
59
07
80
.in
-------------------------------------------------------------------
ys
import java.util.Scanner;
ar
94
/* Employee emp = null; //emp is null object
21
emp = new Employee( ); */
59
Employee emp = new Employee();
emp.acceptRecord( );
07
emp.printRecord( );
}
80
}
-------------------------------------------------------------------
This reference:-
.in
• If we call non static method on instance( actually object
ys
page. 34
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
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.
94
Scanner sc = new Scanner( System.in );
System.out.print("Name : ");
21
//name = sc.nextLine();
this.name = sc.nextLine();
59
System.out.print("Empid : ");
//empid = sc.nextInt();
07
this.empid = sc.nextInt();
System.out.print("Salary : ");
80
//salary = sc.nextFloat();
this.salary = sc.nextFloat();
}
.in
void printRecord( /* Employee this */ ){
ys
//System.out.println("Name : "+name);
ra
System.out.println("Name : "+this.name);
//System.out.println("Empid : "+empid);
ar
System.out.println("Empid : "+this.empid);
ith
//System.out.println("Salary : "+salary);
System.out.println("Salary : "+this.salary);
w
}
de
}
co
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.
94
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
21
can print on console.
ab muje kuch change karna honga tho mai setter method use kr sakta hu.
59
setter method likhenge clas mai jakar.
07
import java.util.Scanner;
class Program{ //Program.class
80
public static void main(String[] args) {
class Employee{
.in
private String name;
ys
return this.name;
ith
}
w
this.name = name;
}
co
void acceptRecord( ){
Scanner sc = new Scanner( System.in );
System.out.print("Name : ");
this.name = sc.nextLine();
System.out.print("Empid : ");
this.empid = sc.nextInt();
94
System.out.print("Salary : ");
this.salary = sc.nextFloat();
21
}
59
void printRecord( ){
System.out.println("Name : "+this.name);
07
System.out.println("Empid : "+this.empid);
System.out.println("Salary : "+this.salary);
80
}
}
.in
Employee emp = new Employee();
emp.acceptRecord( ); //Sandeep K 33. 35000.50
ys
emp.setEmpid( 33 );
ith
emp.setSalary( 25000.50f );
w
//System.out.println("Name : "+name);
System.out.println("Name : "+emp.getName());
co
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
94
public String getName() {
return this.name;
21
}
public void setName(String name) {
59
this.name = name;
}
07
public int getEmpid() {
return this.empid;
80
}
public void setEmpid(int empid) {
this.empid = empid;
.in
}
ys
}
public void setSalary(float salary) {
ar
this.salary = salary;
ith
}
}
w
emp.setName( sc.nextLine() );
System.out.print("Empid : ");
emp.setEmpid( sc.nextInt() );
System.out.print("Salary : ");
emp.setSalary( sc.nextFloat() );
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{
94
private int day;
private int month;
21
private int year;
public int getDay() {
59
return this.day;
}
07
public void setDay(int day) {
this.day = day;
80
}
public int getMonth() {
return this.month;
.in
}
public void setMonth(int month) {
ys
this.month = month;
ra
}
public int getYear() {
ar
return this.year;
ith
}
public void setYear(int year) {
w
this.year = year;
de
}
}
co
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;
94
this.year = 2021;
}
21
public void acceptRecord( ){
Scanner sc = new Scanner( System.in );
59
System.out.print("Day : ");
this.day = sc.nextInt();
07
System.out.print("Month : ");
this.month = sc.nextInt();
80
System.out.print("Year : ");
this.year = sc.nextInt();
}
.in
public void printRecord( ){
ys
}
class Program{
ar
date.acceptRecord(); // 28/10/2022
de
date.intiDate(); // 25/03/2022
date.printRecord(); // 25/03/2022
co
}
}
//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;
94
public Date( ){ //Constructor
this.day = 11;
21
this.month = 8;
this.year = 2021;
59
}
public void acceptRecord( ){
07
Scanner sc = new Scanner( System.in );
System.out.print("Day : ");
80
this.day = sc.nextInt();
System.out.print("Month : ");
this.month = sc.nextInt();
.in
System.out.print("Year : ");
this.year = sc.nextInt();
ys
}
ra
}
ith
}
class Program{
w
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;
94
private float salary;
//parameterless constructor /zero argument constructor/user defined
21
default constructor
public Employee( ){
59
this.name = "";
this.empid = 0;
07
this.salary = 0;
}
80
//parameterized constructor
public Employee( String name, int empid, float salary){
this.name = name;
.in
this.empid = empid;
this.salary = salary;
ys
}
ra
System.out.println("Empid : "+this.empid);
ith
System.out.println("Salary : "+this.salary);
}
w
}
de
class Program{
public static void main(String[] args) {
co
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.
94
//Compiler generated default constructor
public Employee( ){ //Parameterless constructor
21
//Empty body
} */
59
public void printRecord( ){
System.out.println("Name : "+this.name);
07
System.out.println("Empid : "+this.empid);
System.out.println("Salary : "+this.salary);
80
}
}
class Program{
.in
public static void main(String[] args) {
Employee emp1 = new Employee( ); //OK
ys
emp1.printRecord( );
ar
OK
//error: constructor Employee in class Employee cannot be applied
w
to given types
de
}
------------------------------------------------------------------------
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) {
94
Employee emp1 = new Employee( ); //NOT OK : Compiler error
emp1.printRecord( );
21
Employee emp2 = new Employee( "Sandeep", 33, 45000.50f ); // OK
59
emp2.printRecord( );
//Here on instance parameterized constructor will call.
07
}
}
80
------------------------------------------------------------------------
Constructor Chaining:-
.in
class Employee{
ys
}
/*
w
constructor.
--> This process of calling constructor from another constructor is
co
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);
}
94
}
class Program{
21
public static void main(String[] args) {
Employee emp = new Employee( ); //OK
59
emp.printRecord( );
}
07
}
------------------------------------------------------------------------
80
Coding and Naming convension:- .in
ys
ra
ar
ith
w
de
co
-------------------------------------------------------------------
page. 46
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Coding Convension For Package Name & Final(const)variable & Enum:-
94
21
59
07
80
-------------------------------------------------------------------
Integer Class Constructor :-
.in
class Program{
ys
System.out.println(i1.toString());
ith
}
public static void main2(String[] args) {
co
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());
}
}
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
-------------------------------------------------------------------
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.
94
21
59
• In case class Employee, class Person is direct super class and
class Object is indirect super class.
07
80
.in
ys
ra
ar
ith
w
de
co
page. 49
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
-------------------------------------------------------------------
page. 50
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Difference between primitive and non primitive type?
94
21
59
07
80
.in
-------------------------------------------------------------------
Initialization & Assignment:-
ys
class Program{
ra
94
21
class Program{
public static void main1(String[] args) {
59
int number = 10;
number = number + 5;
07
System.out.println("Number : "+number);//15
}
80
//ab muze initilization ke bad value modify nhi krna hai
//tho use final keyword used krnege.
.in
public static void main2(String[] args) {
final int number = 10; //Initialization
ys
}
ar
System.out.println("Number : "+number);//15
}
public static void main4(String[] args) {
final int number = 10; //Intialization //OK
//number = 20; //Assignment //NOT OK
//number = number + 5; //Not OK
System.out.println("Number : "+number);//15
}
//
public static void main(String[] args) {
Scanner sc = new Scanner( System.in );
page. 52
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
System.out.print("Number : ");
final int number = sc.nextInt();
//number = number + 5; //Not OK
System.out.println("Number : "+number);
}
}
• In java we do not get const keyword. But we can use final
keyword. • After storing value, if we don’t want to modify it then
we should declare variable final.
• We can provide value to the final variable either at compile time
94
or run time.
-------------------------------------------------------------------
21
Final Keyword:- (Use In Global)
59
//agar field ka value class ke kisi bhi method mai modify
//nhi karna hai bas read krna hai use case mai field ko final declare
07
karna chahiye.
80
class Test{
/* private final int number;
public Test( ){
.in
this.number = 10;
//this.number = 20; //Not OK
ys
}*/
ra
public Test( ){
ith
}
de
System.out.println("Number : "+this.number);
}
public void printRecord( ){
//this.number = this.number + 5; //Not OK
System.out.println("Number : "+this.number);
}
}
class Program{
public static void main(String[] args) {
Test t = new Test( );
t.showRecord( );
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.
-------------------------------------------------------------------
94
Final Keyword :- (use in object/reference)
21
class Complex{
private int real;
59
private int imag;
07
public Complex(int real, int imag ){
this.real = real;
80
this.imag = imag;
}
public void setReal(int real) {
.in
this.real = real;
}
ys
}
ar
@Override
public String toString() {
ith
}
de
class Program{
public static void main1(String[] args) {
co
94
21
59
07
80
.in
-------------------------------------------------------------------------
ys
class Date{
ar
//TODO
}
ith
class Employee{
private String name;
w
// 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.
94
21
59
07
80
.in
ys
ra
ar
ith
w
-------------------------------------------------------------------------
de
Access Modifier:-
co
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
94
private
21
public Employee( ){
}
59
//Parameterized constructor
07
//If name of method parameter / Method local variable and name
of field is same then preference is always is given to the local
80
variable/parameter
//In this case we should use this before members of class.
public Employee( String name, int empid, float salary){
.in
this.name = name;
this.empid = empid;
ys
this.salary = salary;
ra
}
public void acceptRecord( ){
ar
System.out.print("Name : ");
this.name = sc.nextLine();
w
System.out.print("Empid : ");
de
this.empid = sc.nextInt();
System.out.print("Salary : ");
co
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( );
}
94
//Only Fields of the class gets space once per instance,
according to their order of declaration inside class.
21
//Method do not get space inside instance. Rather all the
instances of same class share single copy of it.
59
//By passing reference, all the instances of same class share
methods defined inside class.
07
public static void main(String[] args) {
Employee e1 = new Employee( "Digvijay", 11, 25000.50f );
80
Employee e2 = new Employee( "Rahul", 12, 27000.50f );
Employee e3 = new Employee( "Sandeep", 13, 28000.50f );
.in
e1.printRecord( ); //e1.printRecord( e1 );
e2.printRecord( ); //e2.printRecord( e2 );
ys
e3.printRecord( ); //e3.printRecord( e3 );
ra
}
}
ar
ith
Only Fields of the class gets space once per instance, according to
their order of declaration inside class.
w
Method do not get space inside instance. Rather all the instances of
de
page. 58
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
-------------------------------------------------------------------
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.
94
- We can not call non static method on class name. Non static
21
method is designed to call on instance.
- A method, which is designed to call on instance is called
59
instance method.
- Since non static method is designed to call on instance, it
07
is also called as instance method.
80
- In general to access instance members( instance variable,
instance method ) we must use instance.
.in
*/
class Test{
ys
//Instance variables
private int num1; //Non static field / Instance variable
ra
this.num1 = num1;
this.num2 = num2;
w
this.num3 = 500;
de
}
//Concrete method
co
t1.printRecord( );
t2.printRecord( );
t3.printRecord( );
94
21
59
07
80
.in
ys
• Static field do not get space inside instance rather all the
ith
per class.
• Static Field gets space once per class during class loading on
method area.
• Instance variables are designed to access using object reference.
• Class level variable can be accessed using object reference but
it is designed to access using class name and dot operator.
page. 61
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
-------------------------------------------------------------------
80
.in
Static Initialization Block :-
ys
ra
import java.util.Scanner;
/*
ar
use constructor.
- To intialize static field / class level variable we should
w
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
}
94
//Concrete method
public void printRecord( ){ //Non static method
21
System.out.println("Num1 : "+this.num1);
System.out.println("Num2 : "+this.num2);
59
System.out.println("Num3 : "+Test.num3);
//System.out.println("Num3 : "+this.num3);//OK :
07
Warning The static field Test.num3 should be accessed in a static
way
80
System.out.println("-------------------------");
}
}
.in
class Program{
public static void main(String[] args) {
ys
t1.printRecord( );
t2.printRecord( );
w
t3.printRecord( );
de
}
}
co
page. 63
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
• There is an alternative to static blocks — you can write a
private static method:
94
21
59
07
80
-------------------------------------------------------------------
Some modification for understanding purpose:-
.in
ys
import java.util.Scanner;
ra
/*
- To intialize non static field / instance variable we should
ar
use constructor.
ith
class Test{
co
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;
94
}
21
static{
System.out.println("Static initlizer block#3");
59
Test.num7 = 900;
}
07
static{
System.out.println("Static initlizer block#4");
80
Test.num8 = 1000;
}
.in
//Constructor
public Test( int num1, int num2){
ys
System.out.println("constructor block#1");
ra
this.num1 = num1;
this.num2 = num2;
ar
}
de
//Concrete method
public void printRecord( ){ //Non static method
co
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 );
94
Test t3 = new Test( 50, 60 );
21
t1.printRecord( );
t2.printRecord( );
59
t3.printRecord( );
}
07
}
80
/*Output:-
constructor block#1
constructor block#1
ar
constructor block#1
ith
Num1 : 10 | 30 | 50
Num2 : 20 | 40 | 60
w
-------------------------------------------------------------------
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{
94
private int num1; //Non static field / Instance
variable
21
private int num2; //Non static field / Instance
variable
59
private static int num3; //static field / Class level
variable
07
80
//Static Initializer Block
static{
System.out.println("Inside static initialization block of
.in
class Test");
Test.num3 = 500;
ys
}
ra
//Constructor
ar
this.num1 = num1;
this.num2 = num2;
w
}
de
//Concrete method
public void printRecord( ){ //Non static method
co
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
94
Test t2 = new Test( 30, 40 );
Test t3 = new Test( 50, 60 );
21
t1.printRecord( );
59
t2.printRecord( );
t3.printRecord( );
07
}
}
80
/*Output:-
class Test
ra
Num1 : 10
Num2 : 20
w
Num3 : 500
de
-------------------------
Num1 : 30
co
Num2 : 40
Num3 : 500
-------------------------
Num1 : 50
Num2 : 60
Num3 : 500
-------------------------*/
-------------------------------------------------------------------
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");
}
}
94
/*Error:- main method hona chahiye
static{
21
System.out.println("Inside static initialization block of class
Program");
59
Program.myMain();
}
07
*/
-------------------------------------------------------------------
80
/*
- Non static methods are designed to call on instance. Hence it
is also called as instance method.
.in
- Static methods are designed to call on class name. Hence it
is called as class level method.
ys
- In General conclusion:
ra
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() {
}
94
public void setNum1( /* Test this, */ int num1 ){ //Non static
/ Instance method
21
this.num1 = num1;
}
59
public void setNum2( /* Test this, */ int num2 ){ //Non static
/ Instance method
07
this.num2 = num2;
}
80
public static void setNum3( /* this reference is not required*/
int num3 ){ //Static Method / Class level method
Test.num3 = num3;
.in
}
public void printRecord( /* Test this */){
ys
System.out.println("Num1 : "+this.num1);
ra
System.out.println("Num2 : "+this.num2);
System.out.println("Num3 : "+Test.num3);
ar
}
ith
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;
94
public static int num2 = 20;
public static void main(String[] args) {
21
//System.out.println("Num1 : "+num1); //error: non-
static variable num1 cannot be referenced from a static context
59
Program p = new Program();
System.out.println("Num1 : "+p.num1); //Ok : 10
07
System.out.println("Num2 : "+num2); //OK : 20
80
}
}
-------------------------------------------------------------------
.in
class B{
public static void f2( ){
ys
System.out.println("B.f2()");
}
ra
}
}
w
class Program{
de
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
94
Count : "+InstanceCounter.getCount());
}
21
}
-------------------------------------------------------------------
59
/*
- If constructor is public then we can create instance of a
07
class inside method of same class
as well as different class
80
*/
class Complex{
public Complex( ){
.in
System.out.println("Inside constructor");
}
ys
}
ith
class Program{
public static void main(String[] args) {
w
Complex.test( );
}
co
-------------------------------------------------------------------
/*
- 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( );
}
}
94
-------------------------------------------------------------------
/*
21
- Inside method, if there is need to use this reference then
method should be non static.
59
- Otherwise method should be static.
*/
07
class Calculator{
public static int pow( int base, int index ){
80
int result = 1;
for( int count = 1; count <= index; ++ count )
result = result * base;
.in
return result;
}
ys
}
ra
class Program{
public static void main(String[] args) {
ar
System.out.println("Result : "+result);
}
w
}
de
//jis method mai this reference use krne ki jarurat hai use hi non
static karo agar nhi jarurat tho static kr do method ko.
co
-------------------------------------------------------------------
//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.
94
//According to oops, class level members must in class scope. Hence
we can not declare local variable static.
21
//In Java we can declare field, method, nested type static.
//We can not delcare local variable, constructor and top level
59
class static.
07
class Program{
public static void print( ){
80
static int count = 0; // error: illegal start of expression
count = count + 1;
System.out.println("Count : "+count); //1
.in
}
public static void main(String[] args) {
ys
Program.print();
ra
Program.print();
Program.print();
ar
}
ith
}
-------------------------------------------------------------------
w
Singleton class
• A class from which, we can create only one instance is called
de
singleton class.
• Steps to define singleton class:
co
//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
94
}
21
public int getNumber() {
return this.number;
59
}
public void setNumber(int number) {
07
this.number = number;
}
80
}
class Program{
public static void main(String[] args) {
.in
Singleton s1 = Singleton.getReference( );
s1.setNumber(123);
ys
System.out.println("Number : "+s1.getNumber());
ra
}
public static void main1(String[] args) {
ar
Singleton s1 = Singleton.getReference( );
ith
Singleton s2 = Singleton.getReference( );
System.out.println(s1 == s2 ); //true
w
}
de
}
co
----------
----------
page. 75
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------
class Singleton{
private static Singleton reference;
static{
reference = new Singleton();
}
private Singleton() {
}
public static Singleton getReference() {
94
return reference;
21
}
}
59
class Program{
public static void main(String[] args) {
07
Singleton s1 = Singleton.getReference( );
Singleton s2 = Singleton.getReference( );
80
System.out.println(s1 == s2 ); //true
}
.in
}
-------------------------------------------------------------------
ys
and there dot class file in another folder and by this exicute.
ar
ith
w
de
co
page. 76
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
80
.in
-------------------------------------------------------------------
Package:-
ys
code.
3.To control the access to types.
ith
4.To make types easier to find (from the perspective of java docs).
w
java.lang.object
Here java is main package,lang is sub package and object is
co
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
94
packaged type otherwise it will be unpackaged type.
21
Any type can be member of single package only.
59
07
80
.in
ys
Un-named Package
ra
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
94
How to use package members in different package?
21
If we want to use types declared inside package anywhere
outside the package then
59
1. Either we should use fully qualified type name or
2. import statement.
07
If we are going to use any type infrequently then we should use
fully qualified name.
80
Let us see how to use type using package name.
.in
class Program{
ys
}
ith
import statement.
Let us see how to import Scanner
de
import java.util.Scanner;
co
Class Program{
Public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
}
}
There can be any number of import statements after
packagedeclaration statement.
With the help of(*) we can import entire package.
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);
}
}
94
public nested classes of an enclosing class. Consider following
code.
21
import java.lang.Thread.state;
59
class Program{
public static void main(String[] args) {
07
Thread thread=Thread.currentThread();
State state = thread.getState();
80
}
}
.in
• Note: java.lang package contains fundamental types of core java.
ys
optional.
ar
ith
w
de
co
-------------------------------------------------------------------
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
94
used nhi kar sakte isliye usko public declare karte hai.
21
//name of the public file and dot java file must be same.
@Override
59
public String toString() {
return "TComplex.toString()";
07
}
80
}
import p1.Complex;
.in
class Program {
public static void main(String[] args) {
ys
}
ith
}
Package name is physically mapped to the folder.
w
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 {
94
public static void main(String[] args) {
Complex c1 = new Complex(); //Can not access here
21
System.out.println( c1.toString() );
}
59
}
This cannot run error gives.
07
80
.in
ys
ra
ar
ith
w
de
----------------------------------------------------------------------
package p1;
co
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() );
}
}
94
21
59
07
80
-------------------------------------------------------------------
package p1;
.in
public class Complex{
ys
}
ar
}
ith
package p1;
w
-------------------------------------------------------------------
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;
94
class Program {
public static void main(String[] args) {
21
Complex c1 = new Complex( );
System.out.println( c1.toString() );
59
}
}
07
-------------------------------------------------------------------
80
//import java.lang.*; //Optional-By default imported.
class Program {
public static final double PI = 3.142;
.in
public static float pow( float base, int index ){
ys
float result = 1;
for( int count = 1; count <= index; count++ )
ra
return result;
}
ith
}
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
94
21
59
07
80
.in
ys
ra
ar
ith
-------------------------------------------------------------------
w
94
outside class then we should use static member.
-------------------------------------------------------------------
21
Eclipse basic Program practise and short cut :-
package com.sunbeaminfo.cj06.test;
59
public class Program {
private static final double PI = 3.142;
07
private static double pow(float base, int index) {
80
float result = 1;
for( int count = 1; count <= index; ++ count )
result = result * base;
.in
return result;
ys
}
public static void main(String[] args) {
ra
}
}
w
//Eclipse shortcut
de
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
}
94
public Employee(String name, int empid, float salary) {
this.name = name;
21
this.empid = empid;
this.salary = salary;
59
}
07
public String getName() {
return name;
80
}
public void setName(String name) {
this.name = name;
.in
}
public int getEmpid() {
ys
return empid;
}
ra
this.empid = empid;
}
ith
return salary;
}
de
@Override
public String toString() {
return "Employee [name=" + name + ", empid=" + empid + ",
salary=" + salary + "]";
}
}
94
public class Program {
21
public static void main1(String[] args) {
Employee emp = new Employee();
59
System.out.println(emp); //Employee [name=null, empid=0,
salary=0.0]
07
}
public static void main2(String[] args) {
80
Employee emp = new Employee();
emp.setName("Sandeep");
.in
emp.setEmpid(33);
emp.setSalary(35000.50f);
ys
// System.out.println(emp.toString());
ra
System.out.println("Name : "+emp.getName());
System.out.println("Empid : "+emp.getEmpid());
ar
System.out.println("Salary : "+emp.getSalary());
ith
}
public static void main3(String[] args) {
w
}
}
-------------------------------------------------------------------
page. 88
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Scanner used kiya bas.
package com.sunbeaminfo.cj06.model;
94
}
public Employee(String name, int empid, float salary) {
21
this.name = name;
this.empid = empid;
59
this.salary = salary;
}
07
public String getName() {
return name;
80
}
public void setName(String name) {
this.name = name;
.in
}
public int getEmpid() {
ys
return empid;
}
ra
this.empid = empid;
}
ith
return salary;
}
de
}
@Override
public String toString() {
return "Employee [name=" + name + ", empid=" + empid + ",
salary=" + salary + "]";
}
}
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);
94
System.out.print("Enter salary : ");
emp.setSalary( sc.nextFloat() );
21
System.out.println("Name : "+emp.getName());
59
System.out.println("Empid : "+emp.getEmpid());
System.out.println("Salary : "+emp.getSalary());
07
}
}
80
//Sca ctrl+space hit enter.
-------------------------------------------------------------------
.in
AcceptRecord PrintRecord method use kiye bas:-
package com.sunbeaminfo.cj06.model;
ys
ra
this.name = name;
this.empid = empid;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getEmpid() {
return empid;
page. 90
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;
}
94
@Override
public String toString() {
21
return "Employee [name=" + name + ", empid=" + empid + ",
salary=" + salary + "]";
59
}
}
07
package com.sunbeaminfo.cj06.test;
80
import java.util.Scanner;
public class Program {
.in
public static void acceptRecord( Employee emp ) {
Scanner sc = new Scanner(System.in);
ys
emp.setName( sc.nextLine() );
System.out.print("Enter empid : ");
ar
emp.setEmpid( sc.nextInt() );
ith
}
de
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;
94
public Employee(String name, int empid, float salary) {
this.name = name;
21
this.empid = empid;
this.salary = salary;
59
}
public String getName() {
07
return name;
}
80
public void setName(String name) {
this.name = name;
.in
}
public int getEmpid() {
ys
return empid;
}
ra
}
ith
}
de
}
@Override
public String toString() {
return "Employee [name=" + name + ", empid=" + empid + ",
salary=" + salary + "]";
}
}
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
94
2. System.out => Monitor
3. System.err => Monitor ( It is error stream. It should be
21
used to display errors)
*/
59
public class Program {
07
//private static Scanner sc = new Scanner(System.in);
private static Scanner sc;
80
static {
sc = new Scanner(System.in);
}
.in
public static void acceptRecord( Employee emp ) {
System.out.print("Enter name : ");
ys
emp.setEmpid( sc.nextInt() );
System.out.print("Enter salary : ");
ith
emp.setSalary( sc.nextFloat() );
w
}
public static void printRecord( Employee emp ) {
de
System.out.println("Name : "+emp.getName());
System.out.println("Empid : "+emp.getEmpid());
co
System.out.println("Salary : "+emp.getSalary());
}
public static int menuList( ) {
System.out.println("0.Exit.");
System.out.println("1.Accept Record.");
System.out.println("2.Print Record.");
System.out.print("Enter choice : ");
return sc.nextInt();
}
public static void main(String[] args) {
int choice;
page. 93
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Employee emp = new Employee();
while( ( choice = Program.menuList( ) ) != 0 ) {
switch( choice ) {
case 1:
Program.acceptRecord(emp);
break;
case 2:
Program.printRecord(emp);
break;
}
94
}
}
21
}
-------------------------------------------------------------------
59
Correct way to write a OOPS program.
07
package com.sunbeaminfo.cj06.test;
80
public class Program {
public static void main(String[] args) {
int choice;
.in
EmployeeTest test = new EmployeeTest();
while( ( choice = EmployeeTest.menuList( ) ) != 0 ) {
ys
switch( choice ) {
ra
case 1:
test.acceptRecord();
ar
break;
ith
case 2:
test.printRecord();
w
break;
de
}
}
co
}
}
package com.sunbeaminfo.cj06.test;
import java.util.Scanner;
import com.sunbeaminfo.cj06.model.Employee;
page. 94
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
} */
94
System.out.print("Enter salary : ");
this.emp.setSalary( sc.nextFloat() );
21
}
public void printRecord( ) {
59
System.out.println("Name : "+this.emp.getName());
System.out.println("Empid : "+this.emp.getEmpid());
07
System.out.println("Salary : "+this.emp.getSalary());
}
80
public static int menuList( ) {
System.out.println("0.Exit.");
System.out.println("1.Accept Record.");
.in
System.out.println("2.Print Record.");
System.out.print("Enter choice : ");
ys
return sc.nextInt();
}
ra
}
ar
-------------------------------------------------------------------
ith
package com.sunbeaminfo.cj06.model
import lombok.AllArgsConstructor;
co
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
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
page. 96
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
• int arr[ 3 ] = { 10, 20 }; //OK : Partial Initialization
• int arr[ 3 ] = { }; //OK : Partial Initialization
21
• int arr[ 3 ] = { 10, 20, 30, 40, 50 }; //Not recommended
59
Accessing Elements Of Array in C
• If we want to access elements of array then we should use integer
07
index.
• Array index always begins with 0.
80
.in
ys
ra
• Advantage Of Array
ar
• Disadvantage Of Array
1. We can not resize array at runtime.
w
Array In Java
page. 97
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
1. do-while loop
21
2. while loop
3. for loop
59
4. for-each loop
07
• To perform operations on array we can use following classes:
1. java.util.Arrays
80
2. org.apache.commons.lang
3.ArrayUtils( download .jar file )
.in
Methods of java.util.Arrays Class
ys
ra
ar
ith
w
de
co
-------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
page. 98
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
int[ ] arr3 = null; //OK : Reference
}
21
public static void main2(String[] args) {
int arr1[ ] = null; //OK
59
arr1 = new int[ 3 ]; //OK
07
int[] arr2 = null; //OK
arr2 = new int[ 3 ]; //OK
80
int[] arr3 = new int[ 3 ]; //OK
}
.in
public static void main(String[] args) {
int size = -3;
ys
}
}
ith
w
de
co
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
94
class or interface Lclassname;
double D
21
float F
int I
59
long J
short S
07
*/
80
public class Program {
public static void main1(String[] args) {
int[] arr = new int[ 3 ]; //OK
.in
System.out.println( arr[ 0 ] ); //0
System.out.println( arr[ 1 ] ); //0
ys
}
public static void main(String[] args) {
de
page. 100
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
int[] arr5 = new int[ 3 ]; //OK
System.out.println(arr5.toString()); //[I@5c647e05
94
System.out.println(arr7.toString()); //[F@55f96302
21
double[] arr8 = new double[ 3 ]; //OK
System.out.println(arr8.toString()); //[D@3d4eac69
59
long[] arr9 = new long[ 3 ]; //OK
07
System.out.println(arr9.toString()); //[J@42a57993
}
80
} .in
ys
ra
ar
ith
w
de
co
-------------------------------------------------------------------
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;
94
if( arr != null ) {
for( int index = 0; index < 3; ++ index ) {
21
System.out.print("Enter element : ");
arr[ index ] = sc.nextInt();
59
}
}
07
}
80
private static void printRecord(int[] arr) {
if( arr != null ) {
for( int index = 0; index < 3; ++ index )
.in
System.out.println(arr[ index ]);
}
ys
} */ //isse comment nhi kiya tho code run hi nhi hota kyuki
ra
//in java 7 the new feature objects naam ka class hai usme
ith
//ye line nhi likhi tho program run honga aur element dalne
de
94
arr[ 0 ] = 10; //hardcore value
arr[ 1 ] = 20;
21
arr[ 2 ] = 30;
59
System.out.println( Arrays.toString(arr));
07
/* for( int index = 0; index < 3; ++ index )
80
System.out.println(arr[ index ]); */
/* System.out.println(arr[ 0 ]);
.in
System.out.println(arr[ 1 ]);
System.out.println(arr[ 2 ]); */
ys
ra
}
public static void main3(String[] args) {
ar
94
21
59
07
80
.in
ys
-------------------------------------------------------------------
Mavan used in eclipse like lambok jar file.
ra
-------------------------------------------------------------------
ar
Using toString()Method :-
package com.sunbeaminfo.cj06.test;
ith
import java.util.Arrays;
w
import java.util.Objects;
de
import java.util.Scanner;
co
page. 104
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
//"{ 10, 20, 30 }" is called as initializer
94
}
-------------------------------------------------------------------
21
ArrayIndexOutOfBoundsException :-
package com.sunbeaminfo.cj06.test;
59
public class Program {
public static void main1(String[] args){
07
int[ ] arr = new int[ ] { 10, 20, 30, 40, 50 };
System.out.println(arr.length); //5
element = arr[ 2 ];
ra
element = arr[ 4 ];
ith
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.
}
}
94
21
59
07
-------------------------------------------------------------------
80
Referance Copy and Instance copy:-
.in
ys
ra
ar
ith
w
de
co
page. 106
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
import java.util.Arrays;
94
System.out.println(Arrays.toString(arr2));
21
arr2 = Arrays.copyOf(arr1, arr1.length + 2);
System.out.println(Arrays.toString(arr2));
59
}
public static void main(String[] args) {
07
int[] arr1 = new int[] { 11, 22, 33, 44, 55, 66, 77, 88, 99 };
80
int[] arr2 = Arrays.copyOfRange(arr1, 2, 5);
System.out.println(Arrays.toString(arr2));
}
.in
}
ys
ra
ar
ith
w
de
co
-------------------------------------------------------------------
Sorting Arrays Elements:-
page. 107
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
import java.util.Arrays;
94
}
}
21
59
07
80
.in
ys
ra
ar
ith
w
-------------------------------------------------------------------
de
package com.sunbeaminfo.cj06.test;
import java.util.Arrays;
94
}
}
21
public static void main3(String[] args) {
int[] arr = new int[ ] { 10, 20, 30 };
59
for( int index = 0; index < arr.length; ++ index )
System.out.println(arr[ index ] );
07
}
80
public static void main(String[] args) {
int[] arr = new int[ ] { 10, 20, 30 };
.in
//foreach element in arr
for( int element : arr ) { //For each loop
ys
System.out.println(element);
ra
}
//for each loop is also called as iterator
ar
}
}
w
-------------------------------------------------------------------
de
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]
94
default value
//depends on default type of data type.
21
59
07
80
.in
ys
ra
ar
ith
-------------------------------------------------------------------
w
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;
94
Date[] arr = new Date[ 3 ]; //Array of references
for( int index = 0; index < arr.length; ++ index )
21
arr[ index ].printRecord(); //NullPointerException
}
59
public static void main3(String[] args) {
Date[] arr = new Date[ 3 ]; //Array of references
07
arr[ 0 ] = new Date( );
80
arr[ 1 ] = new Date( );
arr[ 2 ] = new Date( );
.in
for( int index = 0; index < arr.length; ++ index )
arr[ index ].printRecord(); //OK
ys
}
ra
page. 111
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
80
Arrays Of references
.in
ys
ra
ar
ith
w
de
co
-------------------------------------------------------------------
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;
94
21
@NoArgsConstructor
@AllArgsConstructor
59
@Getter @Setter
public class Employee {
07
private String name;
private int empid;
80
private float salary;
@Override
.in
public String toString() {
return String.format("%-30s%-5d%-10.2f", this.name,
ys
this.empid, this.salary);
}
ra
}
ar
ith
package com.sunbeaminfo.cj06.test;
w
import java.util.Arrays;
de
import com.sunbeaminfo.cj06.model.Employee;
co
94
Program.printRecord( arr );
}
21
}
59
07
80
.in
ys
ra
ar
ith
w
-------------------------------------------------------------------
de
package com.sunbeaminfo.cj06.test;
import java.util.Objects;
import java.util.Scanner;
page. 114
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
public class Program {
94
}
}
21
}
private static void printRecord(int[][] arr) {
59
arr = Objects.requireNonNull(arr, "arr must not be null");
for( int row = 0; row < arr.length; ++ row ) {
07
for( int col = 0; col < arr[ row ].length; ++ col ) {
80
System.out.print(arr[ row ][ col ]+" ");
}
System.out.println();
.in
}
}
ys
}
de
94
for( int col = 0; col < arr[ row ].length; ++ col ) {
System.out.print("Enter element : ");
21
arr[ row ][ col ] = sc.nextInt();
}
59
}
07
for( int row = 0; row < arr.length; ++ row ) {
80
for( int col = 0; col < arr[ row ].length; ++ col ) {
System.out.print(arr[ row ][ col ]+" ");
}
.in
System.out.println();
}
ys
}
ra
Program.acceptRecord( arr );
ith
Program.printRecord( arr );
w
}
de
}
co
-------------------------------------------------------------------
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;
94
//int[][] arr = new int[ ][ ] {
{1,2,3},{4,5,6},{7,8,9},{10,11,12}}; //OK
21
//int[][] arr = { {1,2,3},{4,5,6},{7,8,9},{10,11,12}}; //OK
//int[][] arr = new int[ 4 ][ 3 ] {
59
{1,2,3},{4,5,6},{7,8,9},{10,11,12}}; //Not OK
}
07
80
public static void main2(String[] args) {
int[][] arr = new int[ ][ ] {
{1,2,3},{4,5,6},{7,8,9},{10,11,12}}; //OK
.in
for( int row = 0; row < arr.length; ++ row ) {
ys
System.out.println();
ith
}
}
w
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]
94
//System.out.println(Arrays.deepToString(arr)); //This method
21
is designed for converting multidimensional arrays to strings.
59
for( int[] row : arr ) {
System.out.println(Arrays.toString( row ));
07
}
80
}
public static void main(String[] args) {
int[] arr = new int[ 3 ];
.in
System.out.println(arr.getClass().getSuperclass().getName());
//java.lang.Object
ys
}
ra
}
--
ar
--
ith
--
--
w
--
de
--
--
co
--
--
--
--
--
--
--
--
--
--
---------------------------------
page. 118
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Ragged Array :-
package com.sunbeaminfo.cj06.test;
import java.util.Scanner;
94
public static int[][] getArrayInstance( ) {
int[][] arr = new int[ 4 ][ ]; //Array of references
21
arr[ 0 ] = new int[ 3 ];
59
arr[ 1 ] = new int[ 2 ];
arr[ 2 ] = new int[ 4 ];
07
arr[ 3 ] = new int[ 3 ];
return arr;
80
}
private static void acceptRecord(int[][] arr) {
for( int row = 0; row < arr.length; ++ row ) {
.in
for( int col = 0; col < arr[ row ].length; ++ col ) {
ys
}
ar
}
}
ith
}
System.out.println();
}
}
public static void main1(String[] args) {
int arr1[][] = null; //OK
94
public static void main3(String[] args) {
int[][] arr = new int[ 4 ][ ]; //Array of references
21
arr[ 0 ] = new int[ 3 ];
arr[ 1 ] = new int[ 2 ];
59
arr[ 2 ] = new int[ 4 ];
arr[ 3 ] = new int[ 3 ];
07
80
for( int row = 0; row < arr.length; ++ row ) {
for( int col = 0; col < arr[ row ].length; ++ col ) {
System.out.printf("%-5d",arr[ row ][ col ]);
.in
}
System.out.println();
ys
}
ra
}
public static void main4(String[] args) {
ar
Program.acceptRecord( arr );
94
Program.printRecord( arr );
21
}
}
59
07
80
.in
ys
ra
ar
ith
w
-------------------------------------------------------------------
de
package com.sunbeaminfo.cj06.test;
co
import java.util.Arrays;
import java.util.Scanner;
page. 121
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
System.out.println(Arrays.deepToString(arr));
}
94
}
21
--
--
59
--
--
07
--
--
80
--
--
--
.in
--
--
ys
--
--
ra
--
ar
--
--
ith
--
w
---------------------------------
Argument Passing Methods :-
de
using 2 ways:
1. By value.
2. By address
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
94
int temp = a;
a = b;
21
b = temp;
59
}
public static void main(String[] args) {
07
int x = 10;
int y = 20;
80
Program.swap(x, y); //x & y are method arguments / arguments
.in
System.out.println("x : "+x); //10
ys
}
ar
//In this no swapping done only by using array we can swap Pass by
reference code is below.
ith
package com.sunbeaminfo.cj06.test;
de
parameters / parameters
int temp = arr[ 0 ];
arr[ 0 ] = arr[ 1 ];
arr[ 1 ] = temp;
}
public static void main(String[] args) {
int x = 10;
int y = 20;
94
21
59
07
80
.in
-------------------------------------------------------------------
ys
package com.sunbeaminfo.cj06.test;
import java.util.Scanner;
ra
ar
number[ 0 ] = sc.nextInt();
}
co
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 {
94
private static void add(int num1, int num2) {
int result = num1 + num2;
21
System.out.println("Result : "+result);
}
59
private static void sum(double num1, double num2) {
double result = num1 + num2;
07
System.out.println("Result : "+result);
80
}
public static void main(String[] args) {
add( 10, 20 );
.in
sum( 10.2, 20.5);
ys
}
ra
}
//Solution of above problem is next concept
ar
-------------------------------------------------------------------
ith
Method Overloading:-
Type 1:
w
package com.sunbeaminfo.cj06.test;
de
/*
- If we want to give same name to the method and if type of all
co
94
}
-------------------------------------------------------------------
21
Type 2:
package com.sunbeaminfo.cj06.test;
59
/*
- If we want to give same name to the method and if number of
07
parameters are same
then type of at least one parameter must be different.
80
*/
public class Program {
.in
//Type of all at least one parameter must be different
private static void sum(int num1, int num2) { //2 params
ys
System.out.println("Result : "+result);
}
ar
}
de
94
System.out.println("Result : "+result);
}
21
public static void main(String[] args) {
Program.sum( 10, 20.2f ); //OK
59
Program.sum( 10.1f, 20 ); //OK
}
07
}
-------------------------------------------------------------------
80
Error if we don’t follow 3 type rule :-
package com.sunbeaminfo.cj06.test;
.in
/* Only one the basis of different return type we can not give same
name to the methods,
ys
*/
ra
}
de
System.out.println("Result : "+result);
}
public static void main(String[] args) {
int result = Program.sum(10, 20);
System.out.println("Result : "+result);
Program.sum(50, 60);
//catching value from method is optional
}
}
---------------------------------------------------------------------
page. 127
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
80
----------------------------------------------------------------------
Variable Arity/Argument Method:-
.in
package com.sunbeaminfo.cj06.test;
public class Program {
ys
}
de
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
94
called as stop point )
- If we debug code without breakpoint then it is same as run.
21
- To start debugging press - F11 key
59
- For line by line debugging / step over, press F6 key
- To stop debugging press - F8 key.
07
- If we want to jump on called method / step into - press F5
key.
80
- To return from called method / step return - press F7 key
*/
public class Program {
.in
public static void main(String[] args) {
System.out.println("Debugging is started");
ys
int x = 10;
ra
Program.printRecord();
x = ++ x + x ++ - ++ x + x ++;
ar
if( x > 55 )
ith
System.out.println("Valid");
else
w
System.out.println("Invalid");
System.out.println("Debugging is about to finish");
de
}
co
----------------------------------------------------------------------
page. 129
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Enum In C/C++ Programming Language.:-
94
21
59
07
• By default, the first enumeration-constant is associated with the
80
value 0. The next enumeration-constant in the list is associated
with the value of ( constant-expression + 1 ), unless you
explicitly associate it with another value.
.in
• constant-expression must have int type and can be negative.
ys
ra
ar
ith
w
de
co
-------------------------------------------------------------------
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:-
94
21
Enum API:-
59
• Enum class is introduced in JDK 1.5.
• Following are the methods declared in java.lang.Enum class:
07
1. public final String name( )
80
2. public final int ordinal( )
3. public final Class getDeclaringClass()
4. public static > T valueOf(Class enumType, String name)
.in
• Sole constructor: o Programmers cannot invoke this constructor.
ys
type declarations.
ar
ith
w
de
co
page. 131
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Properties of enum:-
94
5. It can only contain concrete methods and no abstract methods.
21
Application of enum 1. enum is used for values that are not going
59
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
07
below is an example of it:
80
.in
ys
ra
ar
ith
w
de
co
page. 132
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
------------------------------------------------------------------
59
Example 1:-
07
// package com.sunbeaminfo.cj06.test;
import java.util.Arrays;
80
enum Color{
RED, GREEN, BLUE
.in
//RED=0, GREEN=1, BLUE=2
ys
}
/*
ra
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());
}
94
Color color = Color.RED;
System.out.println("Name : "+color.name());
21
System.out.println("Ordinal : "+color.ordinal());
59
color = Color.GREEN;
System.out.println("Name : "+color.name());
07
System.out.println("Ordinal : "+color.ordinal());
80
color = Color.BLUE;
System.out.println("Name : "+color.name());
.in
System.out.println("Ordinal : "+color.ordinal());
}
ys
ra
System.out.println("Name : "+color.name());
System.out.println("Ordinal : "+color.ordinal());
w
}
de
}
public static void main4(String[] args) {
co
import java.util.Arrays;
import java.util.Scanner;
enum Color{
RED, GREEN, BLUE
//RED=0, GREEN=1, BLUE=2
94
}
public class Program {
21
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
59
System.out.print("Enter color name(RED/GREEN/BLUE): ");
String colorName = sc.nextLine();
07
Color color = Color.valueOf(colorName.toUpperCase());
80
System.out.println(color.name()+" "+color.ordinal());
}
}
.in
/*
Enter color name(RED/GREEN/BLUE): PURPLE
ys
constant com.sunbeaminfo.cj06.test.Color.PURPLE
at java.lang.Enum.valueOf(Enum.java:238)
ar
at com.sunbeaminfo.cj06.test.Color.valueOf(Program.java:1)
ith
at com.sunbeaminfo.cj06.test.Program.main(Program.java:16)
*/
w
-------------------------------------------------------------------
de
Example 3:-
// package com.sunbeaminfo.cj06.test;
co
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);
94
}
}
21
public class Program {
59
public static void main(String[] args) {
Day day = Day.MON;
07
System.out.println(day.name()); //MON
80
System.out.println(day.ordinal()); //0
System.out.println(day.getDayNumber()); //1
System.out.println(day.toString()); //1
.in
}
}
ys
-------------------------------------------------------------------
ra
Example 4:-
ar
package com.sunbeaminfo.cj06.test;
ith
import java.util.Arrays;
w
import java.util.Scanner;
de
enum Day{
co
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;
}
}
94
System.out.println(day.getDayName()); //MonDay
System.out.println(day.toString()); //MonDay
21
}
}
59
-------------------------------------------------------------------
Example 5:-
07
package com.sunbeaminfo.cj06.test;
80
import java.util.Arrays;
import java.util.Scanner;
.in
enum Day{
ys
this.dayNumber = dayNumber;
this.dayName = dayName;
w
}
de
}
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
94
System.out.println(day.toString());
21
}
}
59
-------------------------------------------------------------------
07
Example 6:-
80
package com.sunbeaminfo.cj06.test;
import java.util.Arrays;
.in
import java.util.Scanner;
ys
enum Day{
ra
MON(1, "MonDay"),TUES("TuesDay"),WED(3);
ar
this(dayNumber, null );
de
}
private Day(String dayName) {
co
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 {
94
public static void main(String[] args) {
Day[] days = Day.values();
21
for (Day day : days) {
System.out.println(day.name()+"
59
"+day.ordinal()+" "+day.getDayName()+" "+day.getDayNumber());
}
07
80
}
}
-------------------------------------------------------------------
.in
OOPS
ys
ra
• 4 Major pillars
ith
1. Abstraction
w
2. Encapsulation
de
3. Modularity
4. Hierarchy
co
• 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
94
in system should not impact on data.
21
59
Abstraction
• It is a major pillar of oops.
07
• It is a process of getting essential things from object.
• It describes outer behaviour of the object.
80
• Abstraction focuses on some essential characteristics of object
relative to the perspective of viewer. In other words, abstraction
changes from user to user.
.in
• Using abstraction, we can achieve simplicity.
ys
-------------------------------------------------------------------
page. 140
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
import java.util.Scanner;
94
this.real = 0;
this.imag = 0;
21
}
//Code
59
public void acceptRecord( ) { //Method
Scanner sc = new Scanner(System.in);
07
System.out.print("Enter real number : ");
80
this.real = sc.nextInt();
System.out.print("Enter imag number : ");
this.imag = sc.nextInt();
.in
}
public void printRecord( ) { //Method
ys
------------------------------------------------------------------
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:
94
Abstraction focuses on the observable behaviour of an object,
whereas encapsulation focuses on the implementation that gives rise
21
to this behaviour.
59
07
80
.in
ys
ra
ar
ith
Modularity
• It is a major pillar of oops.
w
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.
94
• Typing is also called as polymorphism.
• Polymorphism is a Greek word. Polymorphism = Poly( many ) +
21
morphism( forms ).
59
• An ability of object to take multiple forms is called
polymorphism. • Using polymorphism, we can reduce maintenance of
07
the system.
• Types of polymorphism:
80
1. Compile time polymorphism
It is also calling static polymorphism / Early binding / Weak
Typing / False polymorphism.
.in
We can achieve it using:
ys
1. Method Overloading
ra
1. Method Overriding.
de
co
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:-
94
• If has-a relationship is exist between the types then we should
use association.
21
• Example 1. Car has a engine
59
2. Room has a chair
• Let us consider example of car and engine:
07
1. Car has a engine 2. Engine is part of Car.
• If object/instance is a part/component of another instance then
80
it is called as association.
• To implement association, we should declare instance of a class
as a field inside another class.
.in
ys
ra
ar
ith
w
de
co
page. 144
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
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;
94
21
@NoArgsConstructor
@AllArgsConstructor
59
@Getter @Setter
@ToString
07
public class Person {
80
private String name; //Association
private Date birthDate; //Association
private Address currentAddress; //Association
.in
}
ys
package com.sunbeaminfo.cj06.association.lib;
ra
import lombok.AllArgsConstructor;
import lombok.Getter;
ar
import lombok.NoArgsConstructor;
ith
import lombok.Setter;
import lombok.ToString;
w
de
@NoArgsConstructor
@AllArgsConstructor
co
@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
94
@ToString
public class Address {
21
private String cityName;
private String stateName;
59
private String pincode;
}
07
//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;
80
.in
import java.util.Objects;
import java.util.Scanner;
ys
import com.sunbeaminfo.cj06.association.lib.Address;
ra
import com.sunbeaminfo.cj06.association.lib.Date;
import com.sunbeaminfo.cj06.association.lib.Person;
ar
ith
System.out.print("Day : ");
birthDate.setDay(sc.nextInt());
co
System.out.print("Month : ");
birthDate.setMonth(sc.nextInt());
System.out.print("Year : ");
birthDate.setYear(sc.nextInt());
}
private static void acceptRecord(Address currentAddress) {
System.out.print("City Name : ");
currentAddress.setCityName(sc.nextLine());
System.out.print("State Name : ");
currentAddress.setStateName(sc.nextLine());
page. 147
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
System.out.print("Pincode : ");
currentAddress.setPincode(sc.nextLine());
}
private static void acceptRecord(Person person) {
System.out.print("Name : ");
person.setName(sc.nextLine());
94
Date birthDate = new Date( );
Program.acceptRecord(birthDate);
21
person.setBirthDate(birthDate);
59
//Create Address instance, accept record for it and then set
it to person instance
07
Address currentAddress = new Address();
80
sc.nextLine();
Program.acceptRecord( currentAddress );
person.setCurrentAddress(currentAddress);
.in
}
private static void printRecord(Date birthDate) {
ys
be null");
System.out.println("BirthDate : "+birthDate.getDay()+"
ar
/ "+birthDate.getMonth()+" / "+birthDate.getYear());
ith
}
private static void printRecord(Address currentAddress) {
w
currentAddress = Objects.requireNonNull(currentAddress,
de
: "+currentAddress.getCityName()+" "+currentAddress.getStateName()+
" "+currentAddress.getPincode());
}
private static void printRecord(Person person) {
person = Objects.requireNonNull(person, "Person should not be
null");
System.out.println("Name : "+person.getName());
94
public static void main2(String[] args) {
Address currentAddress = new Address();
21
Program.acceptRecord( currentAddress );
Program.printRecord( currentAddress );
59
}
public static void main1(String[] args) {
07
Date birthDate = new Date();
80
Program.acceptRecord( birthDate );
Program.printRecord( birthDate );
}
.in
}
-------------------------------------------------------------------
ys
ra
ar
ith
w
de
co
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;
94
lt.getHour();
lt.getMinute();
21
lt.getSecond();
lt.getNano(); */
59
}
public static void main3(String[] args) {
07
LocalDate ldt = LocalDate.now();
80
System.out.println("Day : "+ldt.getDayOfMonth());
System.out.println("Month : "+ldt.getMonthValue() );
System.out.println("Year : "+ldt.getYear());
.in
}
public static void main2(String[] args) {
ys
Calendar c = Calendar.getInstance();
ra
1 ) );
System.out.println("Year : "+( c.get( Calendar.YEAR ) )
w
);
de
}
public static void main1(String[] args) {
co
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
page. 151
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
-------------------------------------------------------------------
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;
94
}
public class Program {
21
public static void main1(String[] args) {
Employee emp = new Employee();
59
emp.setName("Sandeep");
emp.setEmpid(33);
07
emp.setSalary(45000.50f);
80
System.out.println(emp.toString());
}
}
.in
-------------------------------------------------------------------
package com.sunbeaminfo.cj06.date.test;
ys
import lombok.Builder;
ra
import lombok.Setter;
import lombok.ToString;
ar
@Builder @ToString
ith
class Employee{
private String name;
w
94
21
59
07
• If we want to implement inheritance then we should use extends
80
.in
keyword.
• In Java, parent class is called as super class and child class is
ys
-------------------------------------------------------------------
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;
94
this.age = age;
}
21
public void showRecord( ) {
System.out.println("Name : "+this.name);
59
System.out.println("Age : "+this.age);
}
07
}
80
public class Program {
public static void main1(String[] args) {
//Person p1 = new Person( );
.in
Person p1 = new Person( "Sandeep", 38 );
p1.showRecord();
ys
}
ra
p1.name = "Sandeep";
ith
p1.age = 38;
System.out.println("Name : "+p1.name);
w
System.out.println("Age : "+p1.age);
de
}
}
co
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;
94
this.empid = empid;
this.salary = salary;
21
}
public void displayRecord( ) {
59
System.out.println("Name : "+this.name);
System.out.println("Age : "+this.age);
07
System.out.println("Empid : "+this.empid);
80
System.out.println("Salary : "+this.salary);
}
}
.in
public class Program {
public static void main(String[] args) {
ys
emp.displayRecord();
}
ar
emp.age = 38;
de
emp.empid = 33;
emp.salary = 45000.50f;
co
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
--------------------------------------------------------------------------------------------------------------------------
94
-------------------------------------------------------------------
21
Example 3 :- very very important according concept point of view.
59
// package com.sunbeaminfo.cj06.inheritance.test;
07
import java.sql.PseudoColumnUsage;
80
class Person{ //Parent Class / Super Class
//Fields / Properties
.in
String name;
int age;
ys
public Person( ) {
//super( ); //OK
ra
}
ith
//in java except constructor all the member are inherite into
subclass
w
this.age = age;
}
//Method / Behavior
public void showRecord( ) {
System.out.println("Name : "+this.name);
System.out.println("Age : "+this.age);
}
static void test(){
System.out.println("Super class method");
}
page. 157
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
}
class Employee extends Person{ // Child Class / Sub Class
int empid;
float salary;
public Employee() {
super( ); //
System.out.println("public Employee()");
}
public Employee( String name, int age, int empid, float salary ) {
94
//super statement must be in first statement.
super(name, age ); //Super Statement
21
System.out.println("public Employee( String name, int age, int
empid, float salary )");
59
this.empid = empid;
this.salary = salary;
07
}
80
/*public void showRecord( ) {
System.out.println("Name : "+this.name);
System.out.println("Age : "+this.age);
.in
}*/
public void displayRecord( ) {
ys
this.showRecord();
ra
System.out.println("Empid : "+this.empid);
System.out.println("Salary : "+this.salary);
ar
}
ith
}
public class Program {
w
person.age = 38;
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);
94
System.out.println("Empid : "+emp.empid);
System.out.println("Salary : "+emp.salary);
21
}
59
public static void main4(String[] args) {
//Employee emp = new Employee("Sandeep", 38, 33, 45000.50f );
07
Employee emp = new Employee();
80
emp.showRecord();
emp.displayRecord();
}
.in
public static void main5(String[] args) {
//Employee emp = new Employee("Sandeep", 38, 33, 45000.50f );
ys
emp.displayRecord();
}
ar
}
de
94
called hua by default pr muje parametrized called krna tha tho
iske liye
21
solution hai .....*/
59
/* Then we should use super statement */
07
}
80
public static void main8(String[] args) {
Person person = new Person();
person.name = "Sandeep"; //OK
.in
person.age = 38; //OK
//person.empid = 33; //NOT OK
ys
System.out.println("Name : "+person.name);
ith
System.out.println("Age : "+person.age);
}
w
}
de
• If we create instance of sub class then all the non static fields
co
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.
94
• We can call/invoke, non static method of super class on instance
21
of sub class. In other words, non static method inherit into sub
59
class.
07
• We can call static method of super class on sub class. In other
words, static method inherit into sub class.
80
• Except constructor, all the methods of super class inherit into
sub class.
.in
ys
then JVM first give call to the super class constructor and then
ar
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
94
public class Program {
public static void main(String[] args) {
21
Employee.Date dt1 = new Employee().new Date();
dt1.printRecord();
59
//super class ka nested class sub class mai inherite ho jata
jai.
07
}
80
public static void main1(String[] args) {
Person.Date dt1 = new Person().new Date();
dt1.printRecord();
.in
}
}
ys
ra
--------------------------------------------------------------------
Ex:5
ar
package com.sunbeaminfo.cj06.inheritance.test;
ith
class Person{
w
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;
}
94
public void displayRecord( ) {
this.showRecord();
21
System.out.println("Empid : "+this.empid);
System.out.println("Salary : "+this.salary);
59
}
}
07
public class Program {
80
public static void main1(String[] args) {
Person p = new Person( );
p.setName("Sandeep");
.in
p.setAge(38);
p.showRecord();
ys
}
ra
emp.setName("Sandeep");
ith
emp.setAge(38);
emp.setEmpid(33);
w
emp.setSalary(45000.50f);
de
emp.displayRecord();
}
co
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.");
}
94
class Class2 extends Class1 {
21
private int age;
59
public void setAge(int age) {
this.age = age;
07
System.out.println("The age has been set successfully.");
80
}
}
de
}
co
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
94
}
}
21
Conclusion
59
Yes, a subclass can indirectly access the private members of a
superclass. A subclass can't directly access the private members of
07
a superclass.
80
All the public, private and protected members (i.e. all the fields
and methods) of a superclass are inherited by a subclass but the
.in
subclass can directly access only the public and protected members
of the superclass. If an inherited member from a superclass gives
ys
superclass.
-------------------------------------------------------------------
ar
ith
Ex.7
w
package p1;
de
public class A {
private int num1 = 10;
co
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
94
//System.out.println("Num2 : "+this.num2); //OK
//System.out.println("Num3 : "+this.num3); //OK
21
//System.out.println("Num4 : "+this.num4); //OK
}
59
}
07
package p2;
80
import p1.A;
public class C extends A{
public void printRecord( ) {
.in
//System.out.println("Num1 : "+this.num1); //The field
A.num1 is not visible
ys
}
}
w
de
package p2;
import p1.A;
co
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;
94
//c.printRecord();
21
D d = new D( );
d.printRecord();
59
}
public static void main2(String[] args) {
07
//Private
80
/* A a = new A( );
System.out.println("Num1 : "+a.num1);*/ //The field
A.num1 is not visible
.in
// Default/package level private
ys
/* A a = new A( );
ar
/* A a = new A( );
de
94
---------------------------------------------------------------------
21
Ex.8
59
package com.sunbeam.cj06.inheritance.parent;
07
public class Person{
80
private String name;
private int age;
.in
public Person( ) {
}
ys
this.age = age;
ar
}
ith
System.out.println("Age : "+this.age);
de
}
}
co
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() {
}
94
public Employee(String name, int age, int empid, float salary) {
super(name, age);
21
this.empid = empid;
this.salary = salary;
59
}
//super class aur sub class method ka naam same ho tho
07
//super keyword pr method call karna pdta hai
80
public void printRecord( ) {
super.printRecord();
System.out.println("Empid : "+this.empid);
.in
System.out.println("Salary : "+this.salary);
}
ys
}
ra
}
de
}
----------------------------------------------------------------------
co
Ex.9
package com.sunbeaminfo.cj06.inheritance.test;
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;
94
}
public int getAge() {
21
return age;
}
59
public void setAge(int age) {
this.age = age;
07
}
80
}
class Employee extends Person{
private int empid;
.in
private float salary;
public Employee() {
ys
}
ra
this.empid = empid;
ith
this.salary = salary;
}
w
return empid;
}
co
94
}
public void acceptEmployeeRecord( ) {
21
System.out.print("Name : ");
emp.setName(sc.nextLine());
59
System.out.print("Age : ");
emp.setAge(sc.nextInt());
07
System.out.print("Empid : ");
80
emp.setEmpid(sc.nextInt());
System.out.print("Salary : ");
emp.setSalary(sc.nextFloat());
.in
}
public void printPersonRecord( ) {
ys
System.out.println("Name : "+person.getName());
ra
System.out.println("Age : "+person.getAge());
}
ar
System.out.println("Name : "+emp.getName());
System.out.println("Age : "+emp.getAge());
w
System.out.println("Empid : "+emp.getEmpid());
de
System.out.println("Salary : "+emp.getSalary());
}
co
}
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;
94
public Person() {
}
21
public Person(String name, int age) {
this.name = name;
59
this.age = age;
}
07
public String getName() {
80
return name;
}
public void setName(String name) {
.in
this.name = name;
}
ys
return age;
}
ar
this.age = age;
}
w
}
de
94
}
}
21
class InheritanceTest{
private static Scanner sc = new Scanner(System.in);
59
private Person person; //null
public void setPerson(Person person) {
07
this.person = person;
80
}
public void acceptRecord( ) {
if( this.person != null ) {
.in
//TODO
}
ys
}
ra
//TODO
ith
}
}
w
}
de
import java.awt.image.ReplicateScaleFilter;
import java.util.Scanner;
class Person{
private String name;
94
private int age;
public Person() {
21
}
public Person(String name, int age) {
59
this.name = name;
this.age = age;
07
}
80
public void showRecord( ) {
System.out.println("Name : "+this.name);
System.out.println("Age : "+this.age);
.in
}
public void printRecord( ) {
ys
System.out.println("Name : "+this.name);
ra
System.out.println("Age : "+this.age);
}
ar
}
ith
public Employee() {
}
co
94
super class.
21
Hence using super class instance, we can access members of super class
only.
59
*/
public static void main1(String[] args) {
07
Person person = new Person();
80
person.showRecord();//OK
//person.displayRecord( ); //Not OK
}
.in
/* • During inheritance, members of super class, inherit into sub
class. Hence
ys
using sub class instance, we can access members of super class as well
ra
as sub
class */
ar
emp.displayRecord(); //OK
de
}
public static void main3(String[] args) {
co
94
}
public static void main5(String[] args) {
21
Person p1 = null; //OK
59
Person p2 = new Person(); //OK
07
Person p3 = new Employee(); //OK: Upcasting
80
//Super class reference can contain reference of instance of
sub class.
.in
Employee emp1 = null; //OK
ys
super class.
}
w
}
de
• If name of super class and sub class method is same and if we try
co
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
page. 177
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
float salary;
21
}
public class Program {
59
public static void main1(String[] args) {
07
//Super class ke instance ke through sirf super class
// ke member hi access ho rahe hai
80
Person p = new Person();
p.name = "Sandeep"; //OK
.in
p.age = 38; //OK
//p.empid = 33; //Not OK
ys
}
de
subclass
// ke member ko bhi access kr sakte hai
Employee emp = new Employee();
emp.name = "Sandeep"; //OK
emp.age = 38; //OK
emp.empid = 33; //OK
emp.salary = 45000.50f; //OK
94
//p.empid = 33; //Not OK
//p.salary = 45000.50f; //NOT OK
21
Employee emp = (Employee) p; //Downcasting
59
emp.empid = 33;
emp.salary = 45000.50f;
07
80
System.out.println("Name : "+p.name); //OK
System.out.println("Age : "+p.age); //OK
//System.out.println("Empid : "+p.empid); //NOT OK
.in
//System.out.println("Salary : "+p.salary); //NOT OK
System.out.println("Empid : "+emp.empid); //OK
ys
}
public static void main4(String[] args) {
ar
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
94
• In case of upcasting, using super class reference variable, we
21
can access:
1. Fields of super class 2. Methods of super class 3. overridden
59
methods of sub class
07
• In case of upcasting, using super class reference variable, we
can not access:
80
1. fields of sub class 2. Non overridden methods of sub class.
• If we want to access fields and non overridden methods of sub
.in
class then we should do down casting.
ys
ra
ar
ith
w
de
co
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.
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
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( ) {
94
System.out.println("A.f2");
}
21
}
class B extends A{ //Sub Class
59
public void f2( ) {
System.out.println("B.f2");
07
}
80
public void f3( ) {
System.out.println("B.f3");
}
.in
}
public class Program {
ys
A a = new B( ); //Upcastng
a.f2(); //OK : B.f2 => Dynamic Method Dispatch
ar
}
ith
//a.f3(); //Not OK
co
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");
94
}
}
21
public class Program {
public static void main(String[] args) {
59
A a = new B( );
a.f2();//OK : B.f2
07
//a.f3( ); //NOT OK
80
}
}
----------------------------------------------------------------------
.in
Overriding:-
• Process of redefining method of super class inside sub class is
ys
be wider.
2. Return type of sub class method should be same or it should be
sub type. In other words, it should be covariant.
3. Name of the method, number of parameters and type of parameters
inside sub class method must be same.
4. Checked exception list inside sub class method should be same or
it should be sub set.
• Override is annotation declared in java.lang package.
• We can use this annotation on method only.
• It helps developer to override method inside sub class.
page. 183
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
-
-
-
-
-
-
-
-
94
-
-
21
-
-
59
-
-
07
-
80
-
-
--------------------------------------------------
.in
package com.sunbeaminfo.cjo6.inheritance.test;
ys
ra
abstract class A{
public abstract void f1( );
ar
94
}
public class Program {
21
public static void main(String[] args) {
A a = null;
59
a = new B( );
07
a.f1();
80
a = new C( );
a.f2();
.in
a = new D( );
ys
a.f3();
ra
}
ar
}
ith
-------------------------------------------------------------------
package com.sunbeaminfo.cjo6.inheritance.test;
w
de
abstract class A{
private int num1;
co
94
System.out.println("Num3 : "+this.num3);
}
21
}
public class Program {
59
public static void main(String[] args) {
A a = new B( 10, 20, 30 );
07
a.print();
80
}
}
.in
-------------------------------------------------------------------
ys
package com.sunbeaminfo.cjo6.inheritance.test;
ra
class Account{
private String name;
ar
public Account() {
de
}
public Account(String name, int number, String type, float
co
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() {
94
return type;
}
21
public void setType(String type) {
this.type = type;
59
}
public float getBalance() {
07
return balance;
80
}
public void setBalance(float balance) {
this.balance = balance;
.in
}
@Override
ys
}
ith
}
w
94
42000.50f);
this.accounts[ 2 ] = new Account("Rajiv",789,"Loan",
21
59000.50f);
}
59
//private EmailService service = new EmailService();
//private SMSService service = new SMSService();
07
80
private Service service; //null
public void setService(Service service) {
this.service = service;
.in
}
public boolean deposit( int number, float amount ){
ys
}
return true;
co
}
}
return false;
}
}
public class Program {
public static void main(String[] args) {
Bank bank = new Bank();
//bank.setService(new SMSService());
//bank.setService(new EmailService());
page. 188
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
}
}
----------------------------------------------------------------------
package com.sunbeaminfo.cjo6.inheritance.test;
94
class Rectangle{
21
private float area;
private float length;
59
private float breadth;
public Rectangle() {
07
}
80
public void setLength(float length) {
this.length = length;
}
.in
public void setBreadth(float breadth) {
this.breadth = breadth;
ys
}
ra
}
ith
}
de
}
class Circle{
co
94
System.out.println("Area : "+c.getArea());
}
21
public static void main1(String[] args) {
Rectangle rect = new Rectangle();
59
rect.setLength(10);
rect.setBreadth(20);
07
rect.calculateArea();
80
System.out.println("Area : "+rect.getArea());
}
}
.in
---------------------------------------------------------------------
ys
ra
package com.sunbeaminfo.cjo6.inheritance.test;
class Shape{
ar
public Shape() {
}
w
return this.area;
}
co
}
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() {
94
}
public void setRadius(float radius) {
21
this.radius = radius;
}
59
public void calculateArea( ) {
this.area = (float) (Math.PI * Math.pow(this.radius, 2));
07
}
80
}
public class Program {
public static void main1(String[] args) {
.in
Circle c = new Circle();
c.setRadius(10);
ys
c.calculateArea();
ra
System.out.println("Area : "+c.getArea());
}
ar
rect.setBreadth(20);
de
rect.calculateArea();
System.out.println("Area : "+rect.getArea());
co
}
}
----------------------------------------------------------------------
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() {
94
}
public void setLength(float length) {
21
this.length = length;
}
59
public void setBreadth(float breadth) {
this.breadth = breadth;
07
}
80
public void calculateArea( ) {
super.area = this.length * this.breadth;
}
.in
}
class Circle extends Shape{
ys
public Circle() {
}
ar
this.radius = radius;
}
w
}
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());
}
94
public static int menuList( ) {
System.out.println("0.Exit");
21
System.out.println("1.Rectangle");
System.out.println("2.Circle");
59
System.out.print("Enter choice : ");
return sc.nextInt();
07
}
80
public static void main(String[] args) {
int choice;
while( ( choice = Program.menuList( ) ) != 0 ) {
.in
switch( choice ) {
case 1:
ys
Program.acceptRecord( rect );
rect.calculateArea();
ar
Program.printRecord( rect );
ith
break;
case 2:
w
Program.acceptRecord( c );
c.calculateArea();
co
Program.printRecord( c );
break;
}
}
}
}
----------------------------------------------------------------------
package com.sunbeaminfo.cjo6.inheritance.test;
import java.util.Scanner;
page. 193
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
}
class Rectangle extends Shape{
21
private float length;
private float breadth;
59
public Rectangle() {
}
07
public void setLength(float length) {
80
this.length = length;
}
public void setBreadth(float breadth) {
.in
this.breadth = breadth;
}
ys
@Override
ra
}
ith
}
class Circle extends Shape{
w
public Circle() {
}
co
94
System.out.print("Radius : ");
c.setRadius(sc.nextFloat());
21
}
}
59
private static void printRecord(Shape shape) {
System.out.println("Area : "+shape.getArea());
07
}
80
public static int menuList( ) {
System.out.println("0.Exit");
System.out.println("1.Rectangle");
.in
System.out.println("2.Circle");
System.out.print("Enter choice : ");
ys
return sc.nextInt();
ra
}
public static void main(String[] args) {
ar
int choice;
ith
switch( choice ) {
de
case 1:
shape = new Rectangle(); //Upcasting
co
break;
case 2:
shape = new Circle(); //Upcasting
break;
}
if( shape != null ) {
Program.acceptRecord( shape );
shape.calculateArea(); //Dynamic Method Dispatch
Program.printRecord( shape );
}
page. 195
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
}
}
}
---------------------------------------------------------------------
package com.sunbeaminfo.cjo6.inheritance.test;
import java.util.Scanner;
94
abstract class Shape{
protected float area;
21
public Shape() {
}
59
public abstract void calculateArea( );
public final float getArea() {
07
return this.area;
80
}
}
class Rectangle extends Shape{
.in
private float length;
private float breadth;
ys
public Rectangle() {
ra
}
public void setLength(float length) {
ar
this.length = length;
ith
}
public void setBreadth(float breadth) {
w
this.breadth = breadth;
de
}
@Override
co
94
this.shape = shape;
}
21
private static Scanner sc = new Scanner(System.in);
public void acceptRecord( ) {
59
if( this.shape != null ) {
if( shape instanceof Rectangle ) {
07
Rectangle rect = (Rectangle) shape; //Downcasting
80
System.out.print("Length : ");
rect.setLength(sc.nextFloat());
System.out.print("Breadth : ");
.in
rect.setBreadth(sc.nextFloat());
}else {
ys
System.out.print("Radius : ");
c.setRadius(sc.nextFloat());
ar
}
ith
this.shape.calculateArea();//DMD
}
w
}
de
System.out.println("Area : "+shape.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();
}
page. 197
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
}
public class Program {
public static void main(String[] args) {
int choice;
ShapeTest test = new ShapeTest();
while( ( choice = ShapeTest.menuList( ) ) != 0 ) {
switch( choice ) {
case 1:
test.setShape( new Rectangle());
94
break;
case 2:
21
test.setShape(new Circle());
break;
59
}
test.acceptRecord();
07
test.printRecord();
80
}
}
}
.in
----------------------------------------------------------------------
ys
package com.sunbeaminfo.cjo6.inheritance.test;
ra
import java.util.Scanner;
ar
ith
public Shape() {
de
}
public abstract void calculateArea( );
co
94
}
class Circle extends Shape{
21
private float radius;
public Circle() {
59
}
public void setRadius(float radius) {
07
this.radius = radius;
80
}
@Override
public void calculateArea( ) {
.in
super.area = (float) (Math.PI * Math.pow(this.radius, 2));
}
ys
}
ra
class ShapeFactory{
public static Shape getInstance( int choice ) {
ar
switch( choice ) {
case 1:
w
break;
case 2:
co
94
rect.setBreadth(sc.nextFloat());
}else {
21
Circle c = (Circle) shape; //Downcasting
System.out.print("Radius : ");
59
c.setRadius(sc.nextFloat());
}
07
this.shape.calculateArea();//DMD
80
}
}
public void printRecord( ) {
.in
if( this.shape != null ) {
System.out.println("Area : "+shape.getArea());
ys
}
ra
}
public static int menuList( ) {
ar
System.out.println("0.Exit");
ith
System.out.println("1.Rectangle");
System.out.println("2.Circle");
w
return sc.nextInt();
}
co
}
public class Program {
public static void main(String[] args) {
int choice;
ShapeTest test = new ShapeTest();
while( ( choice = ShapeTest.menuList( ) ) != 0 ) {
Shape shape = ShapeFactory.getInstance(choice);
test.setShape(shape);
test.acceptRecord();
test.printRecord();
page. 200
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
}
}
}
---------------------------------------------------------------------
package com.sunbeaminfo.cjo6.inheritance.test;
/*
- If we want to compare state of instances then we should use
equals method.
94
- equals is non final method of java.lang.Object class.
- If we do not define equals method inside class then its super
21
class's equals method gets called.
- If any class do not contain equals method then Object class's
59
equals method gets called.
- Consider code of Object class's equals method:
07
public boolean equals(Object obj) {
80
return (this == obj);
}
- equals method of Object class compares state of references.
.in
- If we want to compare state of instances of non primitive type
then we should override equals method inside class.
ys
*/
ra
class Employee{
private String name;
ar
this.name = name;
de
this.empid = empid;
this.salary = salary;
co
}
}
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
94
System.out.println("Equal");
else
21
System.out.println("Not Equal"); */
59
//In Java, primitive types are not classes.
//Hence we can not call equals method on variable of primitive
07
type.
80
}
public static void main3(String[] args) {
Employee emp1 = new Employee("Sandeep", 33, 45000.50f );
.in
Employee emp2 = new Employee("Sandeep", 33, 45000.50f );
if( emp1 == emp2 )
ys
System.out.println("Equal");
ra
else
System.out.println("Not Equal");
ar
ith
types.
de
94
public Employee(String name, int empid, float salary) {
this.name = name;
21
this.empid = empid;
this.salary = salary;
59
}
07
//Employee this = emp1;
80
//Object obj = emp2; //Upcasting
@Override
public boolean equals(Object obj) {
.in
if( obj != null ) {
Employee other = (Employee) obj; //Downcasting
ys
return true;
}
ar
return false;
ith
}
}
w
page. 203
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------
package com.sunbeaminfo.cjo6.inheritance.test;
94
System.out.println("Inside print method");
}
21
@Override
public void close() throws Exception {
59
System.out.println("Closing resource");
}
07
}
80
public class Program {
public static void main(String[] args) {
Test t = null;
.in
t = new Test( ); //instance => Resource
ys
ra
t.print();
}
ar
}
ith
w
de
co
---------------------------------------------------------------------
EXCEPTION HANDLING
page. 204
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
80
.in
-Hierarchy of Exception Handling:-
ys
ra
ar
ith
w
de
co
-------------------------------------------------------------------
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;
94
public class Program {
public static void main(String[] args) {
21
System.out.println("Opening resource");
Scanner sc = null;
59
sc = new Scanner(System.in);
07
System.out.print("Num1 : ");
80
int num1 = sc.nextInt();
System.out.print("Num2 : ");
int num2 = sc.nextInt();
.in
try {
ys
System.out.println("Result : "+result);
}catch(ArithmeticException ex ) {
ar
//System.out.println(ex.getMessage());
ith
System.out.println("Closing resource");
de
sc.close();
}
co
}
--------------------------------------------------------------
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;
94
System.out.println("Result : "+result);
}catch(ArithmeticException ex ) {
21
//System.out.println(ex.getMessage());
//ex.printStackTrace();
59
System.out.println("ArithmeticException");
}catch( InputMismatchException ex ) {
07
System.out.println("InputMismatchException");
80
}
System.out.println("Closing resource");
sc.close();
.in
}
}
ys
ra
------------------------------------------------------------
ar
package com.sunbeaminfo.cj06.exception.test;
ith
import java.util.InputMismatchException;
w
import java.util.Scanner;
de
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();
}
}
-----------------------------------------------------------------
94
21
59
07
80
.in
ys
-----------------------------------------------------------------
ra
package com.sunbeaminfo.cj06.exception.test;
ar
import java.util.Scanner;
ith
System.out.println("Opening resource");
Scanner sc = null;
co
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( Exception ex ) { //Generic Catch Block
System.out.println(ex.getClass().getSimpleName());
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;
94
public class Program {
public static void main(String[] args) {
21
System.out.println("Opening resource");
Scanner sc = null;
59
try {
07
sc = new Scanner(System.in);
System.out.print("Num1 : ");
80
int num1 = sc.nextInt();
System.out.print("Num2 : ");
int num2 = sc.nextInt();
.in
int result = num1 / num2;
ys
System.out.println("Result : "+result);
}catch( ArithmeticException ex ) {
ra
System.out.println("ArithmeticException");
ar
}catch( RuntimeException ex ) {
System.out.println("RuntimeException");
ith
System.out.println("Exception");
de
}
System.out.println("Closing resource");
co
sc.close();
}
}
-------------------------------------------------------------------
page. 209
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
------------------------------------------------------------------
80
.in
package com.sunbeaminfo.cj06.exception.test;
ys
import java.util.Scanner;
ra
System.out.println("Opening resource");
Scanner sc = null;
w
try {
de
sc = new Scanner(System.in);
System.out.print("Num1 : ");
co
94
package com.sunbeaminfo.cj06.exception.test;
import java.util.Scanner;
21
public class Program {
59
public static void main(String[] args) {
07
System.out.println("Opening resource");
Scanner sc = null;
80
try {
sc = new Scanner(System.in);
System.out.print("Num1 : ");
.in
int num1 = sc.nextInt();
ys
System.out.print("Num2 : ");
int num2 = sc.nextInt();
ra
if( num2 == 0 )
ar
System.out.println("Result : "+result);
de
ex.printStackTrace();
}
System.out.println("Closing resource");
sc.close();
}
}
------------------------------------------------------------------
// 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 : ");
94
int num2 = sc.nextInt();
if( num2 == 0 )
21
//throw 0; //No exception of type int can be thrown;
an exception type must be a subclass of Throwable
59
//throw new Program(); //No exception of type Program
can be thrown; an exception type must be a subclass of Throwable
07
throw new ArithmeticException("Divide by zero
80
exception");
int result = num1 / num2;
System.out.println("Result : "+result);
.in
}catch( Exception ex ) { //Generic Catch Block
ys
ex.printStackTrace();
ra
}
System.out.println("Closing resource");
ar
sc.close();
ith
}
}
w
-------------------------------------------------------------------
de
package com.sunbeaminfo.cj06.exception.test;
co
import java.util.Scanner;
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
94
exception");
int result = num1 / num2;
21
System.out.println("Result : "+result);
59
}catch( ArithmeticException ex ) {
System.out.println("Inside catch block");
07
ex.printStackTrace();
80
}finally {
System.out.println("Inside finally block");
System.out.println("Closing resource");
.in
sc.close();
}
ys
}
ra
}
-------------------------------------------------------------------
ar
ith
package com.sunbeaminfo.cj06.exception.test;
w
import java.util.Scanner;
de
94
import java.util.Scanner;
21
public class Program {
public static void main(String[] args) {
59
try( Scanner sc1 = new Scanner(System.in);
07
Scanner sc2 = new Scanner(System.in);
Scanner sc3 = new Scanner(System.in); ){ //Try-
80
With-Resource
//TODO
}catch( ArithmeticException ex ) {
.in
ex.printStackTrace();
ys
}
}
ra
}
ar
-------------------------------------------------------------------
ith
w
de
co
-------------------------------------------------------------------
page. 214
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.exception.test;
import java.util.Iterator;
import java.util.Scanner;
94
System.out.println("Count : "+count);
Thread.sleep(350);
21
}
} catch (InterruptedException e) {
59
e.printStackTrace();
}
07
}
80
public static void displayRecord( ) throws InterruptedException {
for( int count = 1; count <= 10; ++ count ) {
System.out.println("Count : "+count);
.in
Thread.sleep(350);
}
ys
}
ra
NumberFormatException
ith
}
public static void main2(String[] args) {
//Program.showRecord();
try {
Program.displayRecord();
} catch (InterruptedException e) {
page. 215
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
e.printStackTrace();
}
}
}
94
21
59
07
-------------------------------------------------------------------
80
.in
ys
ra
ar
ith
w
de
co
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);
}
94
}
21
@SuppressWarnings("serial")
class StackOverflowflowException extends
59
RuntimeException{ //UnChecked Exception
public StackOverflowflowException(String message) {
07
super(message);
}
80
} */
.in
@SuppressWarnings("serial")
class StackUnderflowException extends Exception{ //Checked
ys
Exception
ra
}
ith
}
@SuppressWarnings("serial")
w
Exception
public StackOverflowflowException(String message) {
co
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);
94
}
}
21
@SuppressWarnings("serial")
class StackOverflowException extends Exception{ //Checked Exception
59
public StackOverflowException(String message) {
super(message);
07
}
80
}
class Stack{
.in
private int top = -1;
private int[] arr;
ys
public Stack( ) {
ra
this( 5 );
}
ar
94
public class Program {
static Scanner sc = new Scanner(System.in);
21
private static void acceptRecord(int[] element) {
System.out.print("Enter element : ");
59
element[ 0 ] = sc.nextInt();
}
07
private static void printRecord(int[] element) {
80
System.out.println("Removed element : "+element[ 0 ]);
}
public static int menuList( ) {
.in
System.out.println("0.Exit");
System.out.println("1.Push");
ys
System.out.println("2.Pop");
ra
}
ith
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());
}
}
}
}
94
----------------------------------------------------------------------
Day- 14
21
59
package com.sunbeaminfo.cj06.test;
07
import java.util.Date;
80
//T : Type
.in
//E : Element
ys
//N : Number
ra
//K : Key
ar
ith
//V : Value
w
b1.setObject(new Date());
94
System.out.println(date.toString());
21
}
public static void main2(String[] args) {
59
//Box<Date> b1 = new Box<Date>();
07
Box<Date> b1 = new Box<>(); //OK
80
//Box<> b1 = new Box<Date>(); //Not OK
.in
//Box<Object> b1 = new Box<Date>(); //Not OK
ys
b1.setObject(new Date());
ar
ith
System.out.println(date.toString());
de
}
co
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;
94
private V value;
public void put( K key, V value ) {
21
this.key = key;
this.value = value;
59
}
07
public K getKey() {
return key;
80
}
public V getValue() {
return value;
.in
}
ys
}
public class Program {
ra
System.out.println("Key : "+p.getKey());
w
System.out.println("Value : "+p.getValue());
de
}
}
co
-------------------------------------------------------------------
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;
94
}
}
21
public class Program {
public static void main1(String[] args) {
59
Box1<Number> b1 = new Box1< >( ); //OK
07
Box1<Boolean> b2 = new Box1< >( ); //OK
80
Box1<Character> b3 = new Box1< >( ); //OK
.in
Box1<Integer> b4 = new Box1< >( ); //OK
ys
page. 223
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Box<Date> b7 = new Box< >( ); //Not OK
}
}
-------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
import java.util.ArrayList;
94
private static ArrayList<Integer> getIntegerList( ) {
ArrayList<Integer> list = new ArrayList< >( );
21
list.add(10);
list.add(20);
59
list.add(30);
07
return list;
}
80
private static void printIntegerList( ArrayList<Integer> list ) {
for( Integer element : list )
System.out.println(element );
.in
}
ys
Program.printIntegerList( list );
ar
}
ith
list.add(10);
list.add(20);
co
list.add(30);
for( Integer element : list )
System.out.println(element );
}
}
-------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
import java.util.ArrayList;
94
list.add(10.1);
list.add(20.2);
21
list.add(30.3);
return list;
59
}
private static ArrayList<String> getStringList( ) {
07
ArrayList<String> list = new ArrayList< >( );
80
list.add("Java");
list.add("Python");
list.add("Ruby");
.in
return list;
}
ys
}
ith
System.out.println(element );
de
}
private static void printStringList( ArrayList<String> list ) {
co
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:
94
1. Unbounded wild card
2. Upper bounded wild card
21
3. Lower bounded wilds card.
59
package com.sunbeaminfo.cj06.test;
07
import java.util.ArrayList;
public class Program {
80
private static ArrayList<Integer> getIntegerList( ) {
ArrayList<Integer> list = new ArrayList< >( );
.in
list.add(10);
list.add(20);
ys
list.add(30);
return list;
ra
}
ar
list.add(20.2);
de
list.add(30.3);
return list;
co
}
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 );
94
ArrayList<String> stringList = Program.getStringList();
Program.printList( stringList );
21
}
59
}
----------------------------------------------------------------------------------------------------------------------
07
package com.sunbeaminfo.cj06.test;
80
import java.util.ArrayList;
.in
public class Program {
private static ArrayList<Integer> getIntegerList( ) {
ys
list.add(10);
list.add(20);
ar
list.add(30);
ith
return list;
}
w
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;
page. 227
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
}
//Upper bounded Wild Card
private static void printList( ArrayList<? extends Number > list )
{
System.out.println(list);
}
public static void main(String[] args) {
ArrayList<Integer> integerList = Program.getIntegerList( );
Program.printList( integerList ); //OK
94
ArrayList<Double> doubleList = Program.getDoubleList();
21
Program.printList( doubleList ); //OK
59
ArrayList<String> stringList = Program.getStringList();
Program.printList( stringList ); //Not OK
07
80
}
}
-------------------------------------------------------------------
.in
package com.sunbeaminfo.cj06.test;
ys
import java.util.ArrayList;
ra
import java.util.Date;
ar
list.add(true);
de
list.add('A');
list.add("Sandeep");
co
list.add(123);
list.add(new Date());
return list;
}
private static ArrayList<Number> getNumberList( ) {
ArrayList<Number> list = new ArrayList< >( );
list.add( new Integer(123) );
list.add( new Float(123.45f) );
list.add( new Double(123.45d) );
return list;
page. 228
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
}
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( ) {
94
ArrayList<Double> list = new ArrayList< >( );
list.add(10.1);
21
list.add(20.2);
list.add(30.3);
59
return list;
}
07
private static ArrayList<String> getStringList( ) {
80
ArrayList<String> list = new ArrayList< >( );
list.add("Java");
list.add("Python");
.in
list.add("Ruby");
return list;
ys
}
ra
{
ith
System.out.println(list);
}
w
page. 229
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
ArrayList<Object> objectList = Program.getObjectList();
Program.printList(objectList); //OK
}
}
-------------------------------------------------------------------
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
page. 230
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
80
-------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
.in
import java.util.Date;
public class Program {
ys
//Generic Method
ra
}
ith
Program.print( 'A' );
de
Program.print( 123 );
Program.print( 3.142 );
co
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);
} */
94
Program.print( 123 ); //OK
Program.print( 3.142 ); //OK
21
//Program.print( "Hello" ); //Not OK
//Program.print( new Date( )); //Not OK
59
}
}
07
-----------------------------------------------------------------
80
Restrictions on Generics
1. Cannot Instantiate Generic Types with Primitive Types
2. Cannot Create Instances of Type Parameters
.in
3. Cannot Declare Static Fields Whose Types are Type Parameters
ys
7. Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase
ith
package com.sunbeaminfo.cj06.test;
de
import java.util.ArrayList;
import java.util.List;
co
94
perform instanceof check against parameterized type
ArrayList<Integer>.
21
//TODO
}
59
}
public static void main1(String[] args) {
07
//ArrayList<int> list = new ArrayList< >(); //Not OK
80
ArrayList<Integer> list = new ArrayList< >(); //OK
}
}
.in
------------------------------------------------------------------
ys
// package com.sunbeaminfo.cj06.test;
public class Program {
ra
int count = 1;
//unicode table char printing
ith
System.out.print(ch+" ");
de
++ count;
if( count == 10 ) {
co
System.out.println();
count = 1;
}
}
}
}
-------------------------------------------------------------------
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
94
string instance.
//String instance get space on heap
21
String s1 = new String("SunBeam"); //new String("SunBeam") =>
String instance
59
System.out.println(s1);//SunBeam
}
07
public static void main2(String[] args) {
80
String s1 = new String("SunBeam");
String s2 = new String("SunBeam");
if( s1 == s2 )
.in
System.out.println("Equal");
else
ys
System.out.println("Not Equal");
ra
if( s1.equals(s2) )
de
System.out.println("Equal");
else
co
System.out.println("Not Equal");
//Output: Equal
}
public static void main4(String[] args) {
//We can create String without new operator.
//if we create String without new operator then it is called
as string literal.
//String literal get space on String literal pool
String s1 = "SunBeam"; //"SunBeam" => String literal
page. 234
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
/* char[] data = { 'S','u','n','B','e','a','m'}; //internally
conversion
String s1 = new String(data); */
}
94
System.out.println("Equal");
else
21
System.out.println("Not Equal");
//Output: Equal
59
}
public static void main(String[] args) {
07
String s1 = "SunBeam";
80
String s2 = "SunBeam";
if( s1.equals(s2))
System.out.println("Equal");
.in
else
System.out.println("Not Equal");
ys
//Output: Equal
ra
}
}
ar
------------------------------------------------------------------
ith
w
de
co
page. 235
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
-------------------------------------------------------------------
07
package com.sunbeaminfo.cj06.test;
public class Program {
80
public static void main(String[] args) {
String s1 = "Sun";
String s2 = s1 +"Beam";
.in
System.out.println( s1 == s2 ); //false : Because String
ys
}
ar
ith
w
de
co
--------------------------------------------------------------
page. 236
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
import java.util.Date;
94
System.out.println(s1); //output:-SunBeam
}
21
public static void main2(String[] args) {
String s1 = "Sun";
59
int number = 123;
//s1 = s1.concat( number ); //Error
07
s1 = s1.concat( String.valueOf(number) ); //OK Sun123
80
System.out.println(s1);
}
public static void main3(String[] args) {
.in
String s1 = "Sun";
String s2 = "Beam";
ys
s1 = s1 + s2;
ra
System.out.println(s1); SunBeam
}
ar
String s1 = "Sun";
int number = 123;
w
s1 = s1 + number;
de
System.out.println(s1); sun123
}
co
94
String s1 = " Sandeep ";
String s2 = "Kulange";
21
s1 = s1.trim(); //to remove spaces
System.out.println(s1+""+s2);
59
}
public static void main9(String[] args) {
07
String s1 = new String("Hello");
80
String s2 = new String("Hello");
System.out.println(s1.equals(s2)); //true
}
.in
public static void main10(String[] args) {
String s1 = new String("Hello");
ys
System.out.println(s1.hashCode()); //69609650
System.out.println(s2.hashCode());//69609650
ar
}
ith
}
------------------------------------------------------------------
w
de
objects
2. Make all fields final and private.
3. Don't allow subclasses to override methods. The simplest way to do this is to declare the
constructor class as final.
A more sophisticated approach is to make the private and construct instances in factory
methods.
4. If the instance fields include references to mutable objects, don't allow those objects to
be changed:
Don't provide methods that modify the mutable objects.
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.
-----------------------------------------------------------------
94
21
59
07
String Introduction
80
• Strings, which are widely used in Java programming, are a sequence of characters. to
manipulate string:
.in
• In the Java programming language, strings are objects.
• We can use following classes
ys
2. java.lang.StringBuffer : mutable
3. java.lang.StringBuilder : mutable character sequence
ar
4. java.util.StringTokenizer
ith
5. java.util.regex.Pattern
6. java.util.regex.Matcher
w
de
java.lang.Character
• It is a final class declared in java.lang package.
co
• 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
94
-------------------------------------------------------------------------------------------------------------------
21
Split String:-
59
07
80
.in
ys
StringTokenizer
ra
• The string tokenizer class allows an application to break a string into tokens.
ar
1. boolean hasMoreElements( )
2. E nextElement()
w
nextToken() class
1. public 2. public 3. public 4. public String nextToken(String delim)
co
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) {
94
String str = "https://docs.oracle.com/javase/8/docs/api/";
StringTokenizer stk = new StringTokenizer(str, "./:");
21
System.out.println(stk.countTokens());
String token = null;
59
while( stk.hasMoreTokens()) {
token = stk.nextToken();
07
System.out.println(token);
80
}
}
public static void main4(String[] args) {
.in
String str = "www.sunbeaminfo.com";
StringTokenizer stk = new StringTokenizer(str, ".");
ys
System.out.println(stk.countTokens());
ra
token = stk.nextToken();
ith
System.out.println(token);
}
w
}
de
94
System.out.println(stk.countTokens()); //3
}
21
}
59
------------------------------------------------------------------
Regex Expression:-
07
Pattern and Matcher
80
• Java.util.regex.Pattern and Matcher Classes are used for matching character sequences
against patterns specified by regular expressions.
.in
• 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.
ys
• Instances of the Matcher class are used to match character sequences against a given
ra
pattern.
ar
package com.sunbeaminfo.cj06.test;
ith
import java.util.Scanner;
import java.util.regex.Matcher;
w
import java.util.regex.Pattern;
de
class Validator{
co
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 = "sandeepkulange@gmail.com";
String regex = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-
94
z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
21
Pattern pattern = Pattern.compile(regex,
Pattern.CASE_INSENSITIVE);
59
Matcher matcher = pattern.matcher(email);
if( matcher.matches())
07
System.out.println(email);
80
else
System.out.println("Invalid email");
}
.in
public static void main2(String[] args) {
String email = "sandeepkulange@gmail.com";
ys
z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
if( Pattern.matches(regex, email))
ar
System.out.println(email);
ith
else
System.out.println("Invalid email");
w
}
de
94
• It is used create to mutable string instance.
21
• equals() and hashCode() method is not overridden inside it.
• We can create instances of these classes using new operator only.
59
• Instances get space on Heap.
• StringBuffer implementation is thread safe whereas StringBuilder is not.
07
• StringBuffer is introduced in JDK1.0and StringBuilder is introduced in JDK 1.5.
80
package com.sunbeaminfo.cj06.test;
.in
import java.util.Scanner;
ys
else
co
System.out.println("Not Equal");
//Output : Not Equal
}
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()))
94
System.out.println("Equal");
else
21
System.out.println("Not Equal");
//Output : Equal
59
}
public static void main4(String[] args) {
07
StringBuffer sb = new StringBuffer("SunBeam");
80
sb.append("Pune/");
sb.append("Karad");
System.out.println(sb.toString());
.in
}
ys
System.out.println("Number : "+number);
w
strNumber = sb.toString();
number = Integer.parseInt(strNumber);
System.out.println("Number : "+number);
}
}
public static void main6(String[] args) {
try( Scanner sc = new Scanner(System.in)){
System.out.print("Enter number : ");
System.out.println("Number : "+Integer.parseInt(new
StringBuffer(String.valueOf(sc.nextInt())).reverse().toString()));
page. 245
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
}
}
}
------------------------------------------------------------------
package com.sunbeaminfo.cj06.test;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Program {
public static void main(String[] args) {
94
Date date = new Date();
//String pattern = "EEE, d MMM yyyy HH:mm:ss Z";
21
String pattern = "dd MMMM,yyyy HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat( pattern );
59
String strDate = sdf.format(date);
System.out.println(strDate);
07
}
80
public static void main1(String[] args) {
Date date = new Date();
System.out.println(date);
.in
}
}
ys
----------------------------------------------------------------------
ra
Interface:-
ar
ith
w
de
co
page. 246
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
• Interface can contain:
1. Nested interface
21
2. Field
59
3. Abstract method
4. Default method
07
5. Static method
• Interfaces cannot have constructors.
80
• We can create reference of interface but we can not create instance of interface.
• We can declare fields inside interface. Interface fields are by default public static and
.in
final.
• We can write methods inside interface. Interface methods are by default considered as
ys
• It is mandatory to override, all the abstract methods of interface otherwise sub class can
ith
be considered as abstract.
w
de
co
page. 247
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
80
Types of inheritance
• Interface Inheritance
During inheritance if super type and sub type is interface then it is called interface
.in
inheritance.
ys
• Implementation Inheritance
w
During inheritance if super type and sub type is class then it is called implementation
de
inheritance.
1. Single Inheritance( Valid in Java)
co
page. 248
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
80
-------------------------------------------------------------------
1. If "is-a" relationship is not exist between super type and sub type and if we want same
.in
method design in all the sub types then super type must be interface.
2. Using interface, we can group instances of unrelated type together.
ys
interface.
w
1. java.lang.AutoCloseable
co
2. java.io.Closeable
3. java.lang.Cloneable
4. java.lang.Comparable
5. java.util.Comparator
6. java.lang.Iterable
7. java.util.Iterator
8. java.io.Serializable
----------------------------------------------------------------------------------------------------------
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()
94
method should return zero( 0 ).
• If we want to sort, array of non primitive type which contains all the instances
21
of same type then we should implement Comparable interface
59
Comparator
07
• It is interface declared in java.util package.
80
• "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()
.in
method should return negative integer( -1 ).
• If state of current object is greater than state of other object then compare()
ys
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.
94
• Cloneable is interface declared in java.lang package.
• Without implementing Cloneable interface, if we try to create clone of the
21
instance then clone() method throws CloneNotSupportedException.
59
07
80
.in
ys
ra
ar
ith
w
-----------------------------------------------------------
de
Marker Interface
co
94
• Iterator is interface declared in java.util package.
• It is used to traverse collection in forward direction only.
21
• It is introduced in JDK 1.2
59
• Methods of java.util.Iterator interface:
1. boolean hasNext() 2. E next() 3. default void remove() 4. default void
07
forEachRemaining(Consumer action).
80
---------------------------------------------------------------------------------------------------------
.in
ys
ra
ar
ith
w
de
co
page. 252
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
page. 253
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
• Static nested class can contain static members.
07
• Using instance, we can access all the members of static nested class inside method of top
80
level class.
• If we want to use non static members of top level class inside method of static nested
class then it is mandatory to create instance of top level class.
.in
ys
Local Class
ra
• In Java, we can define class inside scope of another method. It is called local class /
ar
• In Java, we can not declare local variable /class static hence local class is also called as
local inner class.
• We can not use reference/instance of method local class outside method.
page. 254
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
Method local anonymous inner class.
80
• In java, we can create instance without reference. It is called anonymous instance. •
Example:
.in
• new Object( );
• We can define a class without name. It is called anonymous class.
ys
anonymous class.
ar
• We can not declare local class static hence it is also called as method local anonymous
ith
inner class.
• To define anonymous class, we need to take help of existing interface / abstract class /
w
concrete class.
de
co
page. 255
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
----------------------------------------------------------------------------------------------------------------
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.
94
3.Thread is a separate path of execution which runs independently.
21
-Single tasking: -
59
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.
07
-Multi tasking: -
80
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.
.in
-We can achieve it using.
ys
1.Process
ra
2.Thread
ar
Main objective: -
ith
-If we develop application using single thread then it is called single threaded
de
application(STA).
co
-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.
94
2.Thread is non java resource i.e OS resource.
21
To access OS thread java developer need not to use JNI framework rather developer
59
can use readymade thread framework supplied by sun/oracle in other words java is
multithreaded.
07
Type Of Thread :-
80
.in
ys
ra
ar
ith
w
de
co
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
94
1.Thread State
-Exception
21
1.IlleagalThreaddStateException
2.IllegalMonitorStateException
59
3.InterruptedException.
07
-An interface which is having single abstract method is called functional interface/SAM
interface.
80
-Runnable
1.It is a functional interface declared in java.lang package
.in
2.void run() is method of runnable interface
3.This method is called B.L method.
ys
Object Runnable
ith
w
de
co
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)
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
page. 260
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
page. 261
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
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
94
• In java, collection instance do not contain instances rather it contains
21
reference of instances.
• If we want to use collection framework them we should import java.util
59
package.
07
80
.in
ys
ra
ar
ith
w
de
co
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)
94
• Abstract Methods of Collection Interface
21
1. boolean add(E e)
59
2. boolean addAll(Collection<? Extends E> c)
3. void clear()
07
4. boolean contains(Object o)
80
5. boolean containsAll(Collection <?> c)
6. boolean isEmpty()
.in
7. boolean remove(Object o)
8. boolean removeAll(Collection<?> c)
ys
9. boolean retainAll(Collection<?> c)
ra
10.int size()
ar
11.Object[] toArray()
12. <T> T[] toArray(T[] a)
ith
w
List<E>
de
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)
94
4. int indexOf(Object o)
5. int lastIndexOf(Object o)
21
6. ListIterator<E> listIterator()
59
7. ListIterator<E> listIterator(int index)
8. E remove(int index)
07
9. E set(int index, E element)
80
10. List<E> subList(int fromIndex, int toIndex) .in
ys
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.
94
List list = Collections.synchronizedList(new ArrayList(...));
• Initial capacity of ArrayList is 10. If ArrayList is full then its capacity gets
21
increased by half of its existing capacity.
59
• It is introduced in jdk 1.2
07
• Note: If we want to manage elements of non final type inside ArrayList then
80
non final type should override "equals" method. .in
ys
ra
ar
ith
w
de
co
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;
94
ArrayList<Integer> list2 = new ArrayList<>( 15 ); //OK
21
ArrayList<Integer> list = new ArrayList<>();
59
list.add(10);
list.add(20);
07
ArrayList<Integer> list3 = new ArrayList<>( list ); //OK
80
System.out.println( list3.size());//2
list.add(10);
ith
list.add(20);
List<Integer> list3 = new ArrayList<>( list );
w
}
de
94
List<Integer> list = new ArrayList<>(); // Upcasting
21
list.add(10);
list.add(20);
59
list.add(30);
list.add(40);
07
list.add(50);
80
//also written like this.
//List<Integer> list =Arrays.asList(10,20,30,40,50);
}
.in
public static void main2(String[] args) {
ys
System.out.println(element);
ith
}
}
w
//java.util.Arrays$ArrayList
int index = list.size();
Integer element = list.get(index);
//ArrayIndexOutOfBoundsException
System.out.println(element);
}
public static void main4(String[] args) {
List<Integer> list = new ArrayList<>(); // Upcasting
list.add(10);
list.add(20);
page. 268
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
list.add(30);
list.add(40);
list.add(50);
int index = list.size();
Integer element = list.get(index); //IndexOutOfBoundsException
System.out.println(element);
}
}
----------------------------------------------------------------------
94
package com.sunbeaminfo.cj06.collection.test;
21
import java.util.ArrayList;
import java.util.Arrays;
59
import java.util.Iterator;
import java.util.List;
07
import java.util.ListIterator;
80
public class Program {
.in
public static void main1(String[] args) {
List<Integer> list = Arrays.asList(10, 20, 30, 40, 50 );
ys
}
ith
}
public static void main2(String[] args) {
w
while( itr.hasNext()) {
Integer element = itr.next();
System.out.println(element);
}
}
public static void main3(String[] args) {
List<Integer> list = Arrays.asList(10, 20, 30, 40, 50 );
for( Integer element : list )
System.out.println(element);
}
page. 269
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
public static void main4(String[] args) {
List<Integer> list = Arrays.asList(10, 20, 30, 40, 50 );
list.forEach( e -> System.out.println(e) ); //Using Lambda
Expression
}
public static void main5(String[] args) {
List<Integer> list = Arrays.asList(10, 20, 30, 40, 50 );
list.forEach( System.out::println ); //Using method reference
}
94
public static void main6(String[] args) {
21
List<Integer> list = Arrays.asList(10, 20, 30, 40, 50 );
ListIterator<Integer> itr = list.listIterator();
59
Integer element = null;
//forward direction print
07
while( itr.hasNext()) {
80
element = itr.next();
System.out.print(element+" ");
}
.in
System.out.println();
//backward direction print
ys
while( itr.hasPrevious()) {
ra
element = itr.previous();
System.out.print(element+" ");
ar
}
ith
}
public static void main7(String[] args) {
w
.stream()
.forEach(System.out::println);
co
}
}
----------------------------------------------------------------------
package com.sunbeaminfo.cj06.collection.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
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) {
94
List<Integer> list = Program.getList();
list.add(60);
21
list.add(70);
list.forEach(System.out::println);
59
}
public static void main2(String[] args) {
07
List<Integer> list = Program.getList();
80
Collection<Integer> c = new ArrayList<Integer>();
c.add(60);
c.add(70);
.in
list.addAll( c );
list.forEach(System.out::println);
ys
}
ra
list.addAll( Arrays.asList(60,70) );
ith
list.forEach(System.out::println);
}
w
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;
94
list.add( 20 );
list.add( 30 );
21
list.add( 40 );
list.add( 50 );
59
list.add( 60 );
list.add( 70 );
07
return list;
80
}
if( list.contains(key)) {
ra
}else
ith
if( list.contains(key)) {
int index = list.indexOf(key);
Integer element = list.remove(index);
System.out.println(element+" is removed");
}else
System.out.println(key+" not found ");
}
94
public static void main4(String[] args) {
List<Integer> list = Program.getList();
21
List<Integer> keys = Arrays.asList(30,50,70);
if( list.containsAll(keys)) {
59
boolean removedStatus = list.removeAll(keys);
System.out.println(removedStatus);
07
}else
80
System.out.println(keys+" not found ");
}
public static void main5(String[] args) {
.in
List<Integer> list = Program.getList();
List<Integer> keys = Arrays.asList(30,50,70);
ys
if( list.containsAll(keys)) {
ra
list.retainAll(keys);
//list.removeAll(keys);
ar
System.out.println(keys);
ith
System.out.println(list);
}else
w
}
}
co
----------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.collection.test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
94
Collections.sort(list);
//list.sort(null);
21
//list.stream().sorted().forEach(System.out::println);
}
59
}
----------------------------------------------------------------------------------------------------------
07
package com.sunbeaminfo.cj06.collection.model;
80
import lombok.AllArgsConstructor;
.in
import lombok.EqualsAndHashCode;
import lombok.Getter;
ys
import lombok.NoArgsConstructor;
import lombok.Setter;
ra
import lombok.ToString;
ar
ith
@NoArgsConstructor
@AllArgsConstructor
w
@Getter @Setter
de
@EqualsAndHashCode
//@ToString
co
/*@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);
94
}
}
21
59
package com.sunbeaminfo.cj06.collection.test;
07
import java.util.ArrayList;
80
import com.sunbeaminfo.cj06.collection.model.Employee; .in
public class ListTest {
private ArrayList<Employee> empList = new ArrayList<Employee>();
ys
this.empList.add(emp);
ith
}
}
w
return emp;
}
return null;
} */
94
int index = this.empList.indexOf(key);
this.empList.remove(index); //method of List I/F
21
return true;
}
59
return false;
}*/
07
80
public boolean removeRecord(int empid) {
Employee key = new Employee();
key.setEmpid(empid);
.in
if( this.empList.contains(key)) {
this.empList.remove(key); //method of Collection I/F
ys
return true;
ra
}
return false;
ar
}
ith
System.out.println(emp.toString());
de
}
}
co
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;
94
public static void acceptRecord( int[] empid ) {
System.out.print("Enter empid : ");
21
empid[ 0 ] = sc.nextInt();
}
59
private static void printRecord(Employee emp) {
if( emp != null )
07
System.out.println(emp.toString());
80
else
System.out.println("Employee not found");
}
.in
private static void printRecord(boolean removedStatus) {
if( removedStatus )
ys
System.out.println("Employee is removed");
ra
else
System.out.println("Employee not found");
ar
}
ith
94
case 1:
Employee[] employees = Program.getEmployees();
21
test.addRecord(employees);
break;
59
case 2:
Program.acceptRecord(empid);
07
Employee emp = test.findRecord( empid[ 0 ] );
80
Program.printRecord( emp );
break;
case 3:
.in
Program.acceptRecord(empid);
boolean removedStatus = test.removeRecord( empid[ 0 ]
ys
);
ra
Program.printRecord(removedStatus);
break;
ar
case 4:
ith
test.printRecords();
break;
w
}
de
}
}
co
----------------------------------------------------------------------
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
94
public class Employee implements Comparable<Employee> {
@EqualsAndHashCode.Exclude private String name;
21
@EqualsAndHashCode.Include private int empid;
@EqualsAndHashCode.Exclude private float salary;
59
/*@Override
07
public boolean equals(Object obj) {
80
if( obj != null ) {
Employee other = (Employee) obj;
if( this.empid == other.empid)
.in
return true;
}
ys
return false;
ra
}*/
ar
@Override
ith
this.empid, this.salary);
de
}
co
@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;
94
for( Employee emp : employees )
this.empList.add(emp);
21
}
}
59
/* public Employee findRecord(int empid) {
for( Employee emp : this.empList ) {
07
if( emp.getEmpid() == empid )
80
return emp;
}
return null;
.in
} */
ys
if( this.empList.contains(key)) {
ith
return emp;
de
}
return null;
co
}
/* public boolean removeRecord(int empid) {
Employee key = new Employee();
key.setEmpid(empid);
if( this.empList.contains(key)) {
int index = this.empList.indexOf(key);
this.empList.remove(index); //method of List I/F
return true;
}
return false;
page. 280
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
}*/
94
return false;
}
21
public void printRecords( Comparator<Employee> comparator ) {
//Collections.sort(this.empList, comparator);
59
this.empList.sort(comparator);
for( Employee emp : this.empList )
07
System.out.println(emp.toString());
80
}
}
.in
package com.sunbeaminfo.cj06.collection.util;
import java.util.Comparator;
ys
import com.sunbeaminfo.cj06.collection.model.Employee;
ra
@Override
ith
}
de
}
co
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;
94
}
}
21
59
package com.sunbeaminfo.cj06.collection.test;
07
import java.util.ArrayList;
80
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
.in
import java.util.Comparator;
import java.util.List;
ys
import java.util.Scanner;
ra
import javax.lang.model.element.Element;
ar
ith
import com.sunbeaminfo.cj06.collection.model.Employee;
import com.sunbeaminfo.cj06.collection.util.CompareByEmpid;
w
import com.sunbeaminfo.cj06.collection.util.CompareByName;
de
import com.sunbeaminfo.cj06.collection.util.CompareBySalary;
co
94
Employee[] arr = new Employee[ 5 ];
arr[ 0 ] = new Employee( "Nitin", 13, 50000);
21
arr[ 1 ] = new Employee( "Amit", 10, 45000);
arr[ 2 ] = new Employee( "Sarang", 15, 40000);
59
arr[ 3 ] = new Employee( "Yogesh", 14,25000);
arr[ 4 ] = new Employee( "Digvijay", 12,30000);
07
return arr;
80
}
public static int menuList( ) {
System.out.println("0.Exit");
.in
System.out.println("1.Add Record");
System.out.println("2.Find Record");
ys
System.out.println("3.Remove Record");
ra
System.out.println("4.Print Record");
System.out.print("Enter choice : ");
ar
return sc.nextInt();
ith
}
public static int subMenuList( ) {
w
System.out.println("0.Exit");
de
System.out.println("1.Sort By Name");
System.out.println("2.Sort By Empid");
co
System.out.println("3.Sort By Salary");
System.out.print("Enter choice : ");
return sc.nextInt();
}
public static void main(String[] args) {
int choice;
int[] empid = new int[ 1 ];
ListTest test = new ListTest();
while( ( choice = Program.menuList( ) ) != 0 ) {
switch( choice ) {
page. 283
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
case 1:
Employee[] employees = Program.getEmployees();
test.addRecord(employees);
break;
case 2:
Program.acceptRecord(empid);
Employee emp = test.findRecord( empid[ 0 ] );
Program.printRecord( emp );
break;
94
case 3:
Program.acceptRecord(empid);
21
boolean removedStatus = test.removeRecord( empid[ 0 ]
);
59
Program.printRecord(removedStatus);
break;
07
case 4:
80
while( ( choice = Program.subMenuList( ) ) != 0 ) {
Comparator<Employee> comparator = null;
switch( choice ) {
.in
case 1:
comparator = new CompareByName();
ys
break;
ra
case 2:
comparator = new CompareByEmpid();
ar
break;
ith
case 3:
comparator = new CompareBySalary();
w
break;
de
}
test.printRecords( comparator );
co
}
break;
}
}
}
}
----------------------------------------------------------------------
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;
94
import lombok.ToString;
21
@NoArgsConstructor
@AllArgsConstructor
59
@Getter @Setter
07
@EqualsAndHashCode
//@ToString
80
public class Employee implements Comparable<Employee> {
@EqualsAndHashCode.Exclude private String name;
@EqualsAndHashCode.Include private int empid;
.in
@EqualsAndHashCode.Exclude private float salary;
ys
/*@Override
ra
return true;
}
de
return false;
co
}*/
@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;
94
import java.util.List;
import java.util.Vector;
21
import com.sunbeaminfo.cj06.collection.model.Employee;
59
public class ListTest {
07
//private ArrayList<Employee> empList = new ArrayList<>();
80
private List<Employee> empList;
public void setEmpList(List<Employee> empList) {
this.empList = empList;
.in
}
public void addRecord( Employee[] employees ) {
ys
this.empList.add(emp);
ith
}
}
w
}
de
94
return false;
}
21
public void printRecords( Comparator<Employee> comparator ) {
if( this.empList != null ) {
59
this.empList.sort(comparator);
for( Employee emp : this.empList )
07
System.out.println(emp.toString());
80
}
}
}
.in
package com.sunbeaminfo.cj06.collection.util;
ys
import java.util.Comparator;
ra
import com.sunbeaminfo.cj06.collection.model.Employee;
ar
@Override
public int compare(Employee e1, Employee e2) {
w
}
}
co
package com.sunbeaminfo.cj06.collection.util;
import java.util.Comparator;
import com.sunbeaminfo.cj06.collection.model.Employee;
public class CompareByName implements Comparator<Employee> {
@Override
public int compare(Employee e1, Employee e2) {
return e1.getName().compareTo(e2.getName());
}
}
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;
94
}
21
package com.sunbeaminfo.cj06.collection.test;
59
import java.util.ArrayList;
import java.util.Arrays;
07
import java.util.Collection;
80
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
.in
import java.util.List;
import java.util.Scanner;
ys
import java.util.Vector;
ra
import javax.lang.model.element.Element;
ar
ith
import com.sunbeaminfo.cj06.collection.model.Employee;
import com.sunbeaminfo.cj06.collection.util.CompareByEmpid;
w
import com.sunbeaminfo.cj06.collection.util.CompareByName;
de
import com.sunbeaminfo.cj06.collection.util.CompareBySalary;
co
94
Employee[] arr = new Employee[ 5 ];
arr[ 0 ] = new Employee( "Nitin", 13, 50000);
21
arr[ 1 ] = new Employee( "Amit", 10, 45000);
arr[ 2 ] = new Employee( "Sarang", 15, 40000);
59
arr[ 3 ] = new Employee( "Yogesh", 14,25000);
arr[ 4 ] = new Employee( "Digvijay", 12,30000);
07
return arr;
80
}
public static int menuList( ) {
System.out.println("0.Exit");
.in
System.out.println("1.Add Record");
System.out.println("2.Find Record");
ys
System.out.println("3.Remove Record");
ra
System.out.println("4.Print Record");
System.out.print("Enter choice : ");
ar
return sc.nextInt();
ith
}
public static int subMenuList( ) {
w
System.out.println("0.Exit");
de
System.out.println("1.Sort By Name");
System.out.println("2.Sort By Empid");
co
System.out.println("3.Sort By Salary");
System.out.print("Enter choice : ");
return sc.nextInt();
}
public static void main(String[] args) {
int choice;
int[] empid = new int[ 1 ];
ListTest test = new ListTest();
//test.setEmpList(new ArrayList<Employee>());
//test.setEmpList(new Vector<Employee>());
page. 289
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
test.setEmpList(new LinkedList<Employee>());
while( ( choice = Program.menuList( ) ) != 0 ) {
switch( choice ) {
case 1:
Employee[] employees = Program.getEmployees();
test.addRecord(employees);
break;
case 2:
Program.acceptRecord(empid);
94
Employee emp = test.findRecord( empid[ 0 ] );
Program.printRecord( emp );
21
break;
case 3:
59
Program.acceptRecord(empid);
boolean removedStatus = test.removeRecord( empid[ 0 ]
07
);
80
Program.printRecord(removedStatus);
break;
case 4:
.in
while( ( choice = Program.subMenuList( ) ) != 0 ) {
Comparator<Employee> comparator = null;
ys
switch( choice ) {
ra
case 1:
comparator = new CompareByName();
ar
break;
ith
case 2:
comparator = new CompareByEmpid();
w
break;
de
case 3:
comparator = new CompareBySalary();
co
break;
}
test.printRecords( comparator );
}
break;
}
}
}
}
----------------------------------------------------------------------
page. 290
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Vector<E>
• It is resizable array.
• It implements List, RandomAccess, Cloneable, Serializable.
• It is List collection.
• It is synchronized collection.
• Default capacity of vector is 10. If vector is full then its capacity gets increased
by its existing capacity.
• We can traverse elements of vector using Iterator, ListIterator as well as
94
Enumeration.
• It is introduced in jdk 1.0.
21
• Note: If we want to manage elements of non final type inside Vector then non
59
final type should override "equals" method.
07
80
Synchronized Collections
• 1. Vector
.in
• 2. Stack(Sub class of Vector)
• 3. Hashtable
ys
Enumeration<E>
ith
1. boolean hasMoreElements()
de
2. E nextElement()
co
page. 291
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
page. 292
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
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()
94
4. default void forEachRemaining(Consumer<? Super E> action)
• It is introduced in jdk 1.2
21
59
ListIterator<E>
07
• It is sub interface of Iterator interface.
• It is used to traverse only List Collection in bidirectional.
80
• During traversing, we can add, set as well as remove element from collection.
• It is introduced in jdk 1.2
.in
• Methods of ListIterator
ys
1. boolean hasNext()
2. E next()
ra
3. boolean hasPrevious()
ar
4. E previous()
ith
5. void add(E e)
6. void set(E e)
w
7. void remove()
de
co
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
--------------------------------------------------------------------------------------------------------------------------
94
21
2. Fail Safe Iterator
• During traversing, if iterator allows us to do changes in underlying
59
collection then such iterator is called fail safe iterator.
07
80
.in
ys
ra
ar
ith
w
de
co
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.
94
21
59
07
80
.in
ys
ra
ar
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.
94
• Note : If we want to manage elements of non-final type inside LinkedList then
21
non final type should override "equals" method.
• Instantiation
59
List <integer> list = new LinkedList<>();
07
----------------------------------------------------------------------------------------------------------
80
Queue Interface Hierarchy:-
.in
ys
ra
ar
ith
w
de
co
page. 297
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
package com.sunbeaminfo.cj06.collection.test;
import java.util.ArrayDeque;
94
import java.util.Queue;
public class Program {
21
public static void main1(String[] args) {
59
Queue<Integer> que = new ArrayDeque<>();
que.add(10);
07
que.add(20);
que.add(30);
80
Integer element = null;
.in
while( !que.isEmpty( ) ) {
element = que.element();
ys
System.out.println(element);
que.remove();
ra
}
ar
}
ith
que.offer(10); //offer-->add
de
que.offer(20); //offer-->add
que.offer(30);//offer-->add
co
94
21
59
07
• Deque Interface is a linear collection that supports element insertion and
80
.in
removal at both ends.
ys
ArrayDeque.
ith
ArrayDeque();
de
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.
94
21
59
// package com.sunbeaminfo.cj06.collection.test;
import java.util.ArrayDeque;
07
import java.util.Deque;
80
public class Program {
public static void main1(String[] args) {
.in
Deque<Integer> que = new ArrayDeque<>( );
que.add(20);
ys
que.add(30);
ra
que.add(40);
que.addFirst(10);
ar
que.addLast(50);
ith
que.addFirst(5);
que.addLast(60);
w
que.removeFirst();
de
que.removeLast();
co
94
System.out.println(element);
que.removeFirst();
21
}
}
59
public static void main3(String[] args) {
Deque<Integer> que = new ArrayDeque<>( );
07
que.add(10);
80
que.add(20);
que.add(30);
que.add(40);
.in
que.add(50);
ys
while( !que.isEmpty()) {
element = que.getLast();
ar
System.out.println(element);
ith
que.removeLast();
}
w
}
de
}
co
----------------------------------------------------------------------------------------------------------
page. 301
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Set Interface Hierarchy :-
94
21
59
07
80
.in
• It is sub interface of java.util.Collection interface.
• HashSet, LinkedHashSet, TreeSet etc. implements Set interface. It is also called
ys
as Set collection.
ra
• There are three concrete Set implementations that are part of the Collection
de
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.
94
• Using "Collections.synchronizedSortedSet()” method we can make it
synchronized. SortedSet s = Collections.synchronizedSortedSet(new
21
TreeSet(...));
59
• It is introduced in jdk 1.2
07
• Note : If we want to manage elements of non final type inside TreeSet then
80
non final type should implement Comparable interface.
• Instantiation Set set = new TreeSet<>( );
.in
ys
ra
Hashing :-
ar
94
• In hashcode based collection, if we want manage elements of non final type
then reference type should override equals() and hashcode() method.
21
• we want to generate hashcode then in sub class.
59
• hashCode() is non final method of java.lang.Object class.
• Syntax: public native int hashCode( );
07
• On the basis of state of the object, we should override hashCode() method
80
• The hashCode method defined by class Object does return distinct integers for
distinct objects. This is typically implemented by converting the internal address
.in
of the object into an integer.
ys
HashSet<E>
ra
• It Set Collection.
• It can not contain duplicate elements but it can contain null element.
ar
• It is unordered collection.
w
• 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;
94
import java.util.LinkedHashSet;
import java.util.Set;
21
import java.util.TreeSet;
59
public class Program {
07
public static void main1(String[] args) {
80
Set<Integer> set = new TreeSet<>( );
set.add(50);
set.add(10);
.in
set.add(40);
set.add(20);
ys
set.add(30);
ra
System.out.println(element);
ith
}
}
w
set.add(10);
set.add(40);
set.add(20);
set.add(30);
//Duplicate values not allowed.
set.add(50);
set.add(10);
set.add(40);
set.add(20);
set.add(30);
page. 305
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
for (Integer element : set) {
System.out.println(element);
}
}
94
set.add(40);
set.add(20);
21
set.add(30);
set.add(null); //NullPointerException
59
for (Integer element : set) {
07
System.out.println(element);
80
}
}
public static void main4(String[] args) {
.in
Set<Integer> set = new HashSet<Integer>();
set.add(234);
ys
set.add(9823);
ra
set.add(1863);
set.add(754);
ar
set.add(50);
ith
System.out.println(element);
de
}
//output: 754 50 1863 234 9823
co
}
public static void main5(String[] args) {
Set<Integer> set = new HashSet<Integer>();
set.add(234);
set.add(9823);
set.add(1863);
set.add(754);
set.add(50);
set.add(234);
page. 306
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
set.add(9823);
set.add(1863);
set.add(754);
set.add(50);
94
}
public static void main6(String[] args) {
21
Set<Integer> set = new HashSet<Integer>();
set.add(234);
59
set.add(9823);
set.add(1863);
07
set.add(754);
80
set.add(50);
set.add(null);
.in
for (Integer element : set) {
System.out.println(element);
ys
}
ra
set.add(9823);
de
set.add(1863);
set.add(754);
co
set.add(50);
----------------------------------------------------------------------------------------------------------
page. 307
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
Map Interface Hierarchy :-
94
21
59
07
80
Dictionary<K,V>
• It is abstract class declared in java.util package.
.in
• It is is super class of Hashtable.
ys
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
94
• Map.Entry<K,V> is nested interface of Map<K,V>.
• Following are abstract methods of Map.Entry interface. duplicate values.
21
1. K getKey()
59
2. V getValue()
3. V setValue(V value)
07
80
Map<K,V>
• Abstract Methods of Map<K,V>
.in
1. boolean isEmpty()
ys
4.int Size()
5.boolean containsKey(Object Key)
ith
7.V.get(Object Key)
de
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.
94
21
HashMap<K,V>
59
• It is map collection
• It's implementation is based on Hashtable.
07
• It can not contain duplicate keys but it can contain duplicate values.
80
• In HashMap, key and value can be null.
• It is unsynchronized collection. Using Collections.synchronizedMap() method,
.in
we can make it synchronized. :-
Map m = Collections.synchronizedMap(new HashMap(...));
ys
• Instantiation
ar
LinkedHashMap<K,V>
• It is sub class of HashMap class
co
TreeMap<K,V>
• It is map collection.
• It can not contain duplicate keys but it can contain duplicate values.
94
• It TreeMap, key not be null but value can be null.
• Implementation of TreeMap is based on Red-Black Tree.
21
• It maintains entries in sorted form according to the key.
59
• It is unsynchronized collection. Using Collections.synchronizedSortedMap()
method, we can make it synchronized.
07
SortedMap m = Collections.synchronizedSortedMap(new
80
TreeMap(...));
• Instantiation:
.in
Map map = new TreeMap<>();
• It is introduced in jdk 1.2
ys
• Note : In TreeMap, if we want to use element of non final type as a key then it
ra
Programs:-
de
co
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;
94
Set<Integer> keys = map.keySet();
for (Integer key : keys) {
21
System.out.println(key);
}
59
}
private static void printValues(Map<Integer, String> map) {
07
Collection<String> values = map.values();
80
for (String value : values) {
System.out.println(value);
}
.in
}
private static void printEntries(Map<Integer, String> map) {
ys
}
ith
}
private static void findEntry(Map<Integer, String> map, int id) {
w
if( map.containsKey(key)) {
String value = map.get(key);
co
System.out.println(key+" "+value);
}else
System.out.println(key+" not found");
}
private static void removeEntry(Map<Integer, String> map, int id)
{
Integer key = new Integer(id);
if( map.containsKey(key)) {
String value = map.remove(key);
System.out.println(key+" "+value+" is removed");
page. 312
Core Java Notes By ASHOK PATE
--------------------------------------------------------------------------------------------------------------------------
}else
System.out.println(key+" not found");
}
public static void main(String[] args) {
Map<Integer, String> map = Program.getMap();
//Program.printKeys( map );
//Program.printValues( map );
//Program.printEntries( map );
94
//Program.findEntry( map, 1234 );
Program.removeEntry( map, 1234 );
21
}
}
59
-------------------------------------------------------------------------------------------------------
07
80
.in
ys
ra
ar
ith
w
de
co
page. 313