[Go to site: main page, start]

0% found this document useful (0 votes)
3 views124 pages

Java Notes

Uploaded by

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

Java Notes

Uploaded by

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

Java

Programming and Data Structures


Complete Self-Study Guide

1
Table of Contents
Session 1: Java Introduction & Variables .................................................................................................
1.1 Java Introduction............................................................................................................................ 1
1.2 History of Java................................................................................... Error! Bookmark not defined.
1.3 Features of Java ................................................................................. Error! Bookmark not defined.
1.4 JVM(Java Virtual Machine) ............................................................................................................ 4
1.5 JRE(Java Runtime Environment) ..................................................................................................... 4
1.6 JDK(Java Development Kit) ............................................................................................................ 5
1.7 Variable ........................................................................................................................................ 6
1.8 Keywords ...................................................................................................................................... 6
1.9 Data types ..................................................................................................................................... 7
1.10 Operators .................................................................................................................................... 9
1.11 Scanner Input ............................................................................................................................. 13
Session 2 : Control Statements & Loops ............................................................................................... 16
2..1 Control Statements ...................................................................................................................... 16
2.2 if Statements................................................................................................................................ 16
2.3 if-else Statements ......................................................................................................................... 17
2.4 else-if Ladder .............................................................................................................................. 18
2.5 Nested if Statement ...................................................................................................................... 19
2.6 Switch Statement ......................................................................................................................... 20
2.7 for Loop ...................................................................................................................................... 21
2.8 while Loop .................................................................................................................................. 22
2.9 do-while Loop ............................................................................................................................. 23
2.10 break Statement.......................................................................................................................... 25
2.11 continue Statement ..................................................................................................................... 25
2.12 Pattern programs ........................................................................................................................ 26
Session 3 : Arrays & Strings ............................................................................................................. 27
3.1 Array .......................................................................................................................................... 27
3.2 Array Traversal ............................................................................................................................ 28
3.3 Linear Search .............................................................................................................................. 29
3.4 Multidimensional Arrays............................................................................................................... 32
3.5 String.......................................................................................................................................... 33
3.6 Methods of String Class ................................................................................................................ 34
3.7 StringBuffer & StringBuilder Classes ............................................................................................. 38
Session 4 : Methods, Classes & Encapsulation ...................................................................................... 39
4.1 Method ...................................................................................................................................... 39
4.2 Parameters .................................................................................................................................. 41
4.3 Return Types ............................................................................................................................... 43
2
4.4 Method Overloading .......................................................................... Error! Bookmark not defined.
4.5 Class Creation & Object Creation................................................................................................... 47
4.6 this Keyword ..................................................................................... Error! Bookmark not defined.
Session 5 : Constructors & Encapsulations .......................................................................................... 51
5.1 Constructor.................................................................................................................................. 51
5.2 No- Argument Constructor ............................................................................................................ 52
5.3 Parameterized Constructor ............................................................................................................ 52
5.4 Constructor Overloading ............................................................................................................... 53
5.5 Encapsulation .............................................................................................................................. 55
5.6 Access Modifiers ......................................................................................................................... 56
Session 6 : Inheritance & Polymorphism .............................................................................................. 60
6.1 Inheritance .................................................................................................................................. 60
6.2 Types of Inheritance .................................................................................................................... 60
6.3 extends ....................................................................................................................................... 72
6.4 Method Overriding ....................................................................................................................... 74
6.5 Compile-time Polymorphism ......................................................................................................... 76
6.6 Runtime Polymorphism ............................................................................................................... 77
Session 7 : Abstraction & Interface ...................................................................................................... 79
7.1 Abstract ..................................................................................................................................... 79
7.2 Interface...................................................................................................................................... 83
7.3 Abstract vs Interface ..................................................................................................................... 90
Session 8 : Exception Handling & File I/ O........................................................................................... 91
8.1 Exception Handling ...................................................................................................................... 91
8.2 Types of Exceptions ..................................................................................................................... 91
8.3 try-catch-finally ........................................................................................................................... 93
8.4 throw / throws.............................................................................................................................. 93
8.5 File I / O ................................................................................................................................... 94
8.6 File Reader ................................................................................................................................ 95
8.7 Buffered Reader .......................................................................................................................... 96
8.8 File Writer................................................................................................................................... 96
Session 9 : Multithreading .................................................................................................................. 98
9.1 Multithreading ............................................................................................................................. 98
9.2 Thread Creation ........................................................................................................................... 99
9.3 Thread Class................................................................................................................................ 99
9.4 Runnable Interface ..................................................................................................................... 100
9.5 Thread scheduler ........................................................................................................................ 101
9.6 Yield ........................................................................................................................................ 103
9.7 Sleep ....................................................................................................................................... 104

3
9.8 Join ......................................................................................................................................... 105
9.9 Synchronization ......................................................................................................................... 106
Session 10 : Collections Framework ................................................................................................. 108
10..1 Collection Framework .............................................................................................................. 108
10.2 List ......................................................................................................................................... 109
10.3 Set .......................................................................................................................................... 111
10.4 Queue ..................................................................................................................................... 114
10.5 Map ........................................................................................................................................ 116
10.6 TreeMap ................................................................................................................................. 118

4
Session 1: Java Introduction

Java is a high-level, object-oriented programming language developed by Sun


Microsystems (now owned by Oracle) in 1995. It is known for its "Write Once, Run
Anywhere" (WORA) capability, meaning that compiled Java code can run on any
platform
Java latest version is “Java SE 25”, released on 16th September 2025.
java –version

History of java:
Java was developed by James Gosling, Patrick Naughton, Chris Warth, Ed Frank and
Mike Sheridan at SUN (Stanford University Network) Microsystems, in 1991.
Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
After that, it was called “oak” but it was renamed to “java” in 1995 because of a product
already using the name “oak”.
Oak is a national tree of many countries like U.S.A., France, Germany, Romania, etc.
Java is an island of Indonesia where first coffee was produced (called java coffee).
Java was originally designed to develop digital TV setup boxes.
Vendor of java was Sun. But now vendor of java is oracle. Java is a freeware and open
source.

1
Features of java:

1) Simple:
Java is simple language. It contains most of the features of C++ but java is not inherited from
C++. Java does not contains header files, pointers, structures, operator overloading, virtual base
classes and so on.

2) Secure:
Using Java Compatible Browser, anyone can safely download Java applets without the fear of
viral infection or malicious intent because of its key design principle. So anyone can download
applets with confidence that no harm will be done. The first web browser written in java was
called WebRunner, later became HotJava.

3) Portable:
Many types of computers and operating systems are in use throughout the world and many are
connected to the Internet. Java makes it possible to have the assurance that any result on one
computer with Java can be replicated on another. So the code is run in the different platform has
a same result.

4) Object-oriented:
Java support the all the features of object oriented programming language such as Abstraction,
Encapsulation, Inheritance, Polymorphism and Dynamic binding etc….

5) Robust:
Most programs in use today fail for one of the two reasons:

2
(i) memory management mistakes
For example, in C/C++, the programmer must manually allocate and free all dynamic memory.
This sometimes leads to problems, because programmers will either forget to free memory that
has been previously allocated or, sometimes try to free some memory that another part of their
code is still using. Java virtually eliminates these problems by managing memory allocation
(with the help of new operator) and deallocation. (deallocation is completely automatic, because
Java provides garbage collection for unused objects.)
(ii) mishandled exceptional conditions
With the help of Exception Handling (try……….catch block), the programmer can easily handle
an error or exception so user can prevent the program by automatically stop the execution when
an exception found.
Thus, the ability to create robust programs was given a high priority in the design of Java.

6) Multithreaded:
Java supports programming, which allows the user to write programs that perform many
functions simultaneously.
The two or more part of the program can run concurrently then each part of such a program is
called a Thread and this type of programming is called multithreaded programming.

7) Platform Independent
The Java designers worked hard in achieving their goal “write once; run anywhere, anytime,
forever” and as a result the Java Virtual Machine was developed.
Java is Architecture-neutral it generates byte code that resembles machine code, and are not
specific to any processor.

Platform Independent Example:

3
8) Interpreted and High performance
The source code is first compile and generates the code into an intermediate representation called
Java byte code which is a highly optimized set of instruction code.
This code can be interpreted on any system that has a Java Virtual Machine and generates the
machine code.
Java bytecode was carefully designed by using a just-in-time compiler so that it can be easily
translated into native machine code for very high performance.

9) Distributed
Java allows the object can access the information across the network with the help of RMI
(Remote Method Invocation) means this allowed objects on two different computers to execute
procedures remotely. So this feature supports the client/server programming.

10) Dynamic:
Java is dynamic language. Java is capable of dynamically linking new class libraries, methods
and objects. It also supports functions from its native languages, i.e., C and C++.

11) Architecture-neutral:
Java is architecture neutral because there are no implementation dependent features, for example,
the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes
of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-
bit architectures in Java.

JVM (Java Virtual Machine)


JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform
dependent because configuration of each OS differs. But, Java is platform independent.
The JVM performs following main tasks:
Loads code
Verifies code
Executes code
Provides runtime environment

JRE(Java Runtime Environment:

JRE is an acronym for Java Runtime Environment. It is used to provide runtime environment. It
is the implementation of JVM. It physically exists. It contains set of libraries(ex: [Link], run time
java archive) + other files that JVM uses at runtime.
Implementation of JVMs are also actively released by other companies besides Sun Micro
Systems.

4
JRE (Java Runtime Environment)

JDK (Java Development Kit)

It physically exists. It contains JRE + development tools.

5
Download and Install JDK:
Step 1: Visit the Official Website
Go to the Official JDK website to download the file.
Step 2: Run the Java Development Kit (JDK) Installer
Step 3: Setup the Environment Variables
copy C:\Program Files\Java\jdk\bin
Step 3.1: To set the Environment Variables, you need to search Environment Variables in
the Task Bar and click on “Edit the system environment variables”.
Step 3.2: Under System variables, select the "Path" variable and click on "Edit". Click on "New"
then paste the Path Address i.e. C:\Program Files\Java\jdk\bin. Click on "OK".
Step 4: Check the Java Version
Open Command Prompt and enter the following commands: java -version

Variable
Variable is a name that represent a value that stored in a memory location.
-> Variable name can consist of alphabets, digits, _ ,$
->variable name should start with either alphabet or _ or $.
variable name should not start with digits, all ways its better to start a variable name with
alphabet.

Note: using _ in variable is supported up to Java 8, from java 9 it won’t support


Example: int firstNumber=10, secondNumber=23;

Java Language Keywords


You cannot use any of the following as identifiers in your programs. The
keywords const and goto are reserved, even though they are not currently used. true, false,
and null might seem like keywords, but they are actually literals; you cannot use them as
identifiers in your programs.
As of Java 21, there are 53 keywords,

abstract continue for new


assert*** default goto* package

6
boolean do if private
break double implements protected
byte else import public
case enum**** instanceof return
catch extends int short
char final interface static
class finally long strictfp**
const* float native super

Data types

Data type specifies the size and type of values that can hold or stored.
There are two types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float
and double.
Non-primitive or referencedata types: The non-primitive data types include Array, String,
Classes, Interfaces.

8 Primitive data types are byte, short, int, long, float, double, char and boolean.
These can be put in four groups.

7
Integers: This group includes byte, short, int, and long, which are for signed and unsigned
number including zero.
Floating-point numbers: This group includes float and double, which can store numbers with
fractional precision.
Characters: This group includes char, which represents symbols in a character set, like letters
and numbers.
Boolean: This group includes boolean, which is a special type for representing true/false values.
1. Integers:
Java defines four integer types: byte, short, int, and long. All of these can have signed, unsigned
or zero value. Java does not support unsigned, positive-only integers.

Name Width (in bits, bytes) Range


long 64(4) –9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
int 32 (4) –2,147,483,648 to
2,147,483,647
short 16 (2) –32,768 to 32,767
byte 08 (1) –128 to 127
All long values must suffix with either l or L otherwise it will be treated as integer.

2. Floating-Point Types:
Floating-point numbers, also known as real numbers, are used when evaluating expressions that
require fractional precision. For example, calculations such as square root, sine and cosine, result
in a value whose precision requires a floating-point type.

Name Width in Bits(Bytes) Range


double 64 (8) 4.9e–324 to 1.7e+308
float 32 (4) 1.4e−45 to 3.4e+38
All float values must suffix with either f or F otherwise it will be treated as double.

3. Characters:
In Java, the data type used to store characters is char.
char in Java is not the same as char in C or C++. In C/C++, char is an integer type that is 8 bits
wide. This is not the case in Java.
Instead, Java uses Unicode to represent characters.
Unicode defines a fully international character set that can represent all of the characters found in
all human languages.
In Java char require16-bit. The range of a char is 0 to 65,535.

4. Booleans:
Java has a simple type, called boolean, for logical values. It can have only one of two possible
values, true or false. This is the type returned by all relational operators, such as
a < b.
Except boolean and char all data types are signed.

8
• General rule to calculate range
• Min value = - 2(bits – 1)
• Max value = 2(bits-1) – 1
• (where 1 byte = 8 bits)

Integrated development environment (IDE)


These IDEs help you write, run, and debug Java programs easily.
1. IntelliJ IDEA
2. Eclipse
3. Apache NetBeans
4. Visual Studio Code
5. JDeveloper
6. MyEclipse
7. jGRASP
8. BlueJ

Operators in Java
Operators are symbols used to perform operations on variables and values.
Example:
+ - * / %
Example program:
int a = 10;
int b = 5;

[Link](a + b);
Output:
15

Types of Operators
1. Arithmetic Operators
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
Example:
int a = 10;
int b = 3;

[Link](a+b); //13
[Link](a-b); //7
[Link](a*b); //30

9
[Link](a/b); //3
[Link](a%b); //1
2. Relational Operators
A Relational Operator also called a comparison operator, compares the values of two operands
and returns a boolean values: true or false
Operator Meaning
== Equal
!= Not equal
> Greater
< Less
>= Greater or equal
<= Less or equal
Example:
int a = 10;
int b = 20;

[Link](a>b);
[Link](a>=b);
[Link](a<b);
[Link](a<=b);
[Link](a==b);
[Link](a!=b);

Output:
false
false
true
true
false
true
3. Logical Operators
Logical operators are used to combine two or more conditions and return a boolean value
(true or false). They are commonly used in decision-making statements like if, while, and for.

Operator Name Description Example


&& Logical AND Returns true if both conditions are true a>5 && b>5
|| Logical OR Returns true if at least one condition is true a>5 || b>5
! Logical NOT Reverses the result !(a>5)

Example:
inta=10;
intb=5;

10
[Link]("Logical AND: "+ (a>5&&b>2));
[Link]("Logical OR: "+ (a>20||b>2));
[Link]("Logical NOT: "+!(a>5));

Output:
Logical AND: true
Logical OR: true
Logical NOT: false
4. Bitwise Operators
Bitwise operators perform operations on individual bits of integer numbers.
These operators work directly on the binary representation (0s and 1s) of numbers.
Example:
10 in binary = 1010
5 in binary = 0101

Types of Bitwise Operators


Operator Name Description
& Bitwise AND Result is 1 if both bits are 1
| Bitwise OR Result is 1 if at least one bit is 1
^ Bitwise XOR Result is 1 if bits are different
~ Bitwise NOT Reverses all bits
<< Left Shift Shifts bits to the left
>> Right Shift Shifts bits to the right

Example:
inta=10;
intb=5;

[Link]("a & b = "+ (a&b)); // Bitwise AND


[Link]("a | b = "+ (a|b)); // Bitwise OR
[Link]("a ^ b = "+ (a^b)); // Bitwise XOR
[Link]("~a = "+ (~a)); // Bitwise NOT
[Link]("a << 1 = "+ (a<<1)); // Left Shift
[Link]("a >> 1 = "+ (a>>1)); // Right Shift

Output:
a& b = 0
a | b = 15
a ^ b = 15
~a = -11
a << 1 = 20

11
a >> 1 = 5
5. Assignment Operators
Operator Example
= a = 10
+= a += 5
-= a -= 5
*= a *= 5
/= a /= 5

Example:
inta=10;

[Link]("Initial value of a: "+a);

a+=5;
[Link]("After a += 5: "+a);

a-=3;
[Link]("After a -= 3: "+a);

a*=2;
[Link]("After a *= 2: "+a);

a/=4;
[Link]("After a /= 4: "+a);

a%=3;
[Link]("After a %= 3: "+a);

Output:
Initial value of a: 10
After a += 5: 15
After a -= 3: 12
After a *= 2: 24
After a /= 4: 6
After a %= 3: 0

6. Increment / Decrement Operators


Operator Meaning
++ Increment
-- Decrement

12
Example:
inta=10;

[Link]("Initial value: "+a);

[Link]("Post Increment: "+ (a++));


[Link]("After Post Increment: "+a);

[Link]("Pre Increment: "+ (++a));

[Link]("Post Decrement: "+ (a--));


[Link]("Pre Decrement: "+ (--a));

Output:
inta=10;

[Link]("Initial value: "+a);

[Link]("Post Increment: "+ (a++));


[Link]("After Post Increment: "+a);

[Link]("Pre Increment: "+ (++a));

[Link]("Post Decrement: "+ (a--));


[Link]("Pre Decrement: "+ (--a));

Self-Assessment Questions
1. What is Java?
2. Who developed Java?
3. What is JVM?
4. What is JRE?
5. What is JDK?
6. Define platform independence.
7. What are Java keywords?
8. What are data types?
9. What is an IDE?
10. What are operators?
Introduction to Scanner
The Scanner class in Java is used to take input from the user at runtime. It is part of the
[Link] package.
Why we use Scanner
• To read user input from keyboard
• To make programs interactive
• To read different types of data like numbers, strings, and decimals.

13
Importing Scanner
Before using Scanner, we must import the package.
[Link];
Creating Scanner Object
Scannersc=newScanner([Link]);
• Scanner → Class name
• sc → Object name
• [Link] → Input stream from keyboard
Common Scanner Methods
Method Description
nextInt() Reads integer value
nextDouble() Reads decimal number
nextLine() Reads string sentence
next() Reads single word
nextFloat() Reads float number
nextBoolean() Reads true or false

Program 1: Read a Number from User


Scenario - A bank system asks the user to enter an account number.
[Link];

publicclassReadNumber {

publicstaticvoidmain(String[] args) {

Scannersc=newScanner([Link]);

[Link]("Enter a number:");

intnum=[Link]();

[Link]("You entered: "+num);


}
}
Output:
Enter a number:
5
You entered: 5

Program 2: Addition of Two Numbers


Scenario- A simple calculator program that adds two numbers entered by the user.
[Link];

14
publicclassAddition {

publicstaticvoidmain(String[] args) {

Scannersc=newScanner([Link]);

[Link]("Enter first number:");


inta=[Link]();

[Link]("Enter second number:");


intb=[Link]();

intsum=a+b;

[Link]("Sum = "+sum);
}
}
Output:
Enter first number:
7
Enter second number:
52
Sum = 59

Program 3: Find Largest of Two Numbers


Scenario-A school system compares two student marks and prints the highest mark.
[Link];

publicclassLargestNumber {

publicstaticvoidmain(String[] args) {

Scannersc=newScanner([Link]);

[Link]("Enter first number:");


inta=[Link]();

[Link]("Enter second number:");


intb=[Link]();

if(a>b)
[Link]("Largest number is: "+a);
else
[Link]("Largest number is: "+b);

15
}
}
Output:
Enter first number:
52
Enter second number:
6
Largest number is: 52
Session 2- Control Statements in Programming
Control statements are used to control the flow of execution in a program. They allow the
program to make decisions, repeat tasks, and stop execution when needed.
Types of Control Statements:
1. Decision Making Statements
2. Looping Statements
3. Jump Statements
1. if Statement
Definition
The if statement executes a block of code only when the specified condition is true.

Flow Diagram

Example Program 1
public class IfExample {
public static void main(String[] args) {
int number = 10;

if(number >5){
[Link]("Number is greater than 5");
}
}
}
16
Output:
Number is greater than 5
Example Program 2 (Scenario Based – Student Pass)
public class PassExample {
public static void main(String[] args) {
int marks = 60;

if(marks >= 35){


[Link]("Student Passed");
}
}
}

Output:
Student Passed
2. if-else Statement
Definition
The if-else statement is used when there are two possible conditions.
Flow Diagram

Example Program 1
public static void main(String[] args) {
int age = 17;

if(age >= 18){


[Link]("Eligible to vote");
}else{
[Link]("Not eligible to vote");
}
}
Output:
Not eligible to vote

17
Example Program 2 (Scenario – Login System)
public static void main(String[] args) {

String password = "admin123";

if([Link]("admin123")){
[Link]("Login Successful");
}else{
[Link]("Invalid Password");
}
}
Output:

Login Successful
3. else-if Ladder
Definition
The else-if ladder is used when there are multiple conditions.
Flow Diagram

Example Program 1
public static void main(String[] args) {

int marks = 85;

if(marks >= 90)


[Link]("Grade A");
else if(marks >= 70)
[Link]("Grade B");
else
[Link]("Grade C");
}
Output:

18
Grade B
Example Program 2 (Scenario – Employee Bonus)
public static void main(String[] args) {

int experience = 6;

if(experience >= 10)


[Link]("20% Bonus");
else if(experience >= 5)
[Link]("10% Bonus");
else
[Link]("5% Bonus");
}
Output:
10% Bonus
4. Nested if Statement
Definition
A Nested if means an if statement inside another if statement.
Flow Diagram

Example Program 1
public static void main(String[] args) {

int age = 20;


boolean id = true;

if(age >= 18){


if(id){
[Link]("Entry Allowed");

19
}
}
}
Output:
Entry Allowed
Example Program 2 (Scenario – College Admission)
public static void main(String[] args) {

int marks = 80;


boolean entrance = true;

if(marks >= 70){


if(entrance){
[Link]("Admission Granted");
}
}
}
Output:
Admission Granted
5. switch Statement
Definition
The switch statement selects one block of code from many options.

Flow Diagram

Example Program 1
public static void main(String[] args) {

20
int day = 2;
switch(day){
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
default:
[Link]("Invalid Day");
}
}

Output:
Tuesday
Example Program 2 (Scenario – ATM Menu)
public static void main(String[] args) {
int option = 1;
switch(option){
case 1:
[Link]("Check Balance");
break;
case 2:
[Link]("Withdraw Money");
break;
case 3:
[Link]("Deposit Money");
break;
default:
[Link]("Invalid Option");
}
}
Output:
Check Balance

6. for Loop
Definition
The for loop is used when the number of iterations is known.

21
Flow Diagram

Example Program 1
public static void main(String[] args) {
for(int i=1;i<=5;i++){
[Link](i);
}
}
Output:
1
2
3
4
5
Example Program 2 (Scenario – Attendance System)
public static void main(String[] args) {
for(int day=1; day<6; day++){
[Link]("Recording attendance for Day " + day);
}
}
Output:
Recording attendance for Day 1
Recording attendance for Day 2
Recording attendance for Day 3
Recording attendance for Day 4
Recording attendance for Day 5

7. while Loop
Definition
The while loop executes repeatedly while the condition is true.

22
Flow Diagram

Example Program 1
public static void main(String[] args) {

int i = 1;

while(i<= 5){
[Link](i);
i++;
}
}
Output:
1
2
3
4
5
Example Program 2 (Scenario – Password Attempts)
public static void main(String[] args) {

int attempts = 0;

while(attempts <3){
[Link]("Enter Password");
attempts++;
}
}
Output:
Enter Password
Enter Password
Enter Password

23
8. do-while Loop
Definition
The do-while loop executes the code at least once before checking the condition.

Flow Diagram

Example Program 1
public static void main(String[] args) {

int i = 1;

do{
[Link](i);
i++;
}while(i<= 5);
}

Output:
1
2
3
4
5

Example Program 2 (Scenario – Game Menu)


public static void main(String[] args) {

int choice = 2;

do{

24
[Link]("1. Play Game");
[Link]("2. Exit");
}while(choice != 2);
}
Output:
1. Play Game
2. Exit

9. break Statement
Definition
The break statement terminates the loop immediately.
Example Program
public static void main(String[] args) {

for(int i=1;i<=10;i++){
if(i == 5)
break;

[Link](i);
}
}
Output:
1
2
3
4
10. continue Statement
Definition
The continue statement skips the current iteration.
Example Program (Scenario – Skip Absent Student)
public static void main(String[] args) {

for(int roll=1; roll<=7; roll++){

if(roll == 4)
continue;

[Link]("Attendance for Roll No: " + roll);


}
}
Output:
Attendance for Roll No: 1
Attendance for Roll No: 2
Attendance for Roll No: 3

25
Attendance for Roll No: 5
Attendance for Roll No: 6
Attendance for Roll No: 7

11. Pattern Program (Nested Loops)


Definition
Pattern programs use nested loops to print shapes.
Pattern
*
**
***
****
Example Program 1
public static void main(String[] args) {

for(int i=1;i<=4;i++){
for(int j=1;j<=i;j++){
[Link]("*");
}
[Link]();
}
}
Output:
*
**
***
****
Example Program 2 (Scenario – Seating Arrangement)
public static void main(String[] args) {

int rows = 4;
for(int i=1;i<=rows;i++){
for(int j=1;j<=i;j++){
[Link]("S ");
}
[Link]();
}
}
Output:
S
SS
S SS
S SSS
Example Program 3 (Scenario –A training institute display board prints letters in pyramid

26
form to represent levels of learning (A–E))
public class AlphabetPyramid {
public static void main(String[] args) {
int rows = 5;
for(int i = 1; i<= rows; i++) {
for(int j = 1; j <= rows - i; j++) {
[Link](" ");
}
for(int k = 0; k <i; k++) {
[Link]((char)('A' + k));
}
for(int k = i - 2; k >= 0; k--) {
[Link]((char)('A' + k));
}
[Link]();
}
}
}
Output:
A
ABA
ABCBA
ABCDCBA
ABCDEDCBA

Session 3 - Arrays & Strings:


Array:
An array is a group of similar data type items that share a common name. An array occupies
contiguous memory locations. Array size is fixed and cannot be altered dynamically.
We have one dimensional and multidimensional array in java.

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.
Disadvantages:
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows

27
automatically.
Homogeneous elements: It can store homogeneous elements it can not store heterogeneous
elements.
Insertions & deletions: are slow
One dimensional array: a list of items can be given one variable name using only one subscript
and such a variable is called as one dimensional array.
Creating an array: involves three steps
i) Declaring the array
ii) Creating memory locations
iii) Putting values in the memory locations
Declaring the array:
Can be done in two ways
1st way: datatype arrayname[ ];
2nd way: datatype [ ]arrayname;
3rd way: datatype[ ] arrayname;
Examples:
int number[ ];
float[ ] marks;
Note: size of array should not mention while declaration.
creating memory locations:
Using new keyword.
Syntax:arrayname=new datatype[size]
Ex: number=new int[5];
marks=new float[10];
We can combine both the steps for declaration and creation as
float average[ ]=new float[10];
Initialization of arrays:
Syntax: datatype arrayname[ ]={value1,value2,value3,...........valuen};
Ex: int marks[ ]={40,55,73};

Array traversal:
Array Traversal means visiting each element of an array one by one and performing some
operation (like printing).
Example:
public class ArrayTraversal {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
[Link]("Array Elements are:");
for(int i = 0; i<[Link]; i++) {
[Link](arr[i]);
}
}
}

28
Output
Array Elements are:
10
20
30
40
50

Linear Search:
Linear Search is a method used to find an element in an array by checking each element one by
one from the beginning until the element is found or the array ends.
Algorithm
1. Start from the first element of the array.
2. Compare the element with the key (search element).
3. If it matches, return the position.
4. If not, move to the next element.
5. If the element is not found after checking all elements, return -1.
[Link];
public class LinearSearch {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int key = 30;
int position = -1;
for(int i = 0; i<[Link]; i++) {
if(arr[i] == key) {
position = i;
break;
}
}

if(position != -1)
[Link]("Element found at position: " + (position + 1));
else
[Link]("Element not found");
}
}

Output
Element found at position: 3

Basic array programs:


Program to Find Sum of Array Elements
public class ArraySum {

29
public static void main(String[] args) {
int[] arr = {5, 10, 15, 20};
int sum = 0;
for(int i = 0; i<[Link]; i++) {
sum = sum + arr[i];
}
[Link]("Sum = " + sum);
}
}
Output
Sum = 50

Program to Find Largest Element in an Array


public class LargestElement {
public static void main(String[] args) {
int[] arr = {12, 45, 7, 89, 34};
int max = arr[0];
for(int i = 1; i<[Link]; i++) {
if(arr[i] > max) {
max = arr[i];
}
}

[Link]("Largest element = " + max);


}
}
Output:
Largest element = 89

Program to print even no’s from an array


[Link];
public class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("enter [Link] elements");
int n=[Link]();
int a[]=new int[n];
[Link]("enter elements");
for(int i=0;i<n;i++)
{
a[i]=[Link]();
}
[Link]("Even numbers are:");
for(int i=0;i<n;i++)

30
{
if(a[i]%2==0)
[Link](a[i]+" ");
}

}
}
Output:
[Link] elements
4
enter elements
10 3 9 44
Even numbers are:10 44

Program to find the frequency of each element in the array


[Link].*;
class Main {
static void frequency(int arr[])
{
for(int i = 0; i<[Link]; i++){
int count = 1;
for(int j = i+1; j <[Link]; j++){
if(arr[i] == arr[j]){
count++;
//To avoid counting same element again
arr[j] = -1;
}
}
if(arr[i] != -1)
[Link](arr[i] +" repeated "+count +" times");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("enter [Link] elements");
int n=[Link]();
int a[]=new int[n];
[Link]("enter elements");
for(int i=0;i<n;i++)
{
a[i]=[Link]();
}
frequency(a);
}

31
}
Output:
[Link] elements
9
enter elements
128322251
1 repeated 2 times
2 repeated 4 times
8 repeated 1 times
3 repeated 1 times
5 repeated 1 times

Multidimensional arrays:
Array of arrays are called as multidimensional arrays.
Ex: int sales[ ][ ]=new int[2][3];
sales[0 ][0 ]=100 ;
sales[0 ][1 ]=230 ;
sales[0 ][2 ]=330 ;
sales[1 ][0 ]=560 ;
sales[1 ][1 ]=340 ;
sales[1 ][2 ]=280 ;

Program to find transpose of a matrix


[Link];
public class Demo {
public static void main(String[] args) {
Scanner sc= new Scanner([Link]);
[Link]("enter [Link] rows");
int r=[Link]();
[Link]("enter [Link] columns");
int c=[Link]();
int a[][]=new int[r][c];
int b[][]=new int[c][r];
inti,j;
[Link]("enter nos");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
a[i][j]=[Link]();
}
}

for(i=0;i<r;i++)

32
{
for(j=0;j<c;j++)
{
b[j][i]=a[i][j];
}
}
[Link]("matrix transpose");
for(i=0;i<c;i++)
{
for(j=0;j<r;j++)
{
[Link](b[i][j]+" ");
}
[Link]();
}

}
}

Output:
[Link] rows
2
[Link] columns
3
enternos
123
456
matrix transpose
14
25
36

String:
A String is the type of object that can store a sequence of characters enclosed by double quotes.
In Java, each character in a string is a 16-bit Unicode character.
Creating Strings:
The most direct way to create a string is to write:
String s1 = "Hello world";// Hello world
char[] ch={'r','a','j','u'};
String s=new String(ch);
Is same as:
String s1=new String(“raju”);
A string literal is created at compile time & the compiler never creates a duplicate string literal.
However a string with the new operator is created at runtime & always creates a new String even

33
if it is identical to an already existing String.
Strings created by the String class are immutable.
String s1=“java”;
[Link](s1);//java
[Link]([Link](“ rules”));//java rules
[Link](s1);//java
s1=[Link](“ rules”);
[Link](s1);//java rules

String constant pool:


To make Java memory more efficient, the JVM sets aside a special area of memory called the
“String constant pool”. When the compiler encounters string literal, it checks the pool to see if
an identical string already exists. If a match is found , the reference to the new literal is directed
to the existing string and no new string literal object is created.

String str1=“Hello”;
String str2=“Hello”;
String s3=“abcdef”;

Important Methods of String Class:

public char charAt(int index)


String x=“airplane”;
[Link]([Link](2));// r

public String concat(String s)


String x=“taxi”;
[Link]([Link](”cab”));//taxicab
The + and += operators perform functions similar to the concat()method
String x=“library”;
[Link](x+”card”);//librarycard
String x=“atlantic”;
x+=“ ocean”;
[Link](x);//atlantic ocean
public booleanequals(String s)
String s1="java",s2="java",s3="Java";
[Link]([Link](s2));//true
[Link]([Link](s3));//false
[Link](s1==s2); //true
[Link](s1==s3); //false
public booleanequalsIgnoreCase(String s)
String s1="java",s2="Java";
[Link]([Link](s2));//false
[Link]([Link](s2));//true

34
Difference between equals and ==
public int length()
String s1="java";
[Link]([Link]());//4
public String replace(char old, char new)
String s1="java";
[Link]([Link](‘a',‘v'));//jvvv
public String replaceAll(String old, String new)
String s1="java is an oopl. java ";
[Link]([Link]("java","cpp"));//cpp is an oopl. cpp
public String substring(int begin)
String s1="java language";
[Link]([Link](2)); // va language
public String substring(int begin, int end)
String s1="java language";
[Link]([Link](2,9)); //valang
public String toLowerCase()
public String toUpperCase()
String s1="JAVA Language";
[Link]([Link]());//java language
[Link]([Link]());//JAVA LANGUAGE
int compareTo(String anotherString)
String s1 = "ant", s2="Ant";
[Link]([Link](s2)); // 32 (97-65= 32)
public char[] toCharArray()
String s1 = "java";
charch[] = [Link]();
String s2 = new String(ch); [Link](s2); // java
public String trim()
String s1=" JAVA ";
[Link](s1);// JAVA
[Link]([Link]());//JAVA

public int indexOf(char c)


public int lastIndexOf(char c)
booleancontains(String s)

String s1="JAVA LANGUAGE ";


[Link]([Link]('V'));//2
[Link]([Link]('v'));//-1
[Link]([Link]('A'));//10
[Link]([Link](“GUA”)); // true
public String[] split(String regex)
String s1 = "c cpp java dotnet"; /* c 2spaces cpp 2spaces java 1space dotnet*/

35
String s2[] = [Link]("\\s"); // 1space as a delimiter
// or String s2[] = [Link](“ ”);
for(int i=0;i<[Link];i++)
[Link](s2[i].length()+" "); // 1 0 3 0 4 6 [Link]("\n"+[Link]); // 6

Another way to create a string:


String s1=new String("java");
String s2=new String("java");
String s3="java";
String s4="java";
[Link](s1==s2);//false
[Link]([Link](s2));//true
[Link](s3==s4); //true
[Link]([Link](s3)); //true

Program to check Palindrome String:


[Link];
public class PalindromeString {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();
String rev = "";
for(int i = [Link]() - 1; i>= 0; i--) {
rev = rev + [Link](i);
}
if([Link](rev))
[Link]("Palindrome");
else
[Link]("Not Palindrome");
}
}
Output:
Enter a string: madam
Palindrome

Program to Count Number of Vowels in a String


[Link];
public class CountVowels {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();
int count = 0;

36
for(int i = 0; i<[Link](); i++) {
charch = [Link](i);

if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'||
ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U') {
count++;
}
}
[Link]("Number of vowels = " + count);
}
}
Output:
Enter a string: Java language
Number of vowels = 6
Program To Check Whether Two Strings Are Anagram Or Not?
[Link].*;
class Demo {
static void isAnagram(String s1, String s2)
{
String copyOfs1 = [Link]("\\s", "");
String copyOfs2 = [Link]("\\s", "");
boolean status = true;

if([Link]() != [Link]())
{
status = false;
}
else
{
char[] s1Array = [Link]().toCharArray();
char[] s2Array = [Link]().toCharArray();
[Link](s1Array);
[Link](s2Array);
status = [Link](s1Array, s2Array);
}
if(status)
{
[Link](s1+" and "+s2+" are anagrams");
}
else
{
[Link](s1+" and "+s2+" are not anagrams");
}
}

37
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
String s1 = [Link]();
String s2 = [Link]();
isAnagram(s1,s2);
}
}

Output:
Mother In Law
Hitler Woman
Mother In Law and Hitler Woman are anagrams

StringBuffer and StringBuilder Classes


The strings created by the String class are immutable where as the strings created by
StringBuffer and StringBuilder classes are mutable. StringBuffer and StringBuilder are same,
except StringBuilder is not thread safe(methods are not synchronized). StringBuilder will run
faster than StringBuffer.
StringBuilder is available since JDK 1.5.
StringBuildersb = new StringBuilder("java");
[Link](sb); //java
[Link]("language");
[Link](sb); //javalanguage
[Link]([Link]()); //12
StringBuildersb = new StringBuilder("0123456789");
[Link]([Link](4,6)); // 01236789
StringBuildersb = new StringBuilder("0123456789");
[Link]([Link](4,"---")); //0123---456789
StringBuildersb = new StringBuilder("0123456789");
[Link]([Link]());//9876543210
StringBuildersb = new StringBuilder("java language");
[Link]([Link](1));//a
[Link](2,'a');
[Link](sb);// jaaa language
StringBuildersb = new StringBuilder("java language");
[Link]([Link](2));// jaa language
[Link]([Link](6,9));//jaalaage
Convert String to StringBuffer and vice-versa
String name="raju";
StringBuffersb= new StringBuffer(name);
[Link]();
name=[Link]();

38
[Link](name);

StringTokenizer
StringTokenizer class in Java is used to break a string into
tokens based on delimiters.
The hasMoreTokens() method checks there are more tokens available to process or not.
The nextToken() method get the next token (substring).
Example:
[Link];
public class Main {
public static void main(String[] args) {
String s = "Hello how are you";
StringTokenizerst = new StringTokenizer(s, " ");
while ([Link]()) {
[Link]([Link]());
}
}
}
Output:
Hello
how
are
you

Session 4 - Methods and OOP Concepts


1. Method Definition
Definition
A method is a block of code that performs a specific task. It helps in code reuse and modular
programming.
Syntax
returnTypemethodName(parameters){
// method body
}

Example Program 1 (Simple Method)


import [Link];

public class MethodExample1 {

void display(int num){


[Link]("Number entered: " + num);
}

public static void main(String[] args){

39
Scanner sc = new Scanner([Link]);

[Link]("Enter a number:");
int number = [Link]();

MethodExample1 obj = new MethodExample1();

[Link](number);
}
}
Output:
Enter a number:
52
Number entered: 52
Example Program 2
import [Link];

public class MethodExample2 {

void square(int n){


[Link]("Square = " + (n*n));
}

public static void main(String[] args){

Scanner sc = new Scanner([Link]);

[Link]("Enter number:");
int num = [Link]();

MethodExample2 obj = new MethodExample2();


[Link](num);
}
}
Output:
Enter number:
7
Square = 49
Scenario-Based Program
Scenario - A bank system calculates the balance after depositing money.
import [Link];

public class BankDeposit {

40
void deposit(int balance, int amount){
int total = balance + amount;
[Link]("Updated Balance = " + total);
}

public static void main(String[] args){

Scanner sc = new Scanner([Link]);

[Link]("Enter current balance:");


int balance = [Link]();

[Link]("Enter deposit amount:");


int amount = [Link]();

BankDeposit obj = new BankDeposit();

[Link](balance, amount);
}
}
Output:
Enter current balance:
18000
Enter deposit amount:
5000
Updated Balance = 23000

2. Parameters
Definition
Parameters are variablesused to pass values to a method.
Example Program 1
import [Link];

public class ParameterExample1 {

void add(int a, int b){


[Link]("Sum = " + (a+b));
}

public static void main(String[] args){

Scanner sc = new Scanner([Link]);

41
int x = [Link]();
int y = [Link]();

ParameterExample1 obj = new ParameterExample1();


[Link](x,y);
}
}
Output:
7
18
Sum = 25

Example Program 2
import [Link];

public class ParameterExample2 {

void multiply(int a,int b){


[Link]("Multiplication = " + (a*b));
}

public static void main(String[] args){

Scanner sc = new Scanner([Link]);

int a = [Link]();
int b = [Link]();

ParameterExample2 obj = new ParameterExample2();


[Link](a,b);
}
}
Output:
6
7
Multiplication = 42
Scenario-Based Program
Scenario-A shopping system calculates the total price of items.
import [Link];

public class ShoppingBill {

void bill(int price,int quantity){

42
int total = price * quantity;
[Link]("Total Bill = " + total);
}

public static void main(String[] args){

Scanner sc = new Scanner([Link]);

[Link]("Enter price:");
int price = [Link]();

[Link]("Enter quantity:");
int quantity = [Link]();

ShoppingBill obj = new ShoppingBill();


[Link](price,quantity);
}
}
Output:
Enter price:
525
Enter quantity:
6
Total Bill = 3150
3. Return Types
Definition
A return type specifies the value returned by the method.

Example Program 1
import [Link];

public class ReturnExample1 {

int add(int a,int b){


return a+b;
}

public static void main(String[] args){

Scanner sc = new Scanner([Link]);

int a = [Link]();
int b = [Link]();

43
ReturnExample1 obj = new ReturnExample1();

int result = [Link](a,b);

[Link]("Sum = " + result);


}
}
Output:
6
8
Sum = 14
Example Program 2
import [Link];

public class ReturnExample2 {

int cube(int n){


return n*n*n;
}

public static void main(String[] args){

Scanner sc = new Scanner([Link]);

int num = [Link]();

ReturnExample2 obj = new ReturnExample2();

[Link]("Cube = " + [Link](num));


}
}
Output:

5
Cube = 125
Scenario-Based Program
Scenario-A salary system calculates yearly salary.
import [Link];

public class SalaryCalculator {

int calculateSalary(int monthly){


return monthly * 12;
}

44
public static void main(String[] args){

Scanner sc = new Scanner([Link]);

[Link]("Enter monthly salary:");

int salary = [Link]();

SalaryCalculator obj = new SalaryCalculator();

int yearly = [Link](salary);

[Link]("Yearly Salary = " + yearly);


}
}
Output:
Enter monthly salary:
55000
Yearly Salary = 660000
4. Method Overloading
Definition
Method overloading means same method name with different parameters.
Example Program 1
import [Link];

public class Overload1 {

int add(int a,int b){


return a+b;
}

int add(int a,intb,int c){


return a+b+c;
}

public static void main(String[] args){

Scanner sc = new Scanner([Link]);

int a = [Link]();
int b = [Link]();
int c = [Link]();

45
Overload1 obj = new Overload1();

[Link]([Link](a,b));
[Link]([Link](a,b,c));
}
}
Output:
6
8
7
14
21

Example Program 2
public class Overload2 {

double area(double r){


return 3.14*r*r;
}

int area(int l,intb){


return l*b;
}

public static void main(String[] args){

Overload2 obj = new Overload2();

[Link]([Link](5));
[Link]([Link](4,6));
}
}
Output:
78.5
24
Scenario-Based Program
Scenario-A calculator performs different operations based on inputs.
import [Link];

public class Calculator {

int calculate(int a,int b){


return a+b;
}

46
int calculate(int a,intb,int c){
return a*b*c;
}

public static void main(String[] args){

Scanner sc = new Scanner([Link]);

int a = [Link]();
int b = [Link]();
int c = [Link]();

Calculator obj = new Calculator();

[Link]("Addition = " + [Link](a,b));


[Link]("Multiplication = " + [Link](a,b,c));
}
}
Output:
11
7
6
Addition = 18
Multiplication = 462
5. Class Creation & Object Creation
Definition
• Class → Blueprint of an object
• Object → Instance of a class
Example Program 1
import [Link];

class Student{

int id;
String name;

void display(){
[Link](id+" "+name);
}

public static void main(String[] args){


Scanner sc = new Scanner([Link]);

47
Student s = new Student();
[Link] = [Link]();
[Link] = [Link]();

[Link]();
}
}
Output:
52
7
52 7
Example Program 2
import [Link];

class Car{

String model;
int year;

void show(){
[Link](model+" "+year);
}

public static void main(String[] args){

Scanner sc = new Scanner([Link]);

Car c = new Car();

[Link] = [Link]();
[Link] = [Link]();

[Link]();
}
}
Output:
bmw
2025
bmw 2025

Scenario-Based Program
Scenario-A college system stores student details.
import [Link];

48
class College{

int roll;
String name;

void display(){
[Link]("Roll: "+roll);
[Link]("Name: "+name);
}

public static void main(String[] args){

Scanner sc = new Scanner([Link]);

College s1 = new College();

[Link]("Enter roll:");
[Link] = [Link]();

[Link]("Enter name:");
[Link] = [Link]();

[Link]();
}
}
Output:
Enter roll:
52
Enter name:
Vibha
Roll: 52
Name: Vibha
6. this Keyword
Definition
The this keyword refers to the current object of the class.
Example Program 1
class Demo{

int x;

void set(int x){


this.x = x;
}

49
void show(){
[Link](x);
}
public static void main(String[] args){

Demo d = new Demo();

[Link](10);

[Link]();
}
}
Output:
10
Example Program 2
class Test{

int a;

void setValue(int a){


this.a = a;
}

void display(){
[Link](a);
}

public static void main(String[] args){

Test t = new Test();

[Link](20);

[Link]();
}
}
Output:
20
Scenario-Based Program
Scenario- An employee management system stores employee details.
import [Link];

class Employee{

50
int id;
String name;

void setData(int id,String name){


[Link] = id;
[Link] = name;
}

void display(){
[Link](id+" "+name);
}

public static void main(String[] args){

Scanner sc = new Scanner([Link]);

Employee e = new Employee();

int id = [Link]();
String name = [Link]();

[Link](id,name);

[Link]();
}
}
Output:
52
Vibha
52 vibha

Session 5 - Constructors:

Constructor is a method which has a same name as class name & it is invoked automatically
when object of particular class is created.
A constructor does not contain return [Link] is used to initialize the object.
If there is no constructor in a class, compiler automatically creates a default constructor.
There are two types of Constructors
1) No-Argument Constructor or zero Argument Constructor
2) Parameterized Constructor
1) No-Argument Constructor or zero Argument Constructor:
No-Argument Constructor is also called as Empty Constructor which has no arguments.

51
Example:
class Employee
{
inteid;
String name;
float salary;
longmobileNumber;

Employee()
{
eid = 100;
name = "raju";
salary = 75000;
mobileNumber = 9876543210L;
}

voidgetDetails()
{
[Link]("eid="+eid);
[Link]("name="+name);
[Link]("salary="+salary);
[Link]("mobileNumber="+mobileNumber);
}
}

public class EmployeeDemo {


public static void main(String[] args) {
Employee e1 = new Employee();
[Link]();
}
}

Output:
eid=100
name=raju
salary=75000.0
mobileNumber=9876543210

2) Parameterized Constructor:
Constructors with parameters is known as Parameterized Constructor.
Example:
class Employee
{
inteid;

52
String name;
float salary;
longmobileNumber;

Employee(int e,Stringn,floats,long m)
{
eid = e;
name = n;
salary = s;
mobileNumber = m;
}
voidgetDetails()
{
[Link]("eid="+eid);
[Link]("name="+name);
[Link]("salary="+salary);
[Link]("mobileNumber="+mobileNumber);
}
}

public class EmployeeDemo {


public static void main(String[] args) {
Employee e1 = new Employee(100,"raju",75000,9876543210L);
[Link]();
}
}
Output:
eid=100
name=raju
salary=75000.0
mobileNumber=9876543210

Constructor overloading:
Using more than one constructor in a class is called as constructor overloading .
Example:
class Employee
{
inteid;
String name;
float salary;
longmobileNumber;
Employee()
{

53
}
Employee(int id)
{
eid= id;
}
Employee(int e,Stringn,floats,long m)
{
eid = e;
name = n;
salary = s;
mobileNumber = m;
}
voidgetDetails()
{
[Link]("eid="+eid);
[Link]("name="+name);
[Link]("salary="+salary);
[Link]("mobileNumber="+mobileNumber);
}
}
public class EmployeeDemo {
public static void main(String[] args) {
Employee e1 = new Employee();
[Link]();

Employee e2 = new Employee(200);


[Link]();

Employee e3 = new Employee(100,"raju",75000,9876543210L);


[Link]();
}
}
Output:
eid=0
name=null
salary=0.0
mobileNumber=0
eid=200
name=null
salary=0.0
mobileNumber=0
eid=100
name=raju
salary=75000.0

54
mobileNumber=9876543210

Encapsulation:
• Binding (or wrapping) code and data together into a single unit is known as
encapsulation.
• For example: capsule, it is wrapped with different medicines.
• A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
Advantage of Encapsulation:
• It is a way to achieve data hiding in Java because other class will not be able to access
the data through the private data members.
Example:
class Employee
{
private int eid;
private String name;
private float salary;
private long mobileNumber;

public void setEid(int eid) {


if(eid>0)
[Link] = eid;
else
{
[Link]("eidcan not be -ve or 0, plz give +veeid");
[Link] = 1;
}

}
public void setName(String name) {
[Link] = name;
}
public void setSalary(float salary) {
[Link] = salary;
}
public void setMobileNumber(long mobileNumber) {
[Link] = mobileNumber;
}
public int getEid() {
returneid;
}
public String getName() {
return name;

55
}
public float getSalary() {
return salary;
}
public long getMobileNumber() {
returnmobileNumber;
}
}

public class EmployeeDemo {


public static void main(String[] args) {
Employee e1 = new Employee();
[Link](-100);
[Link](200);
[Link]("raju");
[Link](75000);
[Link](9876543210L);

[Link]("eid="+[Link]());
[Link]("name="+[Link]());
[Link]("salary="+[Link]());
[Link]("MobileNumber="+[Link]());
}
}

Output:
eidcan not be -ve or 0, plz give +veeid
eid=200
name=raju
salary=75000.0
MobileNumber=9876543210

Access Modifiers:
Access Modifiers defines the boundary and scope to access the method, variable and class etc.
Java has define four type of access specifier such as:
public
private
protected
default
if you are not define any access specifier so it will be as ‘default’ access specifier for
varibles/methods.
How to compile java package:
Syntax: javac -d directory javafilename
Ex: javac -d . [Link]

56
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).
How to run java package program:
You need to use fully qualified name
[Link]
public :If you declare any variable /method as public access specifier so you can used it from
anywhere.
Example:
[Link]:
package p1;
public class A
{
public void display()
{
[Link]("welcome to java");
}
}
/*
compile: javac -d . [Link]
*/
[Link]:
package p2;
import p1.A;
class B
{
public static void main(String args[])
{
A obj = new A();
[Link]();
}
}

/*
compile: javac -d . [Link]
run: java p2.B
*/
Output:
welcome to java

private :If you declare any variable /method as private access specifier so you can used within
the java class itself, not from outside the class,package and others.
Example:
[Link]:

57
class A
{
private void display()
{
[Link]("welcome to java");
}
}
class B
{
public static void main(String args[])
{
A obj = new A();
[Link](); // compilation error
}
}
Output:
compilation error
default:If you declare any variable /methods as default so you can access those variable/method
with the package itself.
Example:
[Link]:
package p1;
public class A
{
void display()
{
[Link]("welcome to java");
}
}

/*
compile: javac -d . [Link]
*/
[Link]:
package p2;
import p1.A;
class B
{
public static void main(String args[])
{
A obj = new A();
[Link](); // compilation error
}
}

58
/*
compile: javac -d . [Link]
run: java p2.B
*/
Output:
compilation error

Protected: if your variable/method is declared as protected so that Variables/methods can be


access same Package and different package but it should be sub class.
Example:
[Link]:
package p1;
public class A
{
protected void display()
{
[Link]("welcome to java");
}
}
/*
javac -d . [Link]
*/

package p2;
import p1.A;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
[Link]();
}
}
/*
javac -d . [Link]
java p2.B
*/
Output:
welcome to java

59
Session 6 - Inheritance & Polymorphism
1. Inheritance
Definition
Inheritance is an Object-Oriented Programming (OOP) concept where one class inherits the
properties and methods of another class.
• Parent Class → Superclass
• Child Class → Subclass
Inheritance helps in:
• Code reusability
• Reducing redundancy
• Better program structure
Syntax
class Parent {
// variables and methods
}

class Child extends Parent {


// additional variables and methods
}
The keyword extends is used to inherit the parent class.
2. Types of Inheritance

1. Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the properties and
behavior of a single-parent class. Sometimes, it is also known as simple inheritance.

60
Example Program 1
import [Link];
class Animal {
void eat() {
[Link]("Animal eats food");
}
}
class Dog extends Animal {
void bark() {
[Link]("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link](); // inherited method
[Link](); // dog method
}
}
Output:
Animal eats food
Dog barks

Example Program 2
import [Link];
public class Test {
public static void main(String[] args) {
// Creating object of subclass invokes base class constructor
Car obj = new Car();

61
}
}
//Super class
class Vehicle {
Vehicle() {
[Link]("This is a Vehicle");
}
}
// Subclass
class Car extends Vehicle {
Car() {
[Link]("This Vehicle is Car");
}
}
Output:
This is a Vehicle
This Vehicle is Car

Example Program 3
import [Link];
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
Marks obj = new Marks();
[Link](sc);
[Link](sc);
[Link]();
}
}
class Student
{
int id;
String name;
void getDetails(Scanner sc)
{

62
[Link]("Enter Student ID:");
id = [Link]();
[Link]("Enter Student Name:");
name = [Link]();
}
}
class Marks extends Student
{
int marks;
void getMarks(Scanner sc)
{
[Link]("Enter Marks:");
marks = [Link]();
}
void display()
{
[Link]("ID: " + id);
[Link]("Name: " + name);
[Link]("Marks: " + marks);
}
}
Output:
Enter Student ID:
52
Enter Student Name:
vibha
Enter Marks:
98
ID: 52
Name: vibha
Marks: 98

2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived
class also acts as the base class for other classes.

63
Example Program 1
public class Main
{
public static void main(String args[])
{
Puppy p = new Puppy();
[Link]();
[Link]();
[Link]();
}
}
class Animal
{
void eat()
{
[Link]("Animal eats food");
}
}
class Dog extends Animal
{
void bark()
{
[Link]("Dog barks");
}
}
class Puppy extends Dog
{
void weep()
{
[Link]("Puppy weeps");
}

64
}
Output:
Animal eats food
Dog barks
Puppy weeps
Example Program 2
public class Main
{
public static void main(String args[])
{
Manager m = new Manager();
[Link]();
[Link]();
[Link]();
}
}
class Person
{
void showPerson()
{
[Link]("Person class");
}
}
class Employee extends Person
{
void showEmployee()
{
[Link]("Employee class");
}
}
class Manager extends Employee
{
void showManager()
{
[Link]("Manager class");
}
}
Output:
Person class
Employee class
Manager class
Hierarchical Inheritance:-

65
Hierarchical inheritance is a type of inheritance in which a parent class can have multiple child
classes. In other words, it is a type of inheritance in which a parent class serves as a base for
multiple child classes, and each child class inherits properties and methods from the parent class.

Example Program 1
public class Main
{
public static void main(String args[])
{
Dog d = new Dog();
Cat c = new Cat();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
class Animal
{
void eat()
{
[Link]("Animal eats");
}
}
class Dog extends Animal
{
void bark()
{
[Link]("Dog barks");
}

66
}
class Cat extends Animal
{
void meow()
{
[Link]("Cat meows");
}
}
Output:
Animal eats
Dog barks
Animal eats
Cat meows
Example Program 2
public class Main
{
public static void main(String args[])
{
Circle c = new Circle();
Rectangle r = new Rectangle();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
class Shape
{
void draw()
{
[Link]("Drawing shape");
}
}
class Circle extends Shape
{
void circle()
{
[Link]("Drawing Circle");
}
}
class Rectangle extends Shape
{
void rectangle()
{

67
[Link]("Drawing Rectangle");
}
}
Output:
Drawing shape
Drawing Circle
Drawing shape
Drawing Rectangle
Multiple Inheritance (Using Interfaces)
Java does not support multiple inheritance with classes because it creates ambiguity
problems.
However, Java supports multiple inheritance using interfaces.

Example Program 1
public class Main
{
public static void main(String args[])
{
Bat b = new Bat();
[Link]();
[Link]();
}
}
interface Animal
{
void eat();
}
interface Bird
{
void fly();
}
class Bat implements Animal, Bird
{
public void eat()
{

68
[Link]("Bat eats insects");
}
public void fly()
{
[Link]("Bat can fly");
}
}
Output:
Bat eats insects
Bat can fly

Example Program 2
public class Main
{
public static void main(String args[])
{
Machine m = new Machine();
[Link]();
[Link]();
}
}
interface Printer
{
void print();
}
interface Scanner
{
void scan();
}
class Machine implements Printer, Scanner
{
public void print()
{
[Link]("Printing document");
}
public void scan()
{
[Link]("Scanning document");
}
}
Output:
Printing document
Scanning document

69
Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. In Java, we can achieve hybrid
inheritance only through Interfaces if we want to involve multiple inheritance to implement
Hybrid inheritance.

Example Program 1
Hybrid Inheritance (Hierarchical + Multiple using Interface)
public class Main
{
public static void main(String args[])
{
Dog d = new Dog();
Cat c = new Cat();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
interface Animal
{
void eat();
}
class Dog implements Animal
{
public void eat()
{
[Link]("Dog eats meat");
}
void bark()
{
[Link]("Dog barks");
}

70
}
class Cat implements Animal
{
public void eat()
{
[Link]("Cat eats fish");
}
void meow()
{
[Link]("Cat meows");
}
}
Output:
Dog eats meat
Dog barks
Cat eats fish
Cat meows

Example Program 2
Hybrid Inheritance (Multilevel + Interface)
public class Main
{
public static void main(String args[])
{
ElectricCar e = new ElectricCar();
[Link]();
[Link]();
}
}
interface Vehicle
{
void start();
}
class Car implements Vehicle
{
public void start()
{
[Link]("Car starts");
}
}
class ElectricCar extends Car
{
void charge()
{

71
[Link]("Electric car is charging");
}
}
Output:
Car starts
Electric car is charging
extends Keyword
Definition
The extends keyword is used to inherit properties from the parent class.
Syntax
class Child extends Parent
Example 1
public class Main
{
public static void main(String[] args)
{
Child obj = new Child(); // Creating object of Child class
[Link](); // Calling parent class method
[Link](); // Calling child class method
}
}
class Parent
{
void display()
{
[Link]("Parent class method");
}
}
class Child extends Parent
{
void show()
{
[Link]("Child class method");
}
}
Output:
Parent class method
Child class method
Example 2
public class Main
{
public static void main(String[] args)
{

72
Student s = new Student(); // Creating object of Student class

[Link](); // Calling parent class method


[Link](); // Calling child class method
}
}
class Person
{
void info()
{
[Link]("Person information");
}
}
class Student extends Person
{
void study()
{
[Link]("Student studies");
}
}
Output:
Person information
Student studies
Scenario Program -Hospital System
public class Main
{
public static void main(String args[])
{
Doctor d = new Doctor();
[Link]();
[Link]();
}
}
class Hospital
{
void hospitalName()
{
[Link]("City Hospital");
}
}
class Doctor extends Hospital
{
void doctorName()
{

73
[Link]("Doctor Name: Dr. Rao");
}
}
Output:
City Hospital
Doctor Name: Dr. Rao
Method Overriding
Definition
Method overriding means child class provides a different implementation of parent class
method.
Diagram

Example 1
public class Main
{
public static void main(String args[])
{
Dog d = new Dog();
[Link]();
}
}
class Animal
{
void sound()
{
[Link]("Animal makes sound");
}
}
class Dog extends Animal
{
void sound()
{

74
[Link]("Dog barks");
}
}
Output:
Dog barks
Example 2
public class Main
{
public static void main(String[] args)
{
Circle c = new Circle(); // Creating object of Circle class
[Link](); // Calling overridden method
}
}
class Shape
{
void draw()
{
[Link]("Drawing shape");
}
}
class Circle extends Shape
{
void draw()
{
[Link]("Drawing circle");
}
}
Output:
Drawing circle

Scenario Program - Payment System


public class Main
{
public static void main(String args[])
{
CreditCard c = new CreditCard();
[Link]();
}
}
class Payment
{
void pay()
{

75
[Link]("Processing payment");
}
}
class CreditCard extends Payment
{
void pay()
{
[Link]("Payment using Credit Card");
}
}
Output:
Payment using Credit Card

Compile Time Polymorphism (Method Overloading)


Definition
Compile-Time Polymorphism occurs when a method is overloaded with the same name but
different parameters.
The compiler decides which method to call during compile time.
Example 1
class MathOperation
{
int add(int a, int b)
{
return a + b;
}
int add(int a, int b, int c)
{
return a + b + c;
}
public static void main(String[] args)
{
MathOperation obj = new MathOperation();
int result1 = [Link](10, 20);
int result2 = [Link](10, 20, 30);
[Link]("Sum of two numbers: " + result1);
[Link]("Sum of three numbers: " + result2);
}
}
Output:
Sum of two numbers: 30
Sum of three numbers: 60

76
Example 2
class Display
{
void show(int a)
{
[Link](a);
}
void show(String s)
{
[Link](s);
}
public static void main(String[] args)
{
Display d = new Display(); // Creating object
[Link](100); // Calling integer method
[Link]("Hello Java"); // Calling string method
}
}
Output:
100
Hello Java
Runtime Polymorphism
Definition
Runtime Polymorphism occurs when the method call is resolved at runtime instead of
compile time.
It is achieved using:
• Method Overriding
• Inheritance
The method that gets executed depends on the object created at runtime.
Example 1
public class Main
{
public static void main(String[] args)
{
Animal a = new Dog(); // Parent reference, child object
[Link](); // Calls Dog method
}
}
class Animal
{
void sound()
{
[Link]("Animal makes sound");

77
}
}
class Dog extends Animal
{
void sound()
{
[Link]("Dog barks");
}
}
Output:
Dog barks
Example 2
public class Main
{
public static void main(String[] args)
{
Vehicle v = new Bike();
[Link]();
}
}
class Vehicle
{
void run()
{
[Link]("Vehicle is running");
}
}
class Bike extends Vehicle
{
void run()
{
[Link]("Bike is running");
}
}
Output:
Bike is running
Scenario Program - Notification System
public class Main
{
public static void main(String args[])
{
Notification n = new EmailNotification();
[Link]();

78
}
}
class Notification
{
void send()
{
[Link]("Sending notification");
}
}
class EmailNotification extends Notification
{
void send()
{
[Link]("Sending Email Notification");
}
}
Output:
Sending Email Notification
Session 7 - Abstraction & Interface:
Abstraction & Interface:
The method which is defined in the class with implementation i.e with body is called as
concrete method.
The class which is defined with all the methods as concrete methods is called as concrete class.
We can create the objects of concrete class whenever it is required in application.
The method which is defined in the class without implementation i.e without body is called as
abstract method. All the abstract methods must be defined in class with abstract keyword.
The class which is defined with some abstract methods is called abstract class. The abstract
class must be defined with abstract keyword.
We cannot create an object of abstract class but we can create the reference variables of abstract
class whenever it is required.
We can inherit the properties of abstract class into a subclass,in such case the subclass must be
implemented with all the abstract methods of super class otherwise subclass will become as
abstract class.
• Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
• Another way, it shows only important things to the user and hides the internal details for
example sending sms, you just type the text and send the message. You don't know the
internal processing about the message delivery.
• Ways to achieve Abstaction
• There are two ways to achieve abstraction in java
1) Abstract class (0 to 100%)
2) Interface (100%)

79
abstract example on GraphicObject
abstract class GraphicObject
{
abstract void drawShape();
voidfillColour()
{
[Link]("filled with blue colour");
}
}

class Rectangle extends GraphicObject


{
voiddrawShape() {
[Link]("drawing Rectangle");
}
}

class Line extends GraphicObject


{
voiddrawShape() {
[Link]("drawing Line");
}
}

class Square extends GraphicObject


{
voiddrawShape() {
[Link]("drawing Square");
}
}

class Circle extends GraphicObject


{
voiddrawShape() {
[Link]("drawing Circle");
}
}

public class AbstractDemo {

public static void main(String[] args) {

//GraphicObject g = new GraphicObject(); Compilation Error

80
GraphicObject g;

Rectangle r = new Rectangle();


[Link]();
[Link]();

Line l = new Line();


[Link]();
[Link]();

Square s = new Square();


[Link]();
[Link]();

Circle c = new Circle();


[Link]();
[Link]();

g=r;
[Link]();
[Link]();
}
}

Output:
drawing Rectangle
filled with blue colour
drawing Line
filled with blue colour
drawing Square
filled with blue colour
drawing Circle
filled with blue colour
drawing Rectangle
filled with blue colour

Abstract example on Bike

abstract class Bike


{
abstract void run();
}

81
classSplender extends Bike
{
void run() {
[Link]("running 60KMPH");
}
}

class Honda extends Bike


{
void run() {
[Link]("running 59KMPH");
}
}

class Yamaha extends Bike


{
void run() {
[Link]("running 80KMPH");

}
}
public class AbstractDemoOne {

public static void main(String[] args) {

Splender s = new Splender();


[Link]();

Honda h = new Honda();


[Link]();

Yamaha y = new Yamaha();


[Link]();

Bike b;
b=h;
[Link]();
}
}

Output:
running 60KMPH
running 59KMPH
running 80KMPH

82
running 59KMPH

Interface:
An interface is defined with a set of abstract methods in other words all the methods of an
interface are by default public, abstract methods.
We cannot create an object of an interface but we can create the reference of an interface
whenever it is required in the application.
Any class can implement an interface, in such case the class must be implemented with all the
methods of the respective interface otherwise the class will become as abstract class.
When we assign subclass reference variable to super class reference variable, then through an
super class reference variable we can only execute the interface methods which means we can't
execute the non interface methods.
use of interface?
1) It is used to achieve fully abstraction.
2) It can be used to achieve loose coupling.
• NOTE: The java compiler adds public and abstract keywords before the interface method
and public, static and final keywords before data members.
Interfaces Definition Syntax:
interfaceInterfaceName {
// Constant/Final Variable Declaration
// Methods Declaration –
}

interface example on Speaker:


interface Speaker
{
void speak();
}

class Politician implements Speaker


{
public void speak() {
[Link]("Talks about politics");
}
}

class Priest implements Speaker


{
public void speak() {
[Link]("Talks about god");
}
}

class Lecturer implements Speaker


83
{
public void speak() {
[Link]("Talks about subject");
}
public void write()
{
[Link]("writes on the board");
}
}

public class InterfaceDemo {


public static void main(String[] args) {
Politician p = new Politician();
[Link]();

Priest p1 = new Priest();


[Link]();

Lecturer l = new Lecturer();


[Link]();
[Link]();

Speaker s ;
s = l;
[Link]();
//[Link](); C.E
}
}

Output:
Talks about politics
Talks about god
Talks about subject
writes on the board
Talks about subject

interface example (interface extends from another interface)


interface A
{
void f1();
}
interface B extends A
{
void f2();

84
}

class C implements A
{
public void f1() {
[Link]("in f1() of class C");
}
}

class D implements B
{
public void f1() {
[Link]("in f1() of class D");
}

public void f2() {


[Link]("in f2() of class D");
}
}
public class InterfaceDemo1 {
public static void main(String[] args) {

C c = new C();
c.f1();

D d = new D();
d.f1();
d.f2();

A a;
a = c;
a.f1();

B b;
b = d;
b.f1();
b.f2();
}
}

Output:
in f1() of class C
in f1() of class D
in f2() of class D

85
in f1() of class C
in f1() of class D
in f2() of class D

Before Java 8, interfaces could have only abstract methods. The implementation of these
methods has to be provided in a separate class. So, if a new method is to be added in an interface,
then its implementation code has to be provided in the class implementing the same interface. To
overcome this issue, Java 8 has introduced the concept of default methods which allow the
interfaces to have methods with implementation without affecting the classes that implement the
interface. You can override default method also to provide more specific implementation for the
method.
Java 8 Default Method in Interface on GraphicObject example
interfaceGraphicObject
{
voiddrawShape();
default void fillColour()
{
[Link]("filled with blue colour");
}
}

class Rectangle implements GraphicObject


{
public void drawShape() {
[Link]("drawing Rectangle");

}
}

class Line implements GraphicObject


{
public void drawShape() {
[Link]("drawing Line");
}
}

class Square implements GraphicObject


{
public void drawShape() {
[Link]("drawing Square");
}
}

class Circle implements GraphicObject

86
{
public void drawShape() {
[Link]("drawing Circle");
}
}

class Main{
public static void main(String args[]){
GraphicObject g = new Rectangle();
[Link]();
[Link]();

g = new Line();
[Link]();
[Link]();

g = new Rectangle();
[Link]();
[Link]();

g = new Square();
[Link]();
[Link]();

g = new Circle();
[Link]();
[Link]();
}
}
Output:
drawing Rectangle
filled with blue colour
drawing Line
filled with blue colour
drawing Rectangle
filled with blue colour
drawing Square
filled with blue colour
drawing Circle
filled with blue colour

Java 8 Static Method in Interface on GraphicObject example


interfaceGraphicObject
{

87
voiddrawShape();
static void fillColour()
{
[Link]("filled with blue colour");
}
}

class Rectangle implements GraphicObject


{
public void drawShape() {
[Link]("drawing Rectangle");
}
}

class Line implements GraphicObject


{
public void drawShape() {
[Link]("drawing Line");
}
}

class Square implements GraphicObject


{
public void drawShape() {
[Link]("drawing Square");
}
}

class Circle implements GraphicObject


{
public void drawShape() {
[Link]("drawing Circle");
}
}
class Main{
public static void main(String args[]){
GraphicObject g = new Rectangle();
[Link]();
[Link]();

g = new Line();
[Link]();
[Link]();

88
g = new Rectangle();
[Link]();
[Link]();
g = new Square();
[Link]();
[Link]();

g = new Circle();
[Link]();
[Link]();
}
}
Output:
drawing Rectangle
filled with blue colour
drawing Line
filled with blue colour
drawing Rectangle
filled with blue colour
drawing Square
filled with blue colour
drawing Circle
filled with blue colour

Program to demonstrate multiple inheritance through default methods


interface PI1
{
default void show()
{
[Link]("Default PI1");
}
}

interface PI2
{
default void show()
{
[Link]("Default PI2");
}
}

classTestClass implements PI1, PI2


{
public void show()

89
{
[Link]();
[Link]();
}
}

class Main
{
public static void main(String args[])
{
TestClass d = new TestClass();
[Link]();
}
}

Output:
Default PI1
Default PI2

Difference between abstract class and interface


Feature Abstract Class Interface
A class that cannot be instantiated and
A reference type that contains abstract
Definition may contain abstract and concrete
methods (used for full abstraction)
methods
Keyword abstract class interface
Traditionally only abstract methods
Can have abstract and non-abstract
Methods (Java 8 allows default and static
methods
methods)
Variables are public, static, final by
Variables Can have instance variables
default
Constructors Allowed Not allowed
Access Methods can be private, protected,
Methods are public by default
Modifiers public
A class can extend only one abstract A class can implement multiple
Inheritance
class interfaces
Used when classes share common
Implementation Used to define a contract for classes
behavior

90
Session 8 - Exception Handling & File I/O
1. Exception Handling in Java
Definition
Exception Handling is used to handle runtime errors so that the program does not crash and
continues execution normally.
Example errors:
• Division by zero
• File not found
• Array index out of bounds
Exception Handling Flow Diagram

Explanation:
Program Code
|
|
try
|
Exception Occurs
|
catch
|
finally

Types of Exceptions
1. Checked Exceptions
Checked at compile time.
Examples:
• IOException
• FileNotFoundException
Example:
FileReader file = new FileReader("[Link]");

91
2. Unchecked Exceptions
Checked at runtime.
Examples:
• ArithmeticException
• NullPointerException
• ArrayIndexOutOfBoundsException
Example:
int a = 10/0;

Example Program 1 (Arithmetic Exception)


class ExceptionExample1
{
public static void main(String[] args)
{
try
{
int a = 10;
int b = 0;
int c = a / b;
[Link](c);
}
catch(ArithmeticException e)
{
[Link]("Cannot divide by zero");
}
finally
{
[Link]("Program finished");
}
}
}
Output
Cannot divide by zero
Program finished
Example Program 2 (Array Exception)
class ExceptionExample2
{
public static void main(String[] args)
{
try
{
int arr[] = {1,2,3};

92
[Link](arr[5]);
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Array index error");
}
finally
{
[Link]("Execution completed");
}
}
}
Output
Array index error
Execution completed

try – catch – finally


Syntax
try
{
// risky code
}
catch(Exception e)
{
// handling code
}
finally
{
// always executes
}

throw and throws


throw
Used to manually create an exception.
Example:
throw new ArithmeticException("Error occurred");

throws
Used in method declaration to declare exceptions.
Example:
void readFile() throws IOException

93
Example Program (throw)
class ThrowExample
{
public static void main(String[] args)
{
try
{
int age = 15;

if(age < 18)


{
throw new ArithmeticException("Not eligible to vote");
}
else
{
[Link]("Eligible to vote");
}
}
catch(ArithmeticException e)
{
[Link]("Exception caught: " + [Link]());
}
}
}
Output:
Exception caught: Not eligible to vote

2. File I/O in Java

File I/O is used to read and write data from files.


Common classes:
• FileReader
• BufferedReader
• FileWriter

94
File Reading Diagram

Explanation:
Text File
|
FileReader
|
BufferedReader
|
Program

Example Program 1 (FileReader)


import [Link];
class FileReadExample
{
public static void main(String[] args) throws Exception
{
FileReader fr = new FileReader("[Link]");
int i;
while((i = [Link]()) != -1)
{
[Link]((char)i);
}
[Link]();
}
}

95
Output :
If [Link] contains:
Hello Java
Welcome to File Handling
The output will be:
Hello Java
Welcome to File Handling
Example Program 2 (BufferedReader)
import [Link];
import [Link];

class BufferedExample
{
public static void main(String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new FileReader("[Link]"));

String line;

while((line = [Link]()) != null)


{
[Link](line);
}

[Link]();
}
}
Example File Content
Suppose your [Link] file contains:
Hello Java
File Handling Example
BufferedReader Program
Output:
Hello Java
File Handling Example
BufferedReader Program

Example Program 3 (FileWriter)


import [Link];

class FileWriteExample
{
public static void main(String[] args) throws Exception
{

96
FileWriter fw = new FileWriter("[Link]");

[Link]("Hello Java File Handling");

[Link]();

[Link]("Data written to file");


}
}

Scenario-Based Program (Student File System) - This program writes student


data to a file and reads it.
import [Link].*;

class StudentFile
{
public static void main(String[] args) throws Exception
{
FileWriter fw = new FileWriter("[Link]");

[Link]("Student Name: Ravi\n");


[Link]("Marks: 90");

[Link]();

BufferedReader br = new BufferedReader(new FileReader("[Link]"));

String line;

while((line = [Link]()) != null)


{
[Link](line);
}

[Link]();
}
}
Output
Student Name: Ravi
Marks: 90

97
Session 9
Multi Threading:
A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of
execution.
When ever we run the java application the JVM will initially create one thread in the “main”
method of the main class which is called as main thread.
All other threads which are created by the user according to application requirements are called
as user defined threads or child threads.

States of a thread

1) Newly created state or born state: After the creations of Thread instance the thread is in this
state but before the start() method invocation. At this point, the thread is considered not alive.

2) Runnable (Ready-to-run) state:A thread start its life from Runnable state. A thread first
enters runnable state after the invoking of start() method but a thread can return to this state after
either running, waiting, sleeping or coming back from blocked state also. On this state a thread is
waiting for a turn on the processor.

98
3) Running state or execution state: A thread is in running state that means the thread is
currently executing. There is only one way to enter in Running state: the scheduler select a
thread from runnable pool.

4) Dead state or completed state: A thread can be considered dead when its run() method
completes. If any thread comes on this state that means it cannot ever run again.

5) Blocked state or waiting state: A thread can enter in this state because of waiting the
resources that are hold by another thread.

Thread Creation:
Thread can be implemented through any one of two ways:
1) Extending the [Link] Class
2) Implementing the [Link] Interface

1) Extending the [Link] Class


For creating a thread a class have to extend the Thread Class. For creating a thread by this
procedure you have to follow these steps:
i) Extend the [Link] Class.
ii) Override the run( ) method in the subclass from the Thread class to define the code executed
by the thread.
iii) Create an instance of this subclass. This subclass may call a Thread class constructor by
subclass constructor.
iv) Invoke the start( ) method on the instance of the class to make the thread eligible for running.

Program to demonstrate threads creation by extending from "Thread" Class

classChildThread extends Thread {


public void run() {
for (int i = 1; i <= 5; i++)
{

[Link]([Link]().getName()+":"+i);
}
}
}
class Main {
public static void main(String args[]) {
ChildThread c1 = new ChildThread();
ChildThread c2 = new ChildThread();

[Link]("First Thread");
[Link]("Second Thread");

99
[Link]();
[Link]();

for (int i = 10; i >= 6; i--)


{
[Link]([Link]().getName()+":"+i);
}
}
}

Output:

First Thread:1
main:10
main:9
Second Thread:1
Second Thread:2
Second Thread:3
Second Thread:4
Second Thread:5
First Thread:2
First Thread:3
First Thread:4
First Thread:5
main:8
main:7
main:6

2) Implementing the [Link] Interface:


The procedure for creating threads by implementing the Runnable Interface is as follows:
i) A Class implements the Runnable Interface, override the run() method to define the code
executed by thread. An object of this class is Runnable Object.
ii) Create an object of Thread Class by passing a Runnable object as argument.
iii) Invoke the start( ) method on the instance of the Thread class.

Program to demonstrate threads creation by implementing from "Runnable" interface


classChildTh implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++)
{
[Link]([Link]().getName()+":"+i);
}
}

100
}

class Main {
public static void main(String args[]) {
ChildTh c1 = new ChildTh();
ChildTh c2 = new ChildTh();

Thread t1=new Thread(c1);


Thread t2=new Thread(c2);

[Link]("First Thread");
[Link]("Second Thread");

[Link]();
[Link]();

for (int i = 10; i >= 6; i--)


{
[Link]([Link]().getName()+":"+i);
}
}
}

Output:
First Thread:1
First Thread:2
main:10
main:9
main:8
main:7
main:6
Second Thread:1
Second Thread:2
Second Thread:3
Second Thread:4
Second Thread:5
First Thread:3
First Thread:4
First Thread:5

Thread scheduler:
Thread scheduler in java is the part of the JVM that decides which thread should run.
There is no guarantee that which runnable thread will be chosen to run by the thread scheduler.
Only one thread at a time can run in a single process.

101
The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the
threads.
In preemptive scheduling, the highest priority task executes until it enters the waiting or dead
states. Under time slicing, a task executes for a predefined slice of time and then reenters the
pool of ready tasks.
Thread Priority:
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread schedular schedules the threads according to their priority (known as preemptive
scheduling). But it is not guaranteed because it depends on JVM specification that which
scheduling it chooses. 3 constants defined in Thread class:
• public static int MIN_PRIORITY
• public static int NORM_PRIORITY
• public static int MAX_PRIORITY
• Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1
and the value of MAX_PRIORITY is 10.

Example on priority of a Thread


public class Main extends Thread{
public void run(){
[Link]("running thread name
is:"+[Link]().getName());
[Link]("running thread priority
is:"+[Link]().getPriority());
}

public static void main(String[] args) {


[Link]("MIN_PRIORITY="+Thread.MIN_PRIORITY);
[Link]("NORM_PRIORITY="+Thread.NORM_PRIORITY);
[Link]("MAX_PRIORITY="+Thread.MAX_PRIORITY);
[Link]("Thread Name: "+[Link]().getName());
[Link]("Thread Priority: "+[Link]().getPriority());

Main t1=new Main();


Main t2=new Main();
[Link](Thread.MIN_PRIORITY);
[Link](10);
[Link]();
[Link]();
}
}

Output:

102
Thread Priority: 5
running thread name is:Thread-0
running thread priority is:1
running thread name is:Thread-1
running thread priority is:10

Yield():
Yield() method causes to pause current executing thread for giving the chance to remaining
waiting threads of same priority.
If there are no waiting threads or all waiting threads have low priority then the same thread will
continue it’s execution once again.

Example of yield()
classMyThread extends Thread {
public void run() {
for (int i = 1; i <= 100; i++)
{
[Link]([Link]().getName()+":"+i);
}
}
}

public class YieldDemo {


public static void main(String[] args) {
MyThread m1 = new MyThread();
MyThread m2 = new MyThread();

[Link]("First Thread");
[Link]("2nd Thread");
[Link]();
[Link]();

for (int i = 1; i <= 100; i++)


{
// Control passes to child thread
[Link]();
[Link]([Link]().getName()+":"+i);
}
}
}

Output:
main:1
main:2

103
main:3
main:4
main:5
First Thread:1
First Thread:2
2nd Thread:1
First Thread:3
2nd Thread:2
First Thread:4
2nd Thread:3
First Thread:5
2nd Thread:4
2nd Thread:5

Pausing Execution with Sleep():


[Link] causes the current thread to suspend(block) execution for a specified period. This is
an efficient means of making processor time available to the other threads of an application.
Sleep( ) throws InterruptedException.

Example:
classTestSleep extends Thread{
public void run() {
for (int i = 1; i <= 5; i++) {
try {
[Link](2000);
} catch (InterruptedException e) {
[Link](e);
}
[Link]([Link]().getName()+" "+i);
}
}
}

public class SleepDemo {


public static void main(String args[]) {
TestSleep t1 = new TestSleep();
TestSleep t2 = new TestSleep();
[Link]("1st thread");
[Link]("2nd thread");

[Link]();
[Link]();
}
}

104
Output:
2nd thread 1
1st thread 1
2nd thread 2
1st thread 2
2nd thread 3
1st thread 3
2nd thread 4
1st thread 4
2nd thread 5
1st thread 5

join( ):
The join method allows one thread to wait for the completion of another. It is a Thread object
whose thread is currently executing,
[Link]();
causes the current thread to pause execution until it's thread terminates.
Syntax:
public final void join() throws InterruptedException

Example of join()
class Child extends Thread {
public void run() {
for (int i = 1; i <= 5; i++)
[Link]([Link]().getName()+" "+i);
}
}

class Main {
public static void main(String args[]) {
Child c1 = new Child();
Child c2 = new Child();

[Link]();
try {
[Link]();
} catch (InterruptedException e) {
[Link]();
}
[Link]();

if ([Link]())
[Link]("Thread c1 is alive.");

105
if ([Link]())
[Link]("Thread c2 is alive.");

for (int i = 5; i >= 1; i--)


[Link]([Link]().getName()+" "+i);
}
}

Output:
Thread-0 1
Thread-0 2
Thread-0 3
Thread-0 4
Thread-0 5
Thread-1 1
Thread c2 is alive.
Thread-1 2
Thread-1 3
Thread-1 4
Thread-1 5
main 5
main 4
main 3
main 2
main 1

Synchronization: it is a process in which if two or more threads need to access a shared


resource, allows only one thread at a time to access the shared resource. This keeps the data
consistency.
Example on Synchronization
class Display {
synchronized void wish(String name) {
for (int i = 0; i < 5; i++) {
[Link]("Good morning ");

try {
[Link](3000);
} catch (InterruptedException e) {
[Link]("exception is " + e);
}
[Link](name);
}
}

106
}

classMyThreadt extends Thread {


Display d;
String name;

MyThreadt(Display d, String name) {


this.d = d;
[Link] = name;
}

public void run() {


[Link](name);
}
}

classSynchronizedDemo {
public static void main(String[] args) {

Display d1 = new Display();


MyThreadt t1 = new MyThreadt(d1, "raju");
MyThreadt t2 = new MyThreadt(d1, "rani");

[Link]();
[Link]();
}
}

Output:
Good morning raju
Good morning raju
Good morning raju
Good morning raju
Good morning raju
Good morning rani
Good morning rani
Good morning rani
Good morning rani
Good morning rani

Session 10 - Collections Framework

107
1. Java Collections Framework

The Java Collections Framework (JCF) is a set of classes and interfaces used to store and
manipulate groups of objects.

It provides:

• Dynamic data structures


• Searching
• Sorting
• Data manipulation

Main Interfaces

2. LIST (ArrayList)

108
Definition

A List is an ordered collection that allows duplicate elements. ArrayList is a class in the Java
Collections Framework that implements the List interface.

Characteristics

• Maintains insertion order


• Allows duplicates
• Elements accessed by index

Example Classes

• ArrayList
• LinkedList
• Vector

ArrayList Diagram

Duplicates allowed and ordered.

Example Program 1 – ArrayList

import [Link];

public class ArrayListExample1


{
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<>();

[Link]("Java");
[Link]("Python");
[Link]("C++");
[Link]("Java");

109
[Link]("Elements in List:");
for(String lang : list)
{
[Link](lang);
}
}
}
Output

Elements in List:
Java
Python
C++
Java

Example Program 2 – ArrayList with Index

import [Link];

public class ArrayListExample2


{
public static void main(String[] args)
{
ArrayList<Integer> numbers = new ArrayList<>();

[Link](10);
[Link](20);
[Link](30);
[Link]("Second element: " + [Link](1));
[Link](0);
[Link]("After removing first element:");
[Link](numbers);
}
}
Output:
Second element: 20
After removing first element:
[20, 30]

Scenario Based Problem

Problem - Store student names in a list and display them.

110
import [Link];

public class StudentList


{
public static void main(String[] args)
{
ArrayList<String> students = new ArrayList<>();

[Link]("Rahul");
[Link]("Anjali");
[Link]("Kiran");
[Link]("Rahul");

[Link]("Student List:");

for(String s : students)
{
[Link](s);
}
}
}
Output:
Student List:
Rahul
Anjali
Kiran
Rahul

3. SET (HashSet)

Definition

Set is an interface in the Java Collections Framework that stores unique elements only.

HashSet is a class that implements the Set interface.

Characteristics

• No duplicates
• Unordered
• Faster searching

Example Classes

111
• HashSet
• LinkedHashSet
• TreeSet

HashSet Diagram

Example Program 1 – HashSet Basic

import [Link];

public class HashSetExample1


{
public static void main(String[] args)
{
HashSet<Integer> set = new HashSet<>();
[Link](10);
[Link](20);
[Link](30);
[Link](20);
[Link](set);
}
}

Output

[10, 20, 30]

Example Program 2 – HashSet Loop


import [Link];

112
public class HashSetExample2
{
public static void main(String[] args)
{
HashSet<String> cities = new HashSet<>();

[Link]("Hyderabad");
[Link]("Delhi");
[Link]("Mumbai");

for(String city : cities)


{
[Link](city);
}
}
}
Output:
Delhi
Mumbai
Hyderabad

Scenario Based Problem – Unique Email IDs

Problem - Store user email IDs and avoid duplicates.

import [Link];

public class EmailSet


{
public static void main(String[] args)
{
HashSet<String> emails = new HashSet<>();

[Link]("user1@[Link]");
[Link]("user2@[Link]");
[Link]("user1@[Link]");

[Link]("Registered Emails:");
[Link](emails);
}
}
Output:
Registered Emails:
[user1@[Link], user2@[Link]]

113
4. QUEUE (PriorityQueue)
Definition

A Queue follows FIFO (First In First Out) principle.

Characteristics

• First element inserted → first removed


• Used in scheduling systems

Example Classes

• PriorityQueue
• LinkedList

Queue Diagram

Example Program 1 – PriorityQueue Basic

import [Link];

public class QueueExample1


{
public static void main(String[] args)
{
PriorityQueue<Integer> pq = new PriorityQueue<>();

[Link](50);
[Link](10);
[Link](30);

114
[Link]("Queue Elements: " + pq);
}
}
Output:
Queue Elements: [10, 50, 30]

Example Program 2 – Queue Remove


import [Link];

public class QueueExample2


{
public static void main(String[] args)
{
PriorityQueue<String> queue = new PriorityQueue<>();

[Link]("A");
[Link]("B");
[Link]("C");

[Link]("Removed: " + [Link]());

[Link](queue);
}
}
Output:
Removed: A
[B, C]

Scenario Based Problem – Ticket System


Problem- Process customer tickets using queue.

import [Link];

public class TicketQueue


{
public static void main(String[] args)
{
PriorityQueue<String> tickets = new PriorityQueue<>();

[Link]("Customer1");

115
[Link]("Customer2");
[Link]("Customer3");

[Link]("Serving: " + [Link]());


[Link]("Next: " + [Link]());
}
}
Output:
Serving: Customer1
Next: Customer2

5. MAP (HashMap)

Definition

A Map stores data in key-value pairs.

Characteristics

• Unique keys
• Values can duplicate
• Fast lookup

HashMap Diagram

Example Program 1 – HashMap

import [Link];

public class HashMapExample1


{

116
public static void main(String[] args)
{
HashMap<Integer,String> map = new HashMap<>();

[Link](1,"Java");
[Link](2,"Python");
[Link](3,"C++");

[Link](map);
}
}
Output:
{1=Java, 2=Python, 3=C++}

Example Program 2 – HashMap Loop

import [Link];

public class HashMapExample2


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

[Link](101,"Rahul");
[Link](102,"Anjali");
[Link](103,"Kiran");

for(Integer id : [Link]())
{
[Link](id + " " + [Link](id));
}
}
}
Output:
101 Rahul
102 Anjali
103 Kiran

Scenario Based Problem – Employee Database

117
import [Link];

public class EmployeeMap


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

[Link](1,"Ravi");
[Link](2,"Sneha");
[Link](3,"Arjun");

[Link]("Employee List:");

for(Integer id : [Link]())
{
[Link]("ID: " + id + " Name: " + [Link](id));
}
}
}
Output:
Employee List:
ID: 1 Name: Ravi
ID: 2 Name: Sneha
ID: 3 Name: Arjun

6. TreeMap

Definition

TreeMap is a class in the Java Collections Framework that stores data in Key–Value pairs
and automatically sorts the keys.

It implements the Map interface and internally uses a Red-Black Tree (self-balancing binary
tree)

TreeMap Diagram

118
.

Example Program 1 – TreeMap

import [Link];

public class TreeMapExample1


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

[Link](3,"Java");
[Link](1,"Python");
[Link](2,"C++");

[Link](map);
}
}
Output:
{1=Python, 2=C++, 3=Java}

Example Program 2 – TreeMap Loop

import [Link];

public class TreeMapExample2


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

119
[Link](103,"Rahul");
[Link](101,"Anjali");
[Link](102,"Kiran");

for(Integer id : [Link]())
{
[Link](id + " " + [Link](id));
}
}
}
Output:
101 Anjali
102 Kiran
103 Rahul

Scenario Based Problem – Student Marks System

import [Link];

public class StudentMarks


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

[Link](101,85);
[Link](103,90);
[Link](102,78);

[Link]("Student Marks:");

for(Integer id : [Link]())
{
[Link]("ID: " + id + " Marks: " + [Link](id));
}
}
}
Output:
Student Marks:
ID: 101 Marks: 85
ID: 102 Marks: 78
ID: 103 Marks: 90

120

You might also like