0% found this document useful (0 votes)
143 views130 pages

CoreJAVA 20apr2022

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 130

JAVA

PANKAJ SIR ACADEMY NOTES

Prepared by:
PANKAJ SIR ACADEMY CORE JAVA

Notes prepared by _M$A_ : 8801114535. 2


PANKAJ SIR ACADEMY CORE JAVA

S. No Date & Day Topic Page


1. 21 Apr, 2022 (Thu) Keywords in JAVA, Garbage Collector 6
2. 22 Apr, 2022 (Fri) Non-Static / Instance Variable, Static Variable 7
3. 25 Apr, 2022 (Mon) Static Variable (Contd…), Methods, Types of variables 9
4. 27 Apr, 2022 (Wed) Stack and Heap Memory 13
Stack and Heap Memory (Contd…), Types of variables
5. 28 Apr, 2022 (Thu) 15
(Contd...)
6. 29 Apr, 2022 (Fri) Data types in JAVA, Conventions in JAVA 17
7. 04 May, 2022 (Wed) Var types in JAVA, Types of variables (Contd...) 20
8. 06 May, 2022 (Fri) Methods in JAVA 25
9. 09 May, 2022 (Mon) Constructors in JAVA, Constructor Overloading 29
10. 10 May, 2022 (Tue) Default Constructor 32
11. 11 May, 2022 (Wed) “this” Keyword 34
12. 12 May, 2022 (Thu) “this” Keyword (Contd…), Constructor Chaining 37
13. 13 May, 2022 (Fri) OOPs Concept: Inheritance 39
14. 14 May, 2022 (Sat) Assignment-1: Unary Operator in JAVA 41
15. 18 May, 2022 (Wed) Packages in JAVA 44
16. 19 May, 2022 (Thu) Access Specifiers/Modifiers in JAVA 48
Assignment-2: Interface Initialization Block (IIB)
17. 19 May, 2022 (Thu) 54
Static Initialization Block (SIB)
18. 20 May, 2022 (Fri) OOPs Concept (Contd…): Polymorphism 60
19. 23 May, 2022 (Mon) OOPs Concept (Contd…): Encapsulation, Interface in JAVA 63
20. 24 May, 2022 (Tue) Interface in JAVA (Contd…) 66
Interface in JAVA (Contd…), Upcasting in JAVA, JAVA 8 New
21. 25 May, 2022 (Wed) 69
Features
JAVA 8 New Features (Contd…): “default” keyword, OOPs
22. 26 May, 2022 (Thu) 72
Concept (Contd…): Abstraction
23. 26 May, 2022 (Thu) Assignment-3: “super” keyword 74
24. 27 May, 2022 (Fri) OOPs Concept (Contd…): Abstraction, Exceptions in JAVA 77
Exceptions in JAVA (Contd…): Exception Class Hierarchy in
25. 30 May, 2022 (Mon) 81
JAVA
Exception Class Hierarchy in JAVA (Contd…): RunTime
26. 31 May, 2022 (Tue) 82
Exception, Loops in JAVA, “break” Keyword
“continue” Keyword, Conditional Statement in JAVA, Loops in
27. 01 Jun, 2022 (Wed) 87
JAVA (Contd…), Scanner Class (User Input) in JAVA
Array In JAVA: Dynamic Arrays,
28. 02 Jun, 2022 (Thu) 91
Exception: ArrayIndexOutOfBoundsException

Notes prepared by _M$A_ : 8801114535. 3


PANKAJ SIR ACADEMY CORE JAVA
Array in JAVA (Contd..): Removing Duplicate Elements, Swap in
29. 03 Jun, 2022 (Fri) 95
JAVA
30. 04 Jun, 2022 (Fri) Array in JAVA (Contd..): Sorting Array in JAVA 97
31. 08 Jun, 2022 (Wed) Array in JAVA (Contd..): 2-D Array, File Handling in JAVA 99
32. 09 Jun, 2022 (Thu) File Handling in JAVA (Contd…): File Reader, File Writer 103
33. 09 Jun, 2022 (Thu) Task Assignment: Watch Recorded Lectures in PSA App 109
File Handling in JAVA (Contd…): Buffered Reader & Writer,
34. 10 Jun, 2022 (Fri) 110
Serialization
35. 13 Jun, 2022 (Mon) De-Serialization, JAVA Database Connectivity (JDBC), MySQL 114
36. 14 Jun, 2022 (Tue) JAVA Database Connectivity (JDBC): MySQL (Contd…) 116
JAVA Database Connectivity (JDBC): MySQL (Contd…), Multiple
37. 15 Jun, 2022 (Wed) Catch Block in Try-Catch Block, CRUD Operations, Finally Block, 121
Difference between Final, Finally and Finalize

Notes prepared by _M$A_ : 8801114535. 4


PANKAJ SIR ACADEMY CORE JAVA

Notes prepared by _M$A_ : 8801114535. 5


PANKAJ SIR ACADEMY CORE JAVA
21/04/2022 (Thursday)

Syntaxes: { }, ( ), ;

NEW (Keyword):
NEW Keyword Sends request to the class, & class creates Object. Once the Object is
created, NEW keyword will get Object’s address in a reference variable.

GARBAGE COLLECTOR:
Garbage Collector on regular basis keeps removing unused objects from RAM, thus avoiding
overflow of memory, this helps us manage memory efficiently.

Notes prepared by _M$A_ : 8801114535. 6


PANKAJ SIR ACADEMY CORE JAVA
22/04/2022 (Friday)

NON-STATIC/INSTANCE VARIABLE:

These variables are created inside class but outside method without using “static”
keyword. Without creating object this variable cannot be accessed & hence we get error as
shown below:

Let’s correct it:

Notes prepared by _M$A_ : 8801114535. 7


PANKAJ SIR ACADEMY CORE JAVA
Every time we create an object a copy of non-static member will be loaded into that object.

STATIC VARIABLE:
These variables are created inside the class & outside method using “static” keyword,
these variables belong to class and can be accessed with class name. .i.e

Notes prepared by _M$A_ : 8801114535. 8


PANKAJ SIR ACADEMY CORE JAVA
25/04/2022 (Monday)

STATIC VARIABLE: (Contd…)

The value of static variables can be changed as shown in the below Ex:

METHODS:

Methods can be Static or Non Static, If we write “static” in method then it belongs to
Object, If ”static” is not written then it is Non Static.

Ex: public static void main(String[] args) (Static Method)


public void test() { (non static method)

To call a non static method, we need to create an object then only we can call it. i.e:

Notes prepared by _M$A_ : 8801114535. 9


PANKAJ SIR ACADEMY CORE JAVA
If we apply “static” to 2nd method (in above example) then it becomes static method, for
static methods no need to create an object for calling, we can call it directly with class name,
see the next Ex.

The following are the types of variables in JAVA


1) Local Variable
2) Static Variable
3) Non-Static Variable
4) Reference Variable

1. Local Variable: These variables are created inside a method & should be used only within
created method. If used outside created method, then we’ll get an error as shown in the
example below.

Notes prepared by _M$A_ : 8801114535. 10


PANKAJ SIR ACADEMY CORE JAVA

Ex: 2

Correct Error

Correct

It is mandatory to initialize local variable before using it or else we get an error as shown
in the below example:

Notes prepared by _M$A_ : 8801114535. 11


PANKAJ SIR ACADEMY CORE JAVA
2. Static Variable: These variables are global and can be used in any method with class
name.

Notes prepared by _M$A_ : 8801114535. 12


PANKAJ SIR ACADEMY CORE JAVA
27/04/2022 (Wednesday)

STACK AND HEAP MEMORY:


• Program execution flow is maintained in stack & removed in last-in-first
• All the objects created in java are stored in heap, and after the execution of program the
reference to the object is gone, and object without reference in JAVA is called as “unused
object” and is eligible for garbage collection.
• Non static & static variables are stored in a dedicated space in stack memory called
“META SPACE”, It stores the original copy of static and non static variable, It doesn’t store
the local variables. Non static variables from meta space gets loaded into object where
as the Static variable remains there.

RAM

STACK HEAP

Program Objects
Execution

Example 1:

public class A {
STACK HEAP
public static void main(String[] args) { ----- START
A a1 = new A(); ------- 2 main {
object

System.out.println(a1); ------- 3
A a1 = new A();
SOP(a1); Unused object

} -------------------------------------------- STOP
}
Garbage

}
collection

Example 2:

public class A {
STACK HEAP
public static void main(String[] args) { ----- START
A a1 = new A(); ------- 2 main {
object

object

A a2 = new A(); ------- 3


A a1 = new A();
A a2 = new A();
SOP(a1); Unused object

System.out.println(a1); ------- 4 }
SOP(a2);
Garbage

System.out.println(a2); ------- 5
collection

} -------------------------------------------- STOP
}
Notes prepared by _M$A_ : 8801114535. 13
PANKAJ SIR ACADEMY CORE JAVA
Example 3: (with non static variable)

public class A {
HEAP
int x = 10; //non static variable STACK

public static void main(String[] args) { ----- START main {


A a1 = new A();
int x = 10;

A a1 = new A(); ------- 2 SOP(a1.x);


} Unused object

System.out.println(a1.x); ------- 3 Garbage

} -------------------------------------------- STOP int x = 10; collection

} Meta Space

Example 4: (with non static & static variable)

public class A {
HEAP
int x = 10; //non static variable STACK
static int y = 20; //static variable int x = 10;

public static void main(String[] args) { ----- START main {


A a1 = new A();

A a1 = new A(); ------- 2 SOP(a1.x);


SOP(A.y);

System.out.println(a1.x); ------- 3
}

Unused object

System.out.println(A.y); ------- 4 int x = 10;


static int y=10; Garbage

} -------------------------------------------- STOP collection

} Meta Space

Example 5: (with non static & static variable)

public class A {
int x = 10; //non static variable
int y = 20; //non static variable HEAP
static int z = 100; //static variable STACK
public static void main(String[] args) { ----- START main {
A a1 = new A();

A a1 = new A(); ------- 2


int x = 10;
SOP(a1.x); int y = 20;
SOP(a1.y);

System.out.println(a1.x); ------- 3
SOP(A.z);
}
Unused object

System.out.println(a1.y); ------- 4 int x = 10; Garbage

System.out.println(A.z); ------- 5 int y=20;


static int z = 100;
collection

} -------------------------------------------- STOP
} Meta Space

Notes prepared by _M$A_ : 8801114535. 14


PANKAJ SIR ACADEMY CORE JAVA
28/04/2022 (Thursday)

Example 6: (with multiple methods)


STACK HEAP
public class A {
public static void main(String[] args) { ----- START
Test(){
SOP(100);

A a1 = new A(); ------- 2


} object

a1.test(); ------- 3
main {
A a1 = new A();

} -------------------------------------------- STOP
a1.test();
Unused object
}

public void test(); { Garbage


collection

System.out.println(100); ------- 4
} ------- 5
}

Example 7: (with multiple methods (static))


STACK HEAP
public class A {
int x = 10;
Static Test(){ Int x = 10:
A a1 = new A();
SOP(a1.x)

public static void main(String[] args) { ----- START }


}

A.test(); ------- 2
main {
A.test();

} -------------------------------------------- STOP
}
Unused object

public static void test(); { Garbage


collection

A a1 = new A(); ------- 3


int x = 10;

System.out.println(a1.x); ------- 4
} ------- 5
}

Types of variables in Java (Contd…)

1. Static Variable (Contd..): These variables are global and can be used in any method with
ClassName, we can access static variables in 3 ways.

Notes prepared by _M$A_ : 8801114535. 15


PANKAJ SIR ACADEMY CORE JAVA
It is not mandatory to initialize static variable. if we don't initialize then depending on the ‘data
type’ default value gets stored in it. In the below example because the data type is “int”,
automatically value zero gets stored in it.

Notes prepared by _M$A_ : 8801114535. 16


PANKAJ SIR ACADEMY CORE JAVA
29/04/2022 (Friday)

Memory Default
Data Type Value Range Value Type
Size Value
Byte 1 byte 0 -128 .. 127
Short 2 bytes 0 -32,768 .. 32,767
-2,147,483,648 .. Integer
Int 4 bytes 0 2,147,483,647
- Value
9,223,372,036,854,775,808
Long 8 bytes 0 ..
9,223,372,036,854,775,807
3.40282347 x 1038,
Float 4 bytes 0.0 1.40239846 x 10-45 Decimal
Double 8 bytes 0.0 Value
Char 2 bytes Empty Space Character
Boolean NA false True/False
String (Class) NA null
Var (Ver. 10 of
Dynamic
Java)

Integer default value Example:

Notes prepared by _M$A_ : 8801114535. 17


PANKAJ SIR ACADEMY CORE JAVA
Example #2: (all the data types with some values)

• All the KEYWORDS in java are in lowercase.


Ex: new, class, static, int, short

• ClassName should start with Uppercase


Ex: Bank.
public class Bank {
If there are two words in ClassName it should be in CamelCasing
Ex: BankAccount, (it improves readability)
public class BankAccount {

• Variable name should be in lowercase or start with lowercase, if it has two words, it
should be in camelCasing. 1st word start with lowercase & the rest start with uppercase.
Ex: int id;
int employeeId;
int yourIdCard;
Notes prepared by _M$A_ : 8801114535. 18
PANKAJ SIR ACADEMY CORE JAVA
• Variable name cannot start with number in Java.
Ex: int 2id; //Error
int id2: //Correct

• Can not create variable name with space


Ex: Your Card; //Error
• Only two special characters are allowed in Java, UnderScore “_” and Dollar “$”, we can
use it anywhere, no other special characters are allowed.
Ex: int $id;
int i$d;
int id$;
int your_card;
int _your_card;
• Methods in Java can be identified with parentheses “()” beside variable and in casing it is
same as variables.
Ex: employeeId()
yourCardId()

Notes prepared by _M$A_ : 8801114535. 19


PANKAJ SIR ACADEMY CORE JAVA
04/05/2022 (Wednesday)

Var type was introduced in version 10 of Java, it will not work with Java below V10.
A variable with the type ‘var’ can store any kind of value in it. It cannot be static or non static
variable, it can only be local variable & created inside method.
Example:

Limitations of var type:


A variable with type var can not be a method argument and static or non static
variable. It can only be local variable as shown in the below example:

Notes prepared by _M$A_ : 8801114535. 20


PANKAJ SIR ACADEMY CORE JAVA
The memory size of var type is dynamic, means depending upon the value stored the
memory increases and decreases.
A var type can not be method argument, see the below examples:

Example #1: (with data type int)

Example #2: (with String)

Example #2: (with int and String)

Notes prepared by _M$A_ : 8801114535. 21


PANKAJ SIR ACADEMY CORE JAVA
Example #3: (using var in method argument)

Var is not a keyword in Java & hence we can use it as variable name as well, Ex:

Notes prepared by _M$A_ : 8801114535. 22


PANKAJ SIR ACADEMY CORE JAVA

Types of variables in Java (Contd…)

4. Reference Variable: In a reference variable we can store either object’s address or null.
The data type of variable name is ClassName.

Variable Assgn.
Data type Value Terminator
Name Operator
int x = 10 ;
char c = ‘a’ ;

While creating reference variable


Variable Assgn. Object’s
ClassName Terminator
Name Operator address / null
A x = new A () ;
A x = null ;

Types of reference variables:


1) Local reference variable
2) Static reference variable

1. Local Variable: These variables are created inside method & should be used only within the
created method. If used outside method the program will throw an error, see the below
example:

Notes prepared by _M$A_ : 8801114535. 23


PANKAJ SIR ACADEMY CORE JAVA
2. Static reference variable: These variables are created outside method but inside class using
static keyword. This variable has global access & can be used anywhere in the program.

The default value for a static reference variable is ‘null’ as shown in below example:

Notes prepared by _M$A_ : 8801114535. 24


PANKAJ SIR ACADEMY CORE JAVA
06 /05/2022 (Friday)

1) void
2) return value
3) return

1. void method: if a method is void, then it can not return any value, hence the below
program throws an error:

Example #2: without void method (if return value is needed):


If return value is needed, we should use data type of the return value in method argument.

Example #3:

Notes prepared by _M$A_ : 8801114535. 25


PANKAJ SIR ACADEMY CORE JAVA

Example #4:

Example #5:

Q. What’s the difference between ‘return’ and ‘return value’ .? ***


A.
return return value
We can use return keyword inside void We can use return value statement inside
1. 1.
methods only. not a void method.
If a method is not a void then, writing
2. It’s optional to use inside method. 2.
return value is mandatory.
return keyword will transfer control to It will transfer control and value both to
3. 3.
method calling statement. the method calling statement.

Notes prepared by _M$A_ : 8801114535. 26


PANKAJ SIR ACADEMY CORE JAVA
Example #1:

Example #2: We cannot write anything after ‘return’, (unreachable code error):

If a method is not a void, then writing return value is mandatory.


Example #3:

Example: Multiple method arguments: the number of values, value’s data type and order should
match in method argument.

Notes prepared by _M$A_ : 8801114535. 27


PANKAJ SIR ACADEMY CORE JAVA

Example #2: multiple single data type values & single variable in method argument:

Notes prepared by _M$A_ : 8801114535. 28


PANKAJ SIR ACADEMY CORE JAVA
09/05/2022 (Monday)

In Java, a constructor is a block of codes similar to the method. It is called when an


object/instance of the class is created.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, constructor gets called.
It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.
Rules of JAVA Constructors:
• Constructors should have same name as that of Class.
• Constructors are permanently void.
• A Java constructor cannot be abstract, static, final, & cannot return any value.

Q. What’s the difference between “constructor” and “method” ?


A. Constructors are special methods, constructors are permanently void but methods can be
void & can not be void. Constructors are called only when object is created, methods are
called either with ClassName or after creating an object, ultimately both are methods only.

Example #1:

• Constructors are permanently void & can never return any value

Notes prepared by _M$A_ : 8801114535. 29


PANKAJ SIR ACADEMY CORE JAVA
Example #2: (Giving some value to x and printing)

Example #3: (multiple values)

CONSTRUCTOR OVERLOADING:
Here we create more than one constructor in same class provided they are different no.
of arguments & different type of arguments.

Example #1: (different no. of arguments)

Notes prepared by _M$A_ : 8801114535. 30


PANKAJ SIR ACADEMY CORE JAVA
Example #2: (different type of arguments)

Never use void or data type (int, char float etc..) while creating a constructor, If you do that
then it is a method and not a constructor.
Example #1:

Example #2:

Example #3:

Notes prepared by _M$A_ : 8801114535. 31


PANKAJ SIR ACADEMY CORE JAVA
10/05/2022 (Tuesday)

Default Constructors:

Every character has a Unicode value in numerical representation in Java.


For example:
a = 99
b = 98
c = 99 etc...

Class A { Byte Code:


Compiler 011011 Run Output
(JDK) (JRE)
}
File: A.java File: A.class

".java" file is compiled into ".class" file and ".class" file consist of byte code which we further run
".class" file to get the output.
If you are a developer, we install JDK which gives compiler and runtime environment.
If you are a customer, we install only JRE because we run only ".class" file. Whenever we create
an object, it has to mandatorily call constructor, if a constructor is not created explicitly by
developer, then during compilation automatically empty body constructor gets added in dot
".class" file. This is applicable only for no argument constructor and these constructors are called
as default constructors.
A.java A.class

When an object with argument is created and if matching constructor is missing in “.java” file
then it shows an error as shown in the below example:

Notes prepared by _M$A_ : 8801114535. 32


PANKAJ SIR ACADEMY CORE JAVA
When an object with argument is created & an object without argument is created in the same
program then the concept of default constructor is not applicable, hence the below programs
throws an error:

Notes prepared by _M$A_ : 8801114535. 33


PANKAJ SIR ACADEMY CORE JAVA
11/05/2022 (Wednesday)

“this” (keyword):

It’s a special reference variable that gets created automatically.

Obj Address

A a1 = new A (); this

Example:

Using “this” keyword we can access non-static members of class.


Example #2:

Example #3:

Notes prepared by _M$A_ : 8801114535. 34


PANKAJ SIR ACADEMY CORE JAVA
We cannot use “this” keyword inside static methods.
Example: #4

Example #5:

If we do not use “this” keyword inside non static method to access non static members then
during compile time “this” keyword gets appended automatically.
Example #6:

If there are multiple objects created then “This” keyword points to current object running in the
program.
Example #7:

Notes prepared by _M$A_ : 8801114535. 35


PANKAJ SIR ACADEMY CORE JAVA
Using “this” keyword we can access static members, but we should not do that.
Example#8:

Notes prepared by _M$A_ : 8801114535. 36


PANKAJ SIR ACADEMY CORE JAVA
12/05/2022 (Thursday)

“this” (keyword): (Contd...)

There are two usages of “this” keyword:


• this.memberName; (The member here is a non static member).
• this(); (It is used to call constructor but this call should happen from another constructor.
Example:

This is also called as constructor chaining.

Q. What is constructor chaining?


A. When we call one constructor from another constructor is called as constructor chaining.

While calling constructor from another constructor “this()” keyword should always be First
statement.
Example #1:

Example #2:

Notes prepared by _M$A_ : 8801114535. 37


PANKAJ SIR ACADEMY CORE JAVA
Example#3:

Notes prepared by _M$A_ : 8801114535. 38


PANKAJ SIR ACADEMY CORE JAVA
13/05/2022 (Friday)

The following are the Four Pillers of OOPs.


1. Inheritance
2. Polymorphism
3. Encapsulation
4. Abstraction

Inheritance: Here we inherit the members of parent class (super class) to child class with an
intension of re-using it. Example #1:

Example #2:

Notes prepared by _M$A_ : 8801114535. 39


PANKAJ SIR ACADEMY CORE JAVA
Example #3: (Inheritance between more than 2 class)

Note: At Class-level Java doesn’t support multiple inheritances, but at Interfaces-level it


supports multiple inheritances.

Parent 1 Parent 2
Class A
Class A Class B
Class B

Class C
Child
Class C Class D

NOT SUPPORTED IN JAVA SUPPORTED IN JAVA

Example:

Assignment
Watch YouTube Playlist by Pankaj Sir
Academy Chanel entitled
“Unary Operator in JAVA”
& Prepare notes.
Click below to watch on YouTube:

Click Here

Notes prepared by _M$A_ : 8801114535. 40


PANKAJ SIR ACADEMY CORE JAVA
14/05/2022 (Saturday) : Assignment – 1

In Java, the unary operator is an operator that can be used only with an operand. It is
used to represent the positive or negative value, increment/decrement the value by 1.

Unary Operator

Pre-Increment Post-Increment
Pre-Decrement Post- Decrement

• Post-Increment Examples
Example #1:

Example #2:

Example #3:

Notes prepared by _M$A_ : 8801114535. 41


PANKAJ SIR ACADEMY CORE JAVA

Example #4:

• Pre-Increment Examples
Example #1:

Example #2:

• Pre and post increments (both mixed) Examples


Example #1:

Notes prepared by _M$A_ : 8801114535. 42


PANKAJ SIR ACADEMY CORE JAVA
Example #2:

After understanding Increment concept, it’s easier to understand Decrement Concept, in


increment we increased the value by 1 but in decrement we will decrease the value by 1.

• Post-Decrement Examples
Example #1:

Example #2:

All mixed example:

Notes prepared by _M$A_ : 8801114535. 43


PANKAJ SIR ACADEMY CORE JAVA
18/05/2022 (Wednesday)

Packages in Java are nothing but folders created to store the programs in an organized
manner.
• A Package name cannot be a keyword.
• Don't give package name in UPPERCASE letters, encouraged to be given in
lowercase letters.
• If we want to use a class present in the same package then importing is not
required but if we are using a class that is present indifferent package then
importing that becomes mandatory.
Example:

When we create an object of “Class A” in “Class B” then they’re called as “Non-Sub Class”, when
we extend a class in same package then it’s called as “Sub-Class”.

Example: (non-sub class)

Example #2: (non-sub class)

Notes prepared by _M$A_ : 8801114535. 44


PANKAJ SIR ACADEMY CORE JAVA
Example: (sub class)

Example: (Creating a package in another way)

It creates three folders (p1,p2,p3) & class will be saved in “p3” folder.

Without using “import” keyword, importing can be done with (packageName.ClassName), see
the below Example:

Packages resolves naming convention problem in JAVA, that is we can create more than one
class in the same project provided packages are different as shown in the below example:

Notes prepared by _M$A_ : 8801114535. 45


PANKAJ SIR ACADEMY CORE JAVA
19/05/2022 (Thursday)

There are four types of access specifiers/modifiers in JAVA.

Access Specifier Private Default Protected Public


Same Class Yes Yes Yes Yes
Same Package (Sub Class) No Yes Yes Yes
Same Package (Non SubClass) No Yes Yes Yes
Different Package (SubClass) No No Yes Yes
Different Package (Non SubClass) No No No Yes

Examples on Private: Access Specifier


• If we make variable/method private, then it can be accessed only in same class but not
outside class.
Example #1: (same class)

Notes prepared by _M$A_ : 8801114535. 46


PANKAJ SIR ACADEMY CORE JAVA
Example #2: (same package, sub class)

Example #3: (same package, non sub class)

Example #4: (different package, sub class)

Notes prepared by _M$A_ : 8801114535. 47


PANKAJ SIR ACADEMY CORE JAVA
Example #5: (different package, non sub class)

Examples on Default: Access Specifier

• If we make variable/method default, then it can be accessed in same class, same package
but not in different packages.

Example #1: (same class)

Example #2: (same package, sub class)

Notes prepared by _M$A_ : 8801114535. 48


PANKAJ SIR ACADEMY CORE JAVA
Example #3: (same package, non sub class)

Example #4: (different package, sub class)

Example #5: (different package, non sub class)

Examples on Protected: Access Specifier

• If we make variable/method protected, then it can be accessed in same class, same


package & in different packages only via inheritance.

Example #1: (same class)

Notes prepared by _M$A_ : 8801114535. 49


PANKAJ SIR ACADEMY CORE JAVA
Example #2: (same package, sub class)

Example #3: (same package, non sub class)

Example #4: (different package, sub class)

Example #5: (different package, non sub class)

Notes prepared by _M$A_ : 8801114535. 50


PANKAJ SIR ACADEMY CORE JAVA

Examples on Public: Access Specifier

• If we make variable/method public, then it can be accessed everywhere.

Example #1: (same class)

Example #2: (same package, sub class)

Example #3: (same package, non sub class)

Example #4: (different package, sub class)

Notes prepared by _M$A_ : 8801114535. 51


PANKAJ SIR ACADEMY CORE JAVA
Example #5: (different package, non sub class)

Access Specifier on Class


A Class can never be private nor be protected, it can only be default and public.
If we make the Class default, then it can be accessed only in the same package and if we make
a class public then it can be accessed everywhere in the program.

Example: (default)

Example: (public)

Access Specifier on Constructors


If we make a constructor private, then it’s object cannot be created outside the Class. Ex:

If we make a constructor default, then it’s object can be created in same package but not
outside package. Example:

Notes prepared by _M$A_ : 8801114535. 52


PANKAJ SIR ACADEMY CORE JAVA
If we make a constructor protected, then it’s object can be created in same package but not in
different package, i.e same as default. Example:

If we make a constructor public, then it’s object can be created in same package and in different
package as well. Example:

Q. What is data hiding?


A. Here we make the variable private so that this variable cannot be accessed outside the class.
Data hiding is applicable only on variables and not on methods.

Assignment-2
Watch these YouTube Videos by
Pankaj Sir Academy Chanel.
Click to Watch:
IIB: Instance
Initialization Block

SIB: Static
Initialization Block

Notes prepared by _M$A_ : 8801114535. 53


PANKAJ SIR ACADEMY CORE JAVA
21/05/2022 (Saturday) Assignment-2

IIBs are executed when objects are created. No. of times we create the object, same no.
of times IIB will be called. IIBs are used to initialize all the instance (non static) variables in one
place, and that gives us better readability of the code.
Example #1: (No Output, because no object is created, IIB will not be called)

Example #2: (Object Created)

Example #3: (Object Created twice, no. of time we create object same no. of times IIB will be
called)

Example #4: (Creating one constructor with IIB & see which is called first)

Notes prepared by _M$A_ : 8801114535. 54


PANKAJ SIR ACADEMY CORE JAVA
Example #5:

Example #6:

Example #6: (Multiple IIBs)

Example #7:

Notes prepared by _M$A_ : 8801114535. 55


PANKAJ SIR ACADEMY CORE JAVA
We can initialize both static and non static variables inside an IIB.
Example #8:

Static Initialization Block (SIB) are created inside the class with the “static” keyword &
executed before main method, it runs only once, we need not create an object for SIB.
Example:

Example #2:

Example #3:

Notes prepared by _M$A_ : 8801114535. 56


PANKAJ SIR ACADEMY CORE JAVA
Example #4: (Multiple SIBs)

Example #5: (SIB can only initialize static variable, it cannot initialize non static variable)

Example: (IIB and SIB)

Example: (To understand the flow between SIB, IIB, Constructor and Main)

Notes prepared by _M$A_ : 8801114535. 57


PANKAJ SIR ACADEMY CORE JAVA
Example:

Example: (Object created in SIB)

Example: (multiple objects created, in SIB and Main)

Notes prepared by _M$A_ : 8801114535. 58


PANKAJ SIR ACADEMY CORE JAVA
Example: (With test method, IIB and Constructor after main method)

If we create an object inside IIB, we’ll not get any error but then the program will halt abruptly. Example:

Example: (multiple object in SIB)

Notes prepared by _M$A_ : 8801114535. 59


PANKAJ SIR ACADEMY CORE JAVA
20/05/2022 (Friday)

Polymorphism
If we develop the feature such that it can take more than one form depending upon the
situation.
Note: Polymorphism is applicable only on methods and not on variables.
There are two ways we can achieve polymorphism, they are:
i. Overriding
ii. Overloading
i. Overriding: here we inherit a method from the parent class and then we modify its logic
in the child class by once again creating a method in child class with same signature. Advantage
of overriding is, we can achieve modification of inherited method’s logic. Example:

Example #2:

Example #3:

Notes prepared by _M$A_ : 8801114535. 60


PANKAJ SIR ACADEMY CORE JAVA
To check whether overriding is happening or not we use “@Override” annotation. This
annotation instructs the compiler to report an error if there is a mis-match in signature.
Example:

Overriding method with arguments: in argument data type and number of arguments should
match, variableName can be anything. Example:

Example #2:

Example #3:

Notes prepared by _M$A_ : 8801114535. 61


PANKAJ SIR ACADEMY CORE JAVA
ii. Overloading: here we create more than one method in the same class with the same
name provided they have different no. of arguments or different type of argument. Example:

Q. Can we override static methods?


A. Static members are never inherited in Java.
In the below example during compilation “B.x” is converted into “A.x”, and hence it prints “0”.

Notes prepared by _M$A_ : 8801114535. 62


PANKAJ SIR ACADEMY CORE JAVA
23/05/2022 (Monday)

Encapsulation
Wrapping of data with the methods that operate on that data is called “Encapsulation”,
here we avoid direct access to the data by making that variable private. To operate on that
data, we create publicly defined “getters & setters”.
Example #1:

Example #2:

Example #3: (multiple variables)

Notes prepared by _M$A_ : 8801114535. 63


PANKAJ SIR ACADEMY CORE JAVA

An interface in Java is a blueprint of a class. It sets a protocol, designing standards etc…


An interface consists of only incomplete/abstract methods. Ex:

The relationship between classes and interfaces:


A class extends another class, an interface extends another interface, but a class
implements an interface.

Class extends Class

Interface extends Interface

Class implements Interface

Example #1: (Class-Interface)

Q. What do we achieve by using interface?


A. An interface in Java is a blueprint of a class. It sets a protocol, designing standards etc…
• It is used to achieve abstraction.
• By interface, we can support the functionality of multiple inheritance.
• It can be used to achieve loose coupling.

Notes prepared by _M$A_ : 8801114535. 64


PANKAJ SIR ACADEMY CORE JAVA
Example #2: Logics can be different but methods should be same.

Notes prepared by _M$A_ : 8801114535. 65


PANKAJ SIR ACADEMY CORE JAVA
24/05/2022 (Tuesday)

INTERFACE IN JAVA (Cntd...)

Example #3:

• Interfaces in JAVA supports multiple inheritance, Example:


Example #1:

Example #2:

Notes prepared by _M$A_ : 8801114535. 66


PANKAJ SIR ACADEMY CORE JAVA
Example #3: (Using extends and implements at the same time, but order should be first extends
then implements)

Q. Can I create static method in an interface?


A. Static members cannot be inherited.
In an interface incomplete static methods can not be developed hence the below program
throws an error. Ex:

“final” (keyword):
If we make a variable final then its value once initialized then cannot be changed. Ex:

If we make static/non static variable final, then it is mandatory to initialize these variables, auto
initialization will not happen.

Notes prepared by _M$A_ : 8801114535. 67


PANKAJ SIR ACADEMY CORE JAVA
If we make a class final then inheritance is not allowed, Ex:

If we make a method final then Overriding is not allowed, Ex:

Example: “final” convention (optional): Create variables in UPPERCASE.


Easy way to remember: If a variable is in Blue, Italics and Bold, It is final.

Notes prepared by _M$A_ : 8801114535. 68


PANKAJ SIR ACADEMY CORE JAVA
25/05/2022 (Wednesday)

Every variable that is created in an interface, by default it is final and static. Ex:

Reference variable of an interface can be created, but not object, Ex:

Here we can create parent reference variable and store child class object’s address into
it and it is termed as “Class Upcasting”.
Advantage: Reference variable can store all child class object’s addresses.
Example #1: (Upcasting between Interface & Class)

Example #2: (Upcasting between two Classes)

Notes prepared by _M$A_ : 8801114535. 69


PANKAJ SIR ACADEMY CORE JAVA

The following are the JAVA 8 new features:


• Functional Interface
• Lambda Expression
• “default” keyword
• Stream API
• Optional Class

Functional Interface: A functional interface can consist of exactly one incomplete method in it.
Annotation: “@FuctionalInterface”
Example:

(Ex: Error, No Method) (Ex: Error, Two Incomplete Methods)

(Ex: Error, Two complete Methods) (Ex: Correct, one Incomplete Method)

Lambda Expression: It reduces the lines of JAVA code, It can only be applied on Functional
Interface. In case of lambda expression, we don't need to create an object, implement or
Overriding, it does it all automatically. Here, we just write the implementation code. But the
drawback is, it makes the code less readable.
Example #1: (Without using Lambda Expression)

Notes prepared by _M$A_ : 8801114535. 70


PANKAJ SIR ACADEMY CORE JAVA
Example #1: (With Lambda Expression)

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

Example #2: (Method with arguments, Without using Lambda Expression)

Example #2: (Method with arguments, With Lambda Expression)

--------------------------------------------------------------------------------
Example #3: (Method with single arguments, Without using Lambda Expression)

Example #3: (Method with single arguments, With Lambda Expression & One line code in it)

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

Notes prepared by _M$A_ : 8801114535. 71


PANKAJ SIR ACADEMY CORE JAVA
26/05/2022 (Thursday)

JAVA 8 NEW FEATURES (Contd…)

“default” keyword: “default” keyword was introduced in JDK version 1.8 or JDK version 8. Using
“default’ keyword we can create complete methods inside an interface.
Note: A functional interface should consist exactly one incomplete method but can have any
number of complete methods in it. Example:

Example #2: (Using Lambda Expression with Incomplete & Complete methods in)

In an interface we can add main method and can run like a class as shown in the below example,
it was not possible in JAVA Version 7:

We can also develop complete static methods in an interface, incomplete and static is not
allowed. see the below Example:

Notes prepared by _M$A_ : 8801114535. 72


PANKAJ SIR ACADEMY CORE JAVA

Abstraction (Incompletion)
Q . What is Abstraction in JAVA?
A. Hiding of implementation details is called as “abstraction” & the way we achieve that in JAVA
is by using Interfaces and Abstract Class.

“abstract” keyword: It helps us to define incomplete methods & incomplete classes. To develop
incomplete methods in interface usage of “abstract” keyword is optional. Example:

Abstract Class: An abstract class can be 0-100% incomplete, it can consist of a constructor, it
can consist of static and non static members, we can create main method in an abstract class,
but object of abstract class cannot be created. Example:

Assignment -3

Watch this YouTube Video by


Pankaj Sir Academy Chanel, entitled
“super” keyword.
Click to Watch:

“super”
keyword
Notes prepared by _M$A_ : 8801114535. 73
PANKAJ SIR ACADEMY CORE JAVA
27/05/2022 (Friday)

“super” Keyword
Using “super” keyword w can access the members of parent class.
Example #1:

Example #2:

Using “super” keyword we can access static and non static members both. Example:

“super’ keyword cannot be used inside static context. Example:

Using “super” keyword, we can call constructor of parent class but then we should use “super”
keyword in child class constructor and it should be very first statement. Example:

Notes prepared by _M$A_ : 8801114535. 74


PANKAJ SIR ACADEMY CORE JAVA
Constructor call from 2nd statement, Error

If we don’t keep “super” keyword inside child class constructor then compiler will
automatically place the “super” keyword, such that it can call only no args constructor of
parent class. Example:

If we don’t create child class constructor with argument, then compiler will automatically
place no args constructor with “super” keyword. Example:

Every child class constructor automatically creates “super” keyword. Example:

Example: (with arg constructor)

If in the parent class there’s only constructors with argument then as a programmer we
should explicitly write “super” keyword in child class constructor. Example:

Notes prepared by _M$A_ : 8801114535. 75


PANKAJ SIR ACADEMY CORE JAVA

“super” keyword is not automatically kept when there are only constructors with arguments in
parent class, whereas super keyword will be placed automatically in all the child class
constructors when in the parent class there’s a constructor with no arguments. Example:

We cannot use “this” keyword and “super” keyword in the same constructor to call another
constructor as either of the statements becomes 2nd statement then we’ll get an error. Ex:

If child class constructor consist of “this” keyword then in that constructor “super” keyword
will not be automatically placed. Example:

Notes prepared by _M$A_ : 8801114535. 76


PANKAJ SIR ACADEMY CORE JAVA
27/05/2022 (Friday)

OOPs CONCEPT: ABSTRACTION (Contd…)

Abstract class doesn’t support multiple inheritance, Ex:

Example: (Inheritance from Abstract class to Java class)

Points to remember:
• When Inheriting from an abstract Class @Override & Complete.
• If there’s a non static member in abstract class, we can inherit & access that.
• If it is static we can directly access with class name.

Q. Difference between Interface and Abstract Class?


A.
Interface Abstract Class
Abstract Classes can be 0-100%
1. Interfaces are 100% incomplete. 1.
incomplete.
2. Supports multiple Inheritance. 2. Doesn’t support multiple Inheritance.
All variables by default are static and Here we can create static/non static
3. 3.
final. variables

Notes prepared by _M$A_ : 8801114535. 77


PANKAJ SIR ACADEMY CORE JAVA

Q. What is exception in JAVA?


A. Whenever a bad user input is given, it will halt the program execution abruptly. This is called
as “exception”.
Example:

EXCEPTION HANDLING

To handle exception in JAVA, we use Try Catch Block, if an exception occurs in try block,
then try block automatically creates an exception object & gives that object’s address to catch
block. Catch block will now suppress the exception and the further code from there will continue
to run.

Example:

Notes prepared by _M$A_ : 8801114535. 78


PANKAJ SIR ACADEMY CORE JAVA
To know the exact line number where exception has occurred, then instead of using
“System.out.println(e);” we use “e.printStackTrace();”, Example:

Types of Exceptions

There are mainly 2 types of exceptions, RUNTIME EXCEPTION and COMPILE TIME EXCEPTION

Class A { Byte Code:


Compile 011011 Run Output
Time Time
}
File: A.java File: A.class

CompileTime/Checked RunTime/UnChecked
Exception Exception

CompileTime/Checked Exception: These exceptions will occur at compile time (when “.JAVA”
file is compiled to “.CLASS” file). These exceptions cannot simply be ignored at the time of
compilation, the programmer should take care of (handle) these exceptions.
For example, if we use FileReader class in the program to read data from a file, if the file
specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler
prompts the programmer to handle the exception, see the below example:

Notes prepared by _M$A_ : 8801114535. 79


PANKAJ SIR ACADEMY CORE JAVA
RunTime/UnChecked Exception: These exceptions occurs when we run “.CLASS” file. These
include programming bugs, such as logic errors or improper use of an API. Runtime exceptions
are ignored at the time of compilation. See the below example:

Q. Difference between CompileTime and RunTime Errors?


A.
CompileTime/Checked RunTime/UnChecked
The runtime errors are the errors which
The compile-time errors are the errors
are not generated by the compiler and
1. which are produced at the compile-time, 1.
produce an unpredictable result at the
and they are detected by the compiler.
execution time.
In this case, the compiler prevents the In this case, the compiler does not
2. code from execution if it detects an error 2. detect the error, so it cannot prevent the
in the program. code from the execution.
It contains the syntax and semantic It contains the errors such as division by
3. errors such as missing semicolon at the 3. zero, determining the square root of a
end of the statement. negative number.

Notes prepared by _M$A_ : 8801114535. 80


PANKAJ SIR ACADEMY CORE JAVA
30/05/2022 (Monday)

EXCEPTION CLASS HIERARCHY IN JAVA

Q. What are Exception Class Hierarchy in JAVA?


A.

Throwable

Error Exception

RunTime/UnChecked CompileTime/Checked
Exception Exception

ArithmeticException FileNotFoundException

NumberPointerException I/O Exception

NullPointerException SQL Exception

ArrayIndexOutOfBoundException ClassNotFoundException

StringIndexOutOfBoundException ClonedNotSupportedException

ClassCastException

Notes prepared by _M$A_ : 8801114535. 81


PANKAJ SIR ACADEMY CORE JAVA
31/05/2022 (Tuesday)

EXCEPTION CLASS HIERARCHY IN JAVA (Contd…)


RunTime Exception

ArithmeticException: This class can handle ArithmeticExcpetion like dividing a number by zero.
Ex:

NumberFormatException: When an invalid String to number conversion is done we get


NumberFormatException as shown in below example:

Example: Conversion String to Float

Notes prepared by _M$A_ : 8801114535. 82


PANKAJ SIR ACADEMY CORE JAVA
Example: Conversion String to boolean

NullPointerException: When we access non static member with null reference variable we get
“NullPointerException” as shown in the below example:

We can also get result with just writing “Exception e” in catch block, Example:

Q. What’s the difference between using “Exception” class & “NumberFormatException” class
in catch block?
A. When we use NumberFormatException class in catch block, then it can handle only
NumberFormatException, but if we use Exception class in catch block, then it can handle all the
Exceptions that occur in try block.

Notes prepared by _M$A_ : 8801114535. 83


PANKAJ SIR ACADEMY CORE JAVA

Loops are used to repeat a block of code, for example, if we want to show a message
100 times, then rather than typing the same code 100 times, we can use a loop.
There are mainly 3 types of Loops:
1. For loop
2. While loop
3. Do-While loop

For Loop: In JAVA for loop is used to run a block of code for a certain number of times.

Example #1:

Example #2:

Notes prepared by _M$A_ : 8801114535. 84


PANKAJ SIR ACADEMY CORE JAVA
Example #3:

“break” Keyword

“break” Keyword is used to terminate the “loops” and “switch statements” in java. When
the break keyword is used within a loop, the loop is immediately terminated and the program
control goes to the next line of codes after the loop. Example:

Labelled Break: Break keyword will always exit “for block”, but with labelled break we can specify
which block to exit in the loop, “for block” or “if block”.

For block

If block

Notes prepared by _M$A_ : 8801114535. 85


PANKAJ SIR ACADEMY CORE JAVA
Example #1: (Exiting “if block”)

Example #2: (Exiting “for block”)

Notes prepared by _M$A_ : 8801114535. 86


PANKAJ SIR ACADEMY CORE JAVA
01/06/2022 (Wednesday)

“Continue” Keyword
The “continue” keyword is used to end the current iteration (repetition) in a for loop (or
a while loop), and continues to the next iteration (repetition). Example:

If and Else Statements: The Java if statement tests the condition. It executes the “if block” if
condition is true, otherwise “else” block is executed. Example:

Else-if Statement: The Java if statement tests the “if block” condition, if it is false the control
goes to “Else-If block”, If it is true it prints it’s value, if not it prints “else block” value.
Note: we can have multiple Else-if statements. Example:

Notes prepared by _M$A_ : 8801114535. 87


PANKAJ SIR ACADEMY CORE JAVA
Switch Statement: The switch statement tests the equality of a variable against multiple values.
Points to Remember:
• There can be one or any number of case values for a switch expression.
• Each case statement can have a break statement which is optional. When control
reaches to the break statement, it jumps the control after the switch expression. If a
break statement is not found, it executes the next case.
• The case value can have a default label which is optional.
Example #1:

Example #2: (If No value found in switch statements)

Example #3: (If No break given)

Notes prepared by _M$A_ : 8801114535. 88


PANKAJ SIR ACADEMY CORE JAVA
LOOPS IN JAVA (Contd…)

While Loop: The while loop is used to repeat a section of code n number of times until a specific
condition is met.

Example #2: (If the condition is false, it prints nothing)

Do While Loop: Java do-while loop is called an exit control loop. Therefore, unlike while loop
and for loop, the do-while check the condition at the end of loop body. Example:

Example #2:

Notes prepared by _M$A_ : 8801114535. 89


PANKAJ SIR ACADEMY CORE JAVA

The Scanner class is used to get user input, and it is found in the java.util package.
To use the Scanner class, create an object of the class and use any of the available methods
found in the Scanner class documentation. In our example, we will use the nextLine() method,
which is used to read Strings. Example:

The previous program cannot take two words, If your name is “Mike Tyson” it can only print
Mike, the next example shows how to take multiple word string values.

Example #2:

Example #3:

Notes prepared by _M$A_ : 8801114535. 90


PANKAJ SIR ACADEMY CORE JAVA
02/06/2022 (Thursday)

Java array is an object which contains elements of a similar data type. Additionally, the
elements of an array are stored in a contiguous memory location. It is a data structure where
we store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on 1st index and so on.

A Java array variable can also be declared like other variables with [] after the data type.
Advantages:
• Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
• Random access: We can get any data located at an index position.

Represents
array
0
Array
int[] arr = new int[3]; Index Object
Of Array
1
Data Variable No. of
Type name elements
(Stores
Object
in array 2
Address)

Notes prepared by _M$A_ : 8801114535. 91


PANKAJ SIR ACADEMY CORE JAVA

EXCEPTION: RunTime/UnChecked: ArrayIndexOutOfBoundsException


Ex: There's only 3 Indexes (0,1,2) if we print 3, it gives "ArrayIndexOutOfBoundsException"

Example #3: Let’s suppose there are 100s of elements in an array, instead of writing
“System.out.println(arr[#]);” 100 times we can use here “Loop”. Example:

Example #4: Instead of writing “i<3;” in loop condition we can write “i<arr.length;” it will
automatically take the length of array.

Example #5: in array If we don’t initialize the value, depending upon the data type it will print
default value, here int default value is “0”.

Notes prepared by _M$A_ : 8801114535. 92


PANKAJ SIR ACADEMY CORE JAVA
Example #5: (String Value, Default String Value = null)

Example #6: (Float value, Default Float value = 0.0)

Example #7: (char value, Default value value = Empty Space)

Example #8: (foreach loop prints array’s each value with just a single statement, it will run
automatically depending upon the size of an array’s elements), Advantage: We are not worried
about how many time loops will repeat.

Notes prepared by _M$A_ : 8801114535. 93


PANKAJ SIR ACADEMY CORE JAVA

Example #9: (With String)

DYNAMIC ARRAY IN JAVA


The dynamic array is a variable size list data structure. It grows automatically when we
try to insert an element if there is no more space left for the new element. It allows us to add
and remove elements.

Notes prepared by _M$A_ : 8801114535. 94


PANKAJ SIR ACADEMY CORE JAVA
03/06/2022 (Friday)

REMOVING DUPLICATE ELEMENTS

Array Index 0 1 2 3 4 5 6
x 1 1 2 3 3 4 5

Temp 1 2 3 4 5 0 0

In the above example there’s a set of elements which is already sorted in ascending
order, we’re removing duplicate elements from that array.
Let’s suppose x=given array which have 7 elements (array index: 0 to 6), first create same
size of a temp array, comapre x array index 0 & 1 if the elements are different copy the element
in temp array here the element values are same so we’re not copying 1, then compare 1 & 2
here the the elements are different so we’re copying 1 into temp array, next compare 2 & 3,
value is different copy that into temp array, likewise all the elements should be done, & the left
over indexes in temp array should be filled with zeros.
See the below examples:
Example #1: (with error: ArrayIndexOutOfBoundsException):

Let’s correct it in below example & further copying the elemnt into temp array.
Example #2:

The last value of x array (which is 5) is not copied because there were no further elements to
compare with, so let’s copy the last element as it is into temp.
Notes prepared by _M$A_ : 8801114535. 95
PANKAJ SIR ACADEMY CORE JAVA
Example #3:

But as we know there were two duplicate elements so after removing them we got two default
int values in place of those elements, so let’s remove the zeros.

SWAPPING IN JAVA
Swapping two variables refers to mutually exchanging the values of the variables.
Generally, this is done with the data in memory. The simplest method to swap two variables is
to use a third temporary variable. Example:

Notes prepared by _M$A_ : 8801114535. 96


PANKAJ SIR ACADEMY CORE JAVA
04/06/2022 (Saturday)

SORTING AN ARRAY IN JAVA


The sorting is a way to arrange elements of a list or array in a certain order. The order
may be in ascending or descending order. The numerical and lexicographical (alphabetical)
order is a widely used order.
0 1 2 3 4
23 32 14 38 7

Let’s take an example of bubble sorting order, here we’ll compare neighbouring values
& check if the 1st value is greater than 2nd, if true we’ll swap, if false, will keep as it is & compare
next values.
Round #1 Round #2 Round #3
0 1 2 3 4 0 1 2 3 4 0 1 2 3 4
23 32 14 38 7 23 14 32 7 38 23 14 7 32 38

23 32 14 38 7 14 23 32 7 38 14 23 7 32 38

23 14 32 38 7 23 14 32 7 38 14 7 23 32 38

23 14 32 38 7 23 14 7 32 38 14 7 23 32 38

23 14 32 7 38 23 14 7 32 38 14 7 23 32 38

Round #4
0 1 2 3 4
14 7 23 32 38

7 14 23 32 38

7 14 23 32 38

7 14 23 32 38

7 14 23 32 38

SizeOfArray-1=NoOfRounds.
Here it took 4 rounds to sort this array, If the array is of 100 size then it will take 99
rounds.

Notes prepared by _M$A_ : 8801114535. 97


PANKAJ SIR ACADEMY CORE JAVA
Example:

Here it ran only 1 round, we need to run it four times, for that purpose we’re using nested for
loop (for loop inside for loop) here.

The above array is sorted.

Notes prepared by _M$A_ : 8801114535. 98


PANKAJ SIR ACADEMY CORE JAVA
08/06/2022 (Wednesday)

2D – ARRAY
The Two Dimensional Array in Java programming language is nothing but an Array of
Arrays. In Java Two Dimensional Array, data stored in row and columns, and we can access the
record using both the row index and column index (like an Excel File).

0 1 2 3
0 (0,0) (0,1) (0,2) (0,3)
1 (1,0) (1,1) (1,2) (1,3)
2 (2,0) (2,1) (2,2) (2,3)
2 Square
Brackets
Column Index
Indicate
2D Array

Row Index
int[][] arr = int[3][4];

Variable No No
Name Of Of
Rows Columns

Example Output
package p1; 3
public class A { 4
public static void main(String[] args) {
int[][] arr = new int[3][4];
System.out.println(arr.length); //To check no. of rows
System.out.println(arr[0].length); //To check no. of columns
}
}

Example #2:

Notes prepared by _M$A_ : 8801114535. 99


PANKAJ SIR ACADEMY CORE JAVA

In Java, with the help of File Class, we can work with files. This File Class is inside the
java.io package. The File class can be used by creating an object of the class and then
specifying the name of the file.

Q. Why File Handling is Required?


A. File Handling is an integral part of any programming language as file handling enables us
to store the output of any particular program in a file and allows us to perform certain
operations on it.
In simple words, file handling means reading and writing data to a file.

Exists Method: It is non static method present in File Class, the return type of this method is
aboolean value. This method will check whether the file exists in the given path, if the file exists
it will true or else false. Example:

If we want to check the return type, we can also use the exists method like below example:

Notes prepared by _M$A_ : 8801114535. 100


PANKAJ SIR ACADEMY CORE JAVA
Delete Method: It is a non static method present in file class, whose return type is a boolean
value, if the file/folder is deleted it will return true or else false. Example:

Create A New File Method: It is a non static method in file class, in the given path if the file is
not present, then only it will create a new file & return the boolean value as true, if file already
exists then it will not create a file neither override or replace the file & will return as false.

There’s nothing wrong here, still we get CompileTime/Checked Exception, in such situations
its’s a rule that we should mandatorily surround it with “try catch” block or else the program
will not run.

Notes prepared by _M$A_ : 8801114535. 101


PANKAJ SIR ACADEMY CORE JAVA
Make Directory (Folder) Method: It is a non static method present in file class, if the folder
doesn’t exist in the given path it will create a new folder & return the boolean value as true or
else false. Example:

Delete Directory (Folder) Method: we use same method “f.delete()” for deleting file as well as
folder.

Notes prepared by _M$A_ : 8801114535. 102


PANKAJ SIR ACADEMY CORE JAVA
09/06/2022 (Thursday)

FILE HANDLING IN JAVA (Contd…)

List Method: It’s a non static method present in File Class, it will get all the file/folder names
present in the given path & the return type of this method is String Array.
Let’s first check the Files and folders present in the path:

Example:

Length Method: It’s a non static method present in File Class, it counts the number of characters
in the given file including spaces.
First let’s check what’s present in test.text file: “Pankaj Sir Academy” (18 Characters)

Example:

Notes prepared by _M$A_ : 8801114535. 103


PANKAJ SIR ACADEMY CORE JAVA

FILE READER IN JAVA

Read Method: It’s a non static method present in FileReader Class, It is used to read and return
a single character in the form of an integer value that contains the character’s unicode value,
then integer value is converted to char. The FileReader Class doesn’t have legnth method, so
we use File Class to make the output dynamic.
Let’s read the data present in test.txt.

In the above example it read only “m” of “mike” in the integer form, to make it read all the
characters we print System.out.println = no. of characters present in file.

Notes prepared by _M$A_ : 8801114535. 104


PANKAJ SIR ACADEMY CORE JAVA
Let’s convert the integer value into character.

We cannot increase line of codes to print each character, so here we’re using for loop

To get the character values in a single line, let’s remove “ln” from System.out.println

Here in for loop condition (for (int i=0; i<4; i++) {) we gave i<4, because mike has 4
characters & we want the for loop to run till 3 which is less than 4. But we cannot keep giving
the condition based upon the character length, & FileReader Class cannot count the length, to
automate this we’ll use File Class to count the length of the characters. Example:

Notes prepared by _M$A_ : 8801114535. 105


PANKAJ SIR ACADEMY CORE JAVA
The character present in test.txt file:

Example:

There’s an another way to to read the text file by making char array, example:

FILE WRITER IN JAVA


Write Method: It’s a non static method present in FileWriter Class, by default it will override
the existing file or if the file doesn’t exists it will create a new file. To avoid overriding of the
file we type a boolean value “true” after the file path. Example:

Notes prepared by _M$A_ : 8801114535. 106


PANKAJ SIR ACADEMY CORE JAVA
Let’s write “mike” into the file, after writing always use close() method to save and close the
file, if we don’t close it, it wont write anything in the file. Example:

Let’s run the code again:

It wrote the “Mike” once again without overriding the file, due to the “true” written after path.
Now we’re writing the “false” after path, Example:

Notes prepared by _M$A_ : 8801114535. 107


PANKAJ SIR ACADEMY CORE JAVA

It replaced (overrode) the file with new one.

Example: (writing int value to the file without double quotes)

It wrote 97’s coreesponding char value “a” after “Mike”, so always write anything (int, char,
boolean etc..) in double quotes “” (String value) to write into the text files.

Another way to write into the file. Example:

Notes prepared by _M$A_ : 8801114535. 108


PANKAJ SIR ACADEMY CORE JAVA

Task Assignment
Watch recorded lectures from
Pankaj Sir Academy App

Batch > Recorded Series Part 1


Lectures: 28/10/2020 to 04-11-2020 (9 videos)

Batch > Recorded Series Part 2


Lectures: 05/11/2020 to 20-11-2020 (18 videos)

Notes prepared by _M$A_ : 8801114535. 109


PANKAJ SIR ACADEMY CORE JAVA
10/06/2022 (Friday)

BUFFERED READER AND WRITER IN JAVA

Buffered Reader:
• It improves file reading performance
• It has an exclusive readLine() method that reads the content line by line.

File Content:

Example:

Example #2:

Notes prepared by _M$A_ : 8801114535. 110


PANKAJ SIR ACADEMY CORE JAVA
Example #3: (To read all the content from a text file, using while loop)

Buffered Writer:
• It improves file writing performance
• It has an exclusive newLine() method that writes the content in new line.
Example:

Output:

Notes prepared by _M$A_ : 8801114535. 111


PANKAJ SIR ACADEMY CORE JAVA
To write in a new line we insert newLine() method. Example:

Output:

Q. What is Serialization and De-Serialization.?

Notes prepared by _M$A_ : 8801114535. 112


PANKAJ SIR ACADEMY CORE JAVA

All the objects we create in java are stored in RAM (Heap Memory) which is a temporary
memory, to store it permanently in .ser file we use Serialization and De-Serialization.
In serialization we convert the object in zeros and ones and then store the object state
in permanantly in file.
In de-serialization we read binaries from the file and reconstruct the object back.

Example:

OutPut:

Q. What is marker interface?


A. An empty interface is called as Marker Interface.

Notes prepared by _M$A_ : 8801114535. 113


PANKAJ SIR ACADEMY CORE JAVA
13/06/2022 (Monday)

DE-SERIALIZATION
Q. What is ObjectClass in JAVA?
A. The super most class in JAVA is called as ObjectClass in JAVA.

Example:

“transient” (keyword):
During Serialization “transient” keyword when applied on a variable, it will skip writing into the
object.
Example:

Notes prepared by _M$A_ : 8801114535. 114


PANKAJ SIR ACADEMY CORE JAVA

JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute
the query with the database. JDBC API uses JDBC drivers to connect with the database.
We can use JDBC API to access tabular data stored in any relational database. By the help of
JDBC API, we can save, update, delete and fetch data from the database.
There are lot of database softwares, but most popular ones are:

We can use any one, but here we are using MySQL.

Example#1: (we’re creating one Registration table in MySQL to store the data)
create my_db
use my_db
create table Registration
(
Name varchar(45),
City varchar(45),
Email varchar(128),
MobileNumber varchar(10)
)
select * from Registration
-- * means select all the columns in the table, we can also give column name
insert into Registration values('Sayyed', 'Hyderabad', '672msa@gmail.com', '1234567890')
-- I ran it twice, so it saved the data twice in the Registration table
insert into Registration values('Mike', 'Chennai', 'mike@gmail.com', '0123456789')
insert into Registration values('Michael', 'Tamil Nadu', 'michael@gmail.com', '1111111111')
insert into Registration values('Banty Bablu', 'Kerala', 'banty@gmail.com', '2222222222')

Result Grid:
Name City Email MobileNumber
Sayyed Hyderabad 672msa@gmail.com 1234567890
Sayyed Hyderabad 672msa@gmail.com 1234567890
Mike Chennai mike@gmail.com 0123456789
Michael Tamil Nadu michael@gmail.com 1111111111
Banty Bablu Kerala banty@gmail.com 2222222222

Notes prepared by _M$A_ : 8801114535. 115


PANKAJ SIR ACADEMY CORE JAVA
14/06/2022 (Tuesday)

JAVA DATABASE CONNECTIVITY – JDBC (Contd…)


To connect to the database we require a JDBC Driver. The JDBC Driver is a software
component that enables java application to interact with the database.

There are 4 types of JDBC drivers:


1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
To connect to our MySQL database, we are using a JDBC Driver called “MySQL Connector/J”,
MySQL Connector/J is a JDBC Type 4 driver, the Type 4 designation means that the driver is a
pure Java implementation of the MySQL protocol and does not rely on the MySQL client
libraries.

Download Link for MySQL Connector/J:


https://dev.mysql.com/get/Downloads/Connector-J/mysql-connector-java-8.0.29.zip

After extracting the .zip file we’re copying the “mysql-connector-java-8.0.29.jar” file into our
JAVA Project.
Create a new folder in JAVA Project named “lib” & paste the “mysql-connector-java-8.0.29.jar”
into that folder.

After pasting configure the .jar file to the Java project, to do that go to:
JAVAProject>Properties>Java Build Path>Libraries>Add JARs>Select “mysql-connector-java-
8.0.29.jar”.

Notes prepared by _M$A_ : 8801114535. 116


PANKAJ SIR ACADEMY CORE JAVA

Example #1: JDBC code to connect with MySQL database:


package jdbc_demo;
import java.sql.Connection;
import java.sql.DriverManager; //It's built in method to connect to database
//make java code connect to database
public class A {
public static void main(String[] args) {
try {
//3 pararameters to connect to database. URL, UserName, Password
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_db", "root", "Test");
System.out.println(con);
} catch (Exception e) {
e.printStackTrace();
}
}
}
----------------------------------------------------------------------------------------------------------------------------------------
Output:
com.mysql.cj.jdbc.ConnectionImpl@780cb77

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

port No. username


database

("jdbc:mysql://localhost:3306/my_db", "root", "Test")

JDBC location Database password


Technique name

Notes prepared by _M$A_ : 8801114535. 117


PANKAJ SIR ACADEMY CORE JAVA
Example #2: Code to store/insert record in database:
package jdbc_demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class A {
public static void main(String[] args) {
try {

//Make java code connect to database:


Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/my_db", "root", "Test");
System.out.println(con);

//Code to store/insert record into database:


Statement st = con.createStatement();
st.executeUpdate
("insert into Registration values('Stallin', 'Chicago', 'stallin@gmail.com', '1084658760')");

//close database connection


con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
----------------------------------------------------------------------------------------------------------------------------------------
Output:
com.mysql.cj.jdbc.ConnectionImpl@780cb77

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

Result Grid in MySQL:


Name City Email MobileNumber
Sayyed Hyderabad 672msa@gmail.com 1234567890
Sayyed Hyderabad 672msa@gmail.com 1234567890
Mike Chennai mike@gmail.com 0123456789
Michael Tamil Nadu michael@gmail.com 1111111111
Banty Bablu Kerala banty@gmail.com 2222222222
Stallin Chicago stallin@gmail.com 1084658760

Notes prepared by _M$A_ : 8801114535. 118


PANKAJ SIR ACADEMY CORE JAVA
Example #3: Code to delete the record from database:

We can delete record based on Name, City, Email, MobileNumber, here we’re using deletion
based on Email, because Email and Mobile Numbers are always unique, but if we delete based
on Name, City there might be multiple entries with the Name/City, all will be deleted.
package jdbc_demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class A {
public static void main(String[] args) {
try {

//Make java code connect to database:


Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/my_db", "root", "Test");
System.out.println(con);

//Code to delete record from database: deleting Mike's Data


Statement st = con.createStatement();
st.executeUpdate
("DELETE FROM Registration WHERE Email='mike@gmail.com'");

//close database connection


con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
----------------------------------------------------------------------------------------------------------------------------------------
Output:
com.mysql.cj.jdbc.ConnectionImpl@780cb77

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

Result Grid in MySQL:


Name City Email MobileNumber
Sayyed Hyderabad 672msa@gmail.com 1234567890
Sayyed Hyderabad 672msa@gmail.com 1234567890
Michael Tamil Nadu michael@gmail.com 1111111111
Banty Bablu Kerala banty@gmail.com 2222222222
Stallin Chicago stallin@gmail.com 1084658760

Notes prepared by _M$A_ : 8801114535. 119


PANKAJ SIR ACADEMY CORE JAVA
Example #4: Code to update the record in database:
package jdbc_demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class A {
public static void main(String[] args) {
try {

//Make java code connect to database:


Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/my_db", "root", "Test");
System.out.println(con);

//Code to update in database: updating Stalli's City from "Chicago" to "NYC"


Statement st = con.createStatement();
st.executeUpdate
("UPDATE Registration SET City = 'NYC' WHERE email='stallin@gmail.com'");

//close database connection


con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
----------------------------------------------------------------------------------------------------------------------------------------
Output:
com.mysql.cj.jdbc.ConnectionImpl@780cb77

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

Result Grid in MySQL:


Name City Email MobileNumber
Sayyed Hyderabad 672msa@gmail.com 1234567890
Sayyed Hyderabad 672msa@gmail.com 1234567890
Michael Tamil Nadu michael@gmail.com 1111111111
Banty Bablu Kerala banty@gmail.com 2222222222
Stallin NYC stallin@gmail.com 1084658760

Notes prepared by _M$A_ : 8801114535. 120


PANKAJ SIR ACADEMY CORE JAVA
15/06/2022 (Wednesday)

JAVA DATABASE CONNECTIVITY – JDBC (Contd…)


Example #5: Code to read the data in database:
package jdbc_demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class D {
public static void main(String[] args) {
try {
//Make java code connect to database:
Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/my_db", "root", "Test");
System.out.println(con);
//Code to read the data in database: (we use executeQuery in place of executeUpdate
Statement st = con.createStatement();
ResultSet result = st.executeQuery
("select * from Registration"); //collection of values
while(result.next()) {
System.out.println(result.getString(1)); //Column#1 = Name's column
System.out.println(result.getString(2)); //Column#2 = City's column
System.out.println(result.getString(3)); //Column#3 = Email's column
System.out.println(result.getString(4)); //Column#4 = MobileNumber's column
}
//close database connection
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
----------------------------------------------------------------------------------------------------------------------------------------
Output:
com.mysql.cj.jdbc.ConnectionImpl@780cb77
Sayyed
Hyderabad
672msa@gmail.com
1234567890
Sayyed
Hyderabad
672msa@gmail.com
1234567890
Michael
Tamil Nadu
michael@gmail.com
1111111111
Banty Bablu
Kerala
banty@gmail.com
2222222222
Stallin
NYC
stallin@gmail.com
1084658760

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

Notes prepared by _M$A_ : 8801114535. 121


PANKAJ SIR ACADEMY CORE JAVA
Getting the output of the above code in an organised way:
package jdbc_demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class D {
public static void main(String[] args) {
try {
//Make java code connect to database:
Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/my_db", "root", "Test");
System.out.println(con);
//Code to read the data in database: (we use executeQuery in place of executeUpdate
Statement st = con.createStatement();
ResultSet result = st.executeQuery
("select * from Registration"); //collection of values
while(result.next()) {
System.out.print(result.getString(1) + "," + " "); //Column#1 = Name's column
System.out.print(result.getString(2) + "," + " "); //Column#2 = City's column
System.out.print(result.getString(3) + "," + " "); //Column#3 = Email's column
System.out.print(result.getString(4) + " "); //Column#4 = MobileNumber's column
System.out.println(""); //just to get the output in next line
//close database connection
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
----------------------------------------------------------------------------------------------------------------------------------------
Output:
com.mysql.cj.jdbc.ConnectionImpl@780cb77
Sayyed, Hyderabad, 672msa@gmail.com, 1234567890
Sayyed, Hyderabad, 672msa@gmail.com, 1234567890
Michael, Tamil Nadu, michael@gmail.com, 1111111111
Banty Bablu, Kerala, banty@gmail.com, 2222222222
Stallin, NYC, stallin@gmail.com, 1084658760

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

Task Assignment

Watch recorded JDBC lecture from


Pankaj Sir Academy App
Batch > Recorded Series Part 2
Lectures: 10/11/2021 to 11-11-2021
To cover “.jar file concept”

Notes prepared by _M$A_ : 8801114535. 122


PANKAJ SIR ACADEMY CORE JAVA

CRUD OPERATIONS
As a developer every application involves CRUD Operations.
Q. What is CRUD Operations?
A. The abbreviation CRUD stands for Create, Read, Update, and Delete in computer
programming.

In MySQL we use “executeUpdate()” method to Create, Update and Delete the data in database,
and “executeQuery()” method to read the data from the database.

MULTIPLE CATCH BLOCK IN TRY-CATCH BLOCK


Q. Can we create more than one catch block in Try-Catch?
A. Yes, we can create multi catch blocks but we should always start with child class exceptions
followed by parent class, the matching catch block will be called first, if none of the catch block
matches with the exception then the parent class exception automatically handles it.
Note: In place of Exception class, we can also give its parent class Throwable, it can also handle
all kinds of Exceptions.

Example #1: (Child first then parent class exception, No Error)

Notes prepared by _M$A_ : 8801114535. 123


PANKAJ SIR ACADEMY CORE JAVA
Example #2: (parent class first then child exception, Error)
Error Message: Unreachable catch block for NullPointerException. It is already handled by the
catch block for Exception

Example #3: (Creating ArithmeticException)


package p1; //Multiple catch block in try-catch
public class A {
public static void main(String[] args) {
try {
int x = 10/0; //It's an arithmetic exception
} catch (ArithmeticException e) {
System.out.println("This result is from ArithmeticException");
} catch (NullPointerException e) {
System.out.println("This result is from NullPointerException");
} catch (Exception e) {
System.out.println("This result is from Exception");
}
}
}
----------------------------------------------------------------------------------------------------------------------------------------
Output:
This result is from ArithmeticException

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

Example #4: (Creating NullPointerException)


package p1; //Multiple catch block in try-catch
public class A {
int x =10;
public static void main(String[] args) {
try {
A a1 = null;
System.out.println(a1.x); //It's a NullPointerException, control goes to Line#10
} catch (ArithmeticException e) {
System.out.println("This result is from ArithmeticException");
} catch (NullPointerException e) {
System.out.println("This result is from NullPointerException");
} catch (Exception e) {
System.out.println("This result is from Exception");
}
}
}
----------------------------------------------------------------------------------------------------------------------------------------
Output:
This result is from NullPointerException

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

Notes prepared by _M$A_ : 8801114535. 124


PANKAJ SIR ACADEMY CORE JAVA
Example #5: (Creating ArithmeticException and NullPointerException both)
package p1; //Multiple catch block in try-catch
public class A {
int x =10;
public static void main(String[] args) {
try {
int x =10/0; //It's an arithmetic exception
A a1 = null;
System.out.println(a1.x); //It's a NullPointerException
} catch (ArithmeticException e) {
System.out.println("This result is from ArithmeticException");
} catch (NullPointerException e) {
System.out.println("This result is from NullPointerException");
} catch (Exception e) {
System.out.println("This result is from Exception");
}
}
}
----------------------------------------------------------------------------------------------------------------------------------------
Output:
This result is from ArithmeticException

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

Here it handled only ArithmeticException exception, whichever may come first it will handle
that exception and stops & will not run further codes.

Example #6: (Interchanging the exceptions from previous program)


package p1; //Multiple catch block in try-catch
public class A {
int x =10;
public static void main(String[] args) {
try {
A a1 = null;
System.out.println(a1.x); //It's a NullPointerException
int x =10/0; //It's an arithmetic exception
} catch (ArithmeticException e) {
System.out.println("This result is from ArithmeticException");
} catch (NullPointerException e) {
System.out.println("This result is from NullPointerException");
} catch (Exception e) {
System.out.println("This result is from Exception");
}
}
}
----------------------------------------------------------------------------------------------------------------------------------------
Output:
This result is from NullPointerException

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

Here it handled only NullPointerException, because it came first & did not run any further code
of blocks.

Notes prepared by _M$A_ : 8801114535. 125


PANKAJ SIR ACADEMY CORE JAVA
Example (creating NumberFormatException wich cannot be handled
#7: by
ArithmeticException and NullPointerException & control goes to parent class Exception)
package p1; //Multiple catch block in try-catch
public class A {
int x =10;
public static void main(String[] args) {
try {
Integer.parseInt("abcdef"); //It's a NumberFormatException
A a1 = null;
System.out.println(a1.x); //It's a NullPointerException
int x =10/0; //It's an arithmetic exception
} catch (ArithmeticException e) {
System.out.println("This result is from ArithmeticException");
} catch (NullPointerException e) {
System.out.println("This result is from NullPointerException");
} catch (Exception e) {
System.out.println("This result is from Exception");
}
}
}
----------------------------------------------------------------------------------------------------------------------------------------
Output:
This result is from Exception

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

FINALLY BLOCK

Q. What is Finally Block?


A. Finally block is an extension of Try-Catch. Wether exception occurs or not Finally Block will
continue to excecute.
Example #1: (Exception ocuurs)
package p1; //Finally Block
public class B {
public static void main(String[] args) {
try {
Integer.parseInt("abcdef"); //It's a NumberFormatException
} catch (Exception e) {
System.out.println("This result is from Exception");
} finally {
System.out.println("This result is from final block");
}
}
}
----------------------------------------------------------------------------------------------------------------------------------------
Output:
This result is from Exception
This result is from final block

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

Notes prepared by _M$A_ : 8801114535. 126


PANKAJ SIR ACADEMY CORE JAVA
Example #2: (No Exception)
package p1; //Finally Block
public class B {
public static void main(String[] args) {
try {
Integer.parseInt("100");
} catch (Exception e) {
System.out.println("This result is from Exception");
} finally {
System.out.println("This result is from finally block");
}
}
}
----------------------------------------------------------------------------------------------------------------------------------------
Output:
This result is from finally block

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

Q. Can we write only Try and Finally & skip catch block?
A. Yes, We can write it.
Example #3:

Here exception is happening, but if catch block is missing, exception is not handled so line#9
will not run but finally block continues to run.

Task Assignment

Watch recorded lecture from


Pankaj Sir Academy App
To learn “Finalize” Keyword.
Batch > Recorded Series Part 2

Notes prepared by _M$A_ : 8801114535. 127


PANKAJ SIR ACADEMY CORE JAVA
Q. What is the difference between Final, Finally and Finalize?
Sr# Key final finally finalize
1. Definition final is the keyword finally is the block in finalize is the method in
and access modifier Java Exception Java which is used to
which is used to apply Handling to execute perform clean up
restrictions on a class, the important code processing just before
method or variable. whether the exception object is garbage
occurs or not. collected.
2. Applicable Final keyword is used Finally block is always finalize() method is
to with the classes, related to the try and used with the objects.
methods and catch block in
variables. exception handling.
3. Functionality (1) Once declared, (1) finally block runs finalize method
final variable the important code performs the cleaning
becomes constant even if exception activities with respect
and cannot be occurs or not. to the object before its
modified. (2) finally block cleans destruction.
(2) final method up all the resources
cannot be overridden used in try block
by sub class.
(3) final class cannot
be inherited.
4. Execution Final method is Finally block is finalize method is
executed only when executed as soon as executed just before
we call it. the try-catch block is the object is destroyed.
executed.
It's execution is not
dependant on the
exception.

Q. Give a practical example where finally block can be used?


A. The suitable example for this would be JDBC, where we Open the connection to the database
& an excpetion occurs while typing the code to the database & the closing connection (Close()
method) will not run further and the connection remains open.

Notes prepared by _M$A_ : 8801114535. 128


PANKAJ SIR ACADEMY CORE JAVA
package p1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class D {
public static void main(String[] args) {
Connection con = null; //it was local to try, now it's local to Main
try {

//Open Connection
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_db", "root", "Test");
System.out.println(con);

//Code to store/insert record into database:


Statement st = con.createStatement();
//in below statement there's an exception in SQL Query "inserts"
st.executeUpdate
("inserts into Registration values('Stallin', 'Chicago', 'stallin@gmail.com', '1084658760')");

//Close connection
} catch (Exception e) {
e.printStackTrace();

} finally {
try {
System.out.println("This result is from finally block");
con.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
}
----------------------------------------------------------------------------------------------------------------------------------------
Output:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/my_db
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at p1.D.main(D.java:12)
This result is from finally block
Exception in thread "main" java.lang.NullPointerException
at p1.D.main(D.java:27)

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

Notes prepared by _M$A_ : 8801114535. 129


PANKAJ SIR ACADEMY CORE JAVA

Task Assignment

Watch recorded lecture from


Pankaj Sir Academy App
To learn “Typecasting”.
Batch > Recorded Series Part 1

REMAINING TOPICS TO BE COVERED LATER

• Stream API (JAVA 8 Feature)


• Optional Class (JAVA 8 Feature)
• Logical Questions on Collection
• Difference between String buffer and String Builder Class
• Singleton Design Pattern
• Vectors
• Priority Queue
• Sorting an Object
• Difference between Comparator and Comparable Interface
• Runtime Polymorphism

Notes prepared by _M$A_ : 8801114535. 130

You might also like