Java Notes
Java Notes
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
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.
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.
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)
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.
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.
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.
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)
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.
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
Example:
inta=10;
intb=5;
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;
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
12
Example:
inta=10;
Output:
inta=10;
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
publicclassReadNumber {
publicstaticvoidmain(String[] args) {
Scannersc=newScanner([Link]);
[Link]("Enter a number:");
intnum=[Link]();
14
publicclassAddition {
publicstaticvoidmain(String[] args) {
Scannersc=newScanner([Link]);
intsum=a+b;
[Link]("Sum = "+sum);
}
}
Output:
Enter first number:
7
Enter second number:
52
Sum = 59
publicclassLargestNumber {
publicstaticvoidmain(String[] args) {
Scannersc=newScanner([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;
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;
17
Example Program 2 (Scenario – Login System)
public static void main(String[] args) {
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) {
18
Grade B
Example Program 2 (Scenario – Employee Bonus)
public static void main(String[] args) {
int experience = 6;
Example Program 1
public static void main(String[] args) {
19
}
}
}
Output:
Entry Allowed
Example Program 2 (Scenario – College Admission)
public static void main(String[] args) {
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
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) {
if(roll == 4)
continue;
25
Attendance for Roll No: 5
Attendance for Roll No: 6
Attendance for Roll No: 7
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
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
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
30
{
if(a[i]%2==0)
[Link](a[i]+" ");
}
}
}
Output:
[Link] elements
4
enter elements
10 3 9 44
Even numbers are:10 44
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 ;
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 str1=“Hello”;
String str2=“Hello”;
String s3=“abcdef”;
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
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
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
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
39
Scanner sc = new Scanner([Link]);
[Link]("Enter a number:");
int number = [Link]();
[Link](number);
}
}
Output:
Enter a number:
52
Number entered: 52
Example Program 2
import [Link];
[Link]("Enter number:");
int num = [Link]();
40
void deposit(int balance, int amount){
int total = balance + amount;
[Link]("Updated Balance = " + total);
}
[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];
41
int x = [Link]();
int y = [Link]();
Example Program 2
import [Link];
int a = [Link]();
int b = [Link]();
42
int total = price * quantity;
[Link]("Total Bill = " + total);
}
[Link]("Enter price:");
int price = [Link]();
[Link]("Enter quantity:");
int quantity = [Link]();
Example Program 1
import [Link];
int a = [Link]();
int b = [Link]();
43
ReturnExample1 obj = new ReturnExample1();
5
Cube = 125
Scenario-Based Program
Scenario-A salary system calculates yearly salary.
import [Link];
44
public static void main(String[] args){
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 {
[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];
46
int calculate(int a,intb,int c){
return a*b*c;
}
int a = [Link]();
int b = [Link]();
int c = [Link]();
class Student{
int id;
String name;
void display(){
[Link](id+" "+name);
}
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);
}
[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);
}
[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;
49
void show(){
[Link](x);
}
public static void main(String[] args){
[Link](10);
[Link]();
}
}
Output:
10
Example Program 2
class Test{
int a;
void display(){
[Link](a);
}
[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 display(){
[Link](id+" "+name);
}
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);
}
}
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);
}
}
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]();
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 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;
}
}
[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
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
}
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
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
75
[Link]("Processing payment");
}
}
class CreditCard extends Payment
{
void pay()
{
[Link]("Payment using Credit Card");
}
}
Output:
Payment using Credit Card
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");
}
}
80
GraphicObject g;
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
81
classSplender extends Bike
{
void run() {
[Link]("running 60KMPH");
}
}
}
}
public class AbstractDemoOne {
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 –
}
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
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");
}
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");
}
}
}
}
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
87
voiddrawShape();
static void fillColour()
{
[Link]("filled with blue colour");
}
}
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
interface PI2
{
default void show()
{
[Link]("Default PI2");
}
}
89
{
[Link]();
[Link]();
}
}
class Main
{
public static void main(String args[])
{
TestClass d = new TestClass();
[Link]();
}
}
Output:
Default PI1
Default PI2
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;
92
[Link](arr[5]);
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Array index error");
}
finally
{
[Link]("Execution completed");
}
}
}
Output
Array index error
Execution completed
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;
94
File Reading Diagram
Explanation:
Text File
|
FileReader
|
BufferedReader
|
Program
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;
[Link]();
}
}
Example File Content
Suppose your [Link] file contains:
Hello Java
File Handling Example
BufferedReader Program
Output:
Hello Java
File Handling Example
BufferedReader Program
class FileWriteExample
{
public static void main(String[] args) throws Exception
{
96
FileWriter fw = new FileWriter("[Link]");
[Link]();
class StudentFile
{
public static void main(String[] args) throws Exception
{
FileWriter fw = new FileWriter("[Link]");
[Link]();
String 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
[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]();
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
100
}
class Main {
public static void main(String args[]) {
ChildTh c1 = new ChildTh();
ChildTh c2 = new ChildTh();
[Link]("First Thread");
[Link]("Second Thread");
[Link]();
[Link]();
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.
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);
}
}
}
[Link]("First Thread");
[Link]("2nd Thread");
[Link]();
[Link]();
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
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);
}
}
}
[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.");
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
try {
[Link](3000);
} catch (InterruptedException e) {
[Link]("exception is " + e);
}
[Link](name);
}
}
106
}
classSynchronizedDemo {
public static void main(String[] args) {
[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
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:
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
Example Classes
• ArrayList
• LinkedList
• Vector
ArrayList Diagram
import [Link];
[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
import [Link];
[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]
110
import [Link];
[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.
Characteristics
• No duplicates
• Unordered
• Faster searching
Example Classes
111
• HashSet
• LinkedHashSet
• TreeSet
HashSet Diagram
import [Link];
Output
112
public class HashSetExample2
{
public static void main(String[] args)
{
HashSet<String> cities = new HashSet<>();
[Link]("Hyderabad");
[Link]("Delhi");
[Link]("Mumbai");
import [Link];
[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
Characteristics
Example Classes
• PriorityQueue
• LinkedList
Queue Diagram
import [Link];
[Link](50);
[Link](10);
[Link](30);
114
[Link]("Queue Elements: " + pq);
}
}
Output:
Queue Elements: [10, 50, 30]
[Link]("A");
[Link]("B");
[Link]("C");
[Link](queue);
}
}
Output:
Removed: A
[B, C]
import [Link];
[Link]("Customer1");
115
[Link]("Customer2");
[Link]("Customer3");
5. MAP (HashMap)
Definition
Characteristics
• Unique keys
• Values can duplicate
• Fast lookup
HashMap Diagram
import [Link];
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++}
import [Link];
[Link](101,"Rahul");
[Link](102,"Anjali");
[Link](103,"Kiran");
for(Integer id : [Link]())
{
[Link](id + " " + [Link](id));
}
}
}
Output:
101 Rahul
102 Anjali
103 Kiran
117
import [Link];
[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
.
import [Link];
[Link](3,"Java");
[Link](1,"Python");
[Link](2,"C++");
[Link](map);
}
}
Output:
{1=Python, 2=C++, 3=Java}
import [Link];
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
import [Link];
[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