Java Notes
Java Notes
Automation Testing
Automation Testing is the process of testing the software using an automation tool to find the
defect. In this process executing the script and generating the reports automatically.
Required one editor tool to write the java code - Eclipse editor tool. Automation tool - Selenium
web driver
What is Java -:
Java is a classed based object oriented programming language. For building the web based and
desktop based application.
Features of java
1. Simple
2. Object oriented programming lan.
3. Platform independent. - Windows ,Linux , MacOs. 4. Secured.
5. Robust - ( Strong)
6. Freely available in the market.
Project structure :
1 Package —> Multiple Classes —> (Sample1, Sample 2) 1 Class —> Multiple Methods —> Main
method
The main() method is the starting pint for JVM to start execution of the java program.
Without main method JVM will not execute the program. Syntax -
The curly braces { } marks the beginning and ending of the block of the code.
20 -Sep-2024
1. Variables
2. Data Type
3. Methods
4. Loops
5. Control statements
6. Keywords & identifiers
7. Types of variables
8. Constructor
1. Variables :
Program 1.
Ranjeet Kendre
Program 2
Program 3
Ranjeet Kendre
2.Data Types
1. Data type are used to represent data or information which we are going to store in
variables.0r Data types specify the different sizes and values that can be stored in the variable.
Program 1
Ranjeet Kendre
Program 2
Program 3
Ranjeet Kendre
Program 4
Date - 25 Sep 2024
3. We can write a method once and use it many times. We do not require to write a
code again and again. It also provides the easy modification and readability of code
the
5. A method must be declared within a class. It is defined with the name of the
method, followed by parentheses ().
Types of method/functions
1.Predefine Method
Program 1
Program 2
Ranjeet Kendre
Program 4
Ranjeet Kendre
Program 5
Program 6
Ranjeet Kendre
Program 7
Date - 27/09/2024
2. Non static regular method
Program 8
Program 9
Ranjeet Kendre
Program 10
Program 11
Ranjeet Kendre
Program 12
Ranjeet Kendre
Date - 30/09/2024
These return types required a return statement at the end of the method. A return keyword is used
for returning the resulted value.
The void return type doesn't require any return statement. If we try to return a value from a void
method, the compiler shows an error.
• The return type of the method and type of data returned at the end of the method should be
of the same type. For example, if a method is declared with the float return type, the value
returned should be of float type only.
• The variable that stores the returned value after the method is called should be a similar data
type otherwise, the data might get lost.
• If a method is declared with parameters, the sequence of the parameter must be the same
while declaration and method call.
Java Operator
Date - 1/10/2026
Control/conditional statements
Java compiler executes the code from top to bottom. The statements in the code are
executed according to the order in which they appear. However, Java provides
statements that can be used to control the flow of Java code. Such statements are
called control flow statements.
Program 1
Ranjeet Kendre
Program 2
2. If-else statement
The If-else statement is an extension to the if-statement, which uses another block of code,
i.e., else block. The else block is executed if the condition of the if-block is evaluated as
false.
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
Ranjeet Kendre
Program 1
Program 2
Ranjeet Kendre
Program 3
Program 4
Ranjeet Kendre
Date - 3/10/2024
3.if else-if statement
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other
words, we can say that it is the chain of if-else statements that create a decision tree where the
program may enter in the block of code where the condition is true. We can also define an else
statement at the end of the chain.
Syntax :
if(condition 1) {
statement 1; executes when condition 1 is true
}
else if(condition 2) {
statement 2; /executes when condition 2 is false
}
else if(condition 3) {
statement 3; /executes when condition 2 is false
}
else {
statement 2; //executes when all the conditions are false
}
Program 1
Program 2
Ranjeet Kendre
Program 3
Program 4
Ranjeet Kendre
Program 5
Ranjeet Kendre
Nested if statement
The nested if statement represents the if block within another if block. Here, the inner if block
condition executes only when outer if block condition is true.
Syntax
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
Program 1
Ranjeet Kendre
Program 2
Date - 7/10/2024
Program 4.
Ranjeet Kendre
Java Loops
The Java loops is used to iterate a part of the program several times
For Loop :
A simple for loop we can initialize the variable check condition and increment/decrement
value. It consists of
four parts:
1. Initialization: It is the initial condition which is executed once when the loop starts.
Here, we can initialize the variable, or we can use an already initialized variable.
2. Condition: It is the second condition which is executed each time to test the condition
of the loop. It continues execution until the condition is false. It must return boolean
value either true or false.
4. Statement: The statement of the loop is executed each time until the second condition
is false.
Foo Loop
Syntax
for(initialization; condition; increment/decrement)
{
//statement or code to be executed
}
Ranjeet Kendre
Program 1
Ranjeet Kendre
Program 2
Ranjeet Kendre
Program 3.
Date - 8/10/2024
Program 4
Ranjeet Kendre
Program 5
Program 6
Ranjeet Kendre
Program 7
Program 8
Ranjeet Kendre
Program 9
Program 10
Ranjeet Kendre
Date. - 11/10/2024
Types of variables
1. Local variables
1. Non static local variable.
2. Global variable
1. Static/Class global variable
2. Non- static global variable/instance variables
Local Variable
1.A variable declared inside the body of the method/function is called as local
variable
2. Local variable are declared in method/function and constructor.
3. Access modi er cannot used for local variable
4. Local varable are visible only within the declared method /function.
Global variable
Program 1
fi
Program 2
Program 3
Program 4
Identi ers & keywords
Identifiers in programming are names used to identify variables, functions, classes, or other entities
in code.
Rules and conventions for identifiers in most programming languages:
1. Allowed Characters:
• Identifiers can contain letters (A-Z, a-z), digits (0-9), and underscores (_).
• They cannot start with a digit.
◦ Example:
▪ Valid: myVar, _myVar, var123
▪ Invalid: 123var
2. Case Sensitivity:
• Many programming languages are case-sensitive, meaning myVar and MyVar would be considered
different identifiers.
◦ Example:
▪ Valid: myVar and MyVar (both are distinct)
3. Reserved Keywords:
• Keywords or reserved words of the language (such as if, else, while, class, etc.) cannot be used as
identifiers.
◦ Example:
▪ Invalid: int, class, return
4. No Spaces:
• Identifiers cannot contain spaces.
◦ Example:
▪ Invalid: my var
▪ Valid: my_var, myVar
6. Length:
• Identifiers can be of any length in most modern programming languages,
7. Special Characters:
• Besides the underscore (_), special characters like !, @, #, $, %, etc., are usually not allowed.
◦ Example:
▪ Invalid: my@var, var#name
fi
8. Naming Conventions (Best Practices):
• Camel Case: Commonly used in JavaScript, Java, Python etc., where the first word is lowercase, and
subsequent words start with an uppercase letter.
◦ Example: myVariableName
• Snake Case: Words are separated by underscores, used in languages like Python.
◦ Example: my_variable_name
Valid identifiers:
Following are some examples of valid identifiers in Java:
◦ TestVariable
◦ testvariable
◦a
◦ Test_Variable
◦ _testvariable
◦ $testvariable
◦ sum_of_array
◦ TESTVARIABLE
◦ jtp123
Invalid identifiers:
Below are some examples of invalid identifiers:
◦ Test Variable ( We can not include a space in an identifier)
◦ 123jTest ( The identifier should not begin with numbers)
◦ java+Test ( The plus (+) symbol cannot be used)
◦ A-javatest ( Hyphen symbol is not allowed)
◦ java_&_Test ( ampersand symbol is not allowed)
◦ Java'test (we can not use an apostrophe symbol in an identifier)
Java reserved keywords are predefined words, which are reserved for any functionality or
meaning. We can not use these keywords as our identifier names, such as class name or
method name. These keywords are used by the syntax of Java for some functionality. If we
use a reserved word as our variable name, it will throw an error.
In Java, every reserved word has a unique meaning and functionality.
Consider the below syntax:
Ranjeet kendre
Array
• An array is a data structure that stores multiple values of the same type in a contiguous
block of memory.
• Arrays are fixed in size, meaning you must define the length when you create them, and this
size cannot be changed.
2. Declaring an Array
int[] numbers;
int numbers[];
3.Initializing an Array
Arrays can be initialized at the time of declaration or after instantiation.
Example of initialization at declaration
numbers[0] = 1;
numbers[1] = 2;
5.Array Length
System.out.println(numbers.length); // Prints the length of the array
6.Types of Arrays
1.Single-Dimensional Array: A linear array with elements arranged in a single row.
int[] singleArray = new int[5];
Sorting an Array
Arrays.sort(numbers);
Fixed Size: Arrays have a fixed size which is helpful when the amount of data is known in advance.
This makes them easy to manage and reduces memory wastage.
Efficient Access: Array elements are stored contiguously in memory, allowing fast access using
indices. This provides a time complexity of
O(1) for accessing elements by index.
Memory Efficiency: Arrays are memory-efficient as they allocate memory in a contiguous block.
This generally uses less overhead than some other data structures like linked lists.
Ranjeet kendre
Disadvantages of Arrays in Java
Fixed Size Limitation: Once defined, the size of an array cannot be changed, which means you
cannot dynamically add elements. If the array is full, a new, larger array must be created and the
elements copied over, which is inefficient.
Wasted Memory: If the allocated size of an array is larger than the actual data stored, it results in
unused memory, which is inefficient.
Only Homogeneous Data: Arrays can only store elements of the same data type
Program 1
package Arrays;
public class Array1 {
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
arr[5] = 60;
arr[6] = 70;
arr[7] = 80;
arr[8] = 90;
arr[9] = 100;
// arr[10] =200; // System.out.println(len);
// second way
System.out.println(len); //10
System.out.println(arr[4]);
System.out.println(A2.length);
// NegativeArraySizeException
System.out.println(arr[i]);
}
}
}
Ranjeet kendre
Program 2
package Arrays;
import java.util.Arrays;
B1[0] =true;
//B1[1] = 10;
B1[4] =false;
System.out.println(B1[0]);
System.out.println(B1[2]);
System.out.println(B1[4]);
ch[0] = 'A';
ch[1] ='Z';
ch[2] ='F';
ch[3] ='S';
// ch[4] ='e';
System.out.println("Before sort");
for(int i=0 ;i<=ch.length-1;i++) {
System.out.print(ch[i]+" ");
}
System.out.println();
// for(int i=ch.length-1 ;i>=0;i--) {
// System.out.print(ch[i]+" ");
// }
Arrays.sort(ch);
for(int i=0 ;i<=ch.length-1;i++) {
System.out.print(ch[i]+" ");
}
}
Ranjeet kendre
Program 3
package Arrays;
System.out.println(i1);
//System.out.println(i[4]);
System.out.println(i[4]);
Program 4
package Arrays;
import java.util.HashSet;
str[0] = "Ketan";
str[1] = "Java";
str[2] ="Automation";
str[3] ="Manual";
// str[3]=33;
System.out.println(str[2]);
Ranjeet kendre
System.out.println(str[0]);
System.out.println();
System.out.println(str[Test]);
Program 5
package Arrays;
obj[0] = 1; // int
obj[1] = "Java";
obj[2] = true;
obj[3] = '3';
obj[4] = 12.4f;
obj[5] = 44.55d;
System.out.println(obj[4]);
System.out.println(obj[i]);
}
Program 6
package Arrays;
int n1 = 10;
int n2 = 20;
int n3;
// n3 =10;
// System.out.println(n2);
// array declaration
// dataType varibalename [] = new dataType[Numbers];
int arr[] = new int[10];
// syntax
Ranjeet kendre
// Arrayname[]indexnuber = value;
//
/// array initialization
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
arr[5] = 60;
arr[6] = 70;
arr[7] = 80;
arr[8] = 90;
arr[9] = 100;
//arr[10] =300;
// Usages
System.out.println(arr[8]);
// System.out.println(arr[10]); //ArrayIndexOutOfBoundsException
System.out.println(arr[1]);
System.out.println(size);
Program 7
package Arrays;
str[0][0] = "A1";
str[0][1] = "A2";
str[0][2] = "A3";
str[0][3] = "A4";
str[0][4] = "A5";
str[1][0] ="B1";
str[1][1] ="B2";
str[1][2] ="B3";
str[1][3] ="B4";
str[1][4] ="B5";
str[2][0] ="C1";
str[2][1] ="C2";
Ranjeet kendre
str[2][2] ="C3";
str[2][3] ="C4";
str[2][4] ="C5";
str[3][0] ="D1";
str[3][1] ="D2";
str[3][2] ="D3";
str[3][3] ="D4";
str[3][4] ="D5";
System.out.println(str[0][2]);
System.out.println(str[3][3]);
System.out.print(str[Row][Col]+" ");
}
System.out.println();
}
Program 8
package Arrays;
System.out.println(arr.length);
System.out.println(arr[2].length);
System.out.println(arr1.length); //4
System.out.println(arr1[2].length); //3
//for(int Row=0)
System.out.println(arr1[0][2]);
// System.out.println(arr1[3][3]);
System.out.print(arr1[Row][Col]+" ");
}
System.out.println();
}
Program 9
package Arrays;
int sum = 0;
Program 10
package Arrays;
//size of arrays is 7
}
Ranjeet kendre
Program 11
package Arrays;
RevWord = RevWord+word.charAt(i);
}
}
System.out.println(Rev);
}
Ranjeet Kendre
Java String
Example -As Java uses the concept of String literal. Suppose there are 5 reference
variables, all refer to one object "Sachin". If one reference variable changes the value of
the object, it will be affected by all the reference variables. That is why String objects
are immutable in Java.
2. Security
If we don’t make the String immutable, it will pose a serious security threat to the
application. For example, database usernames, passwords are passed as strings to
receive database connections. The socket programming host and port descriptions are
also passed as strings. The String is immutable, so its value cannot be changed. If the
String doesn’t remain immutable, any hacker can cause a security issue in the
application by changing the reference value.
The reason behind the String class being final is because no one can override the
methods of the String class. So that it can provide the same features to the new String
objects as well as to the old ones.
1. The String class equals() method compares the original content of the string. It
compares values of string for equality.
Ranjeet Kendre
2. == operator always compare reference comparison or address comparison reference
comparison means if both reference point into the same object then it will give output
true
1. String Basics
2. Creating Strings
3. String Pool
• When a String literal is created, Java checks if the value already exists in the String
pool.
• If it exists, Java reuses the existing instance/object; otherwise, it creates a new instance/
object in the pool.
• new String("Hello") creates a new object in the heap memory, bypassing the String
pool.
3. Comparing Strings
Program 1
package String;
// 1.String Literal
// 2. By using new keyword
// String Literal
}
Ranjeet Kendre
Program 2
package String;
System.out.println(S1==S4); //True
System.out.println(S1.equals(S4)); //True
}
Ranjeet Kendre
Program 3
package String;
System.out.println(S1==S3);
System.out.println(S1.equals(S3));
System.out.println(S4==S5); //True
System.out.println(S4.equals(S5)); //True
System.out.println(S4==S6); //False
System.out.println(S4.equals(S6)); //False
}
Program 4
package String;
String S1 = "Java";
String S2 = "Python";
String S3 = "JavaScript";
Ranjeet Kendre
String S4 = new String("Java");
String S5 = new String("Ruby");
//SCP 1 1 1 1
//Heap 1 1
//6
Program 5
package String;
String S1 = "Java";
String S2 = "Python";
String S3 = "Java";
System.out.println(S1==S3); //True
System.out.println(S1.equals(S3)); //True
System.out.println(S4==S6); //False
System.out.println(S4.equals(S6)); //True
/**
* == Always compare reference comparison or address com.
* ref comp means if both ref point into the same object hen it will give output as true
.equals method - content comparison means the two given string based on the content of
the given string
if any char is not matched it return false and if all char chae are matched it returns true
*/
}
Ranjeet Kendre
}
Program 6
package String;
//String utable
S1 = "RRR";
System.out.println(S1);
S4 = "Solapur";
System.out.println(S1);
System.out.println(S4);
Str.concat("World");
System.out.println(Str); //HelloWorld
/*Once we created an object after that jav a does not allow to perform any changes
but it your trying to perform any changes with those changes new object will created */
}
}
Program 7
package String;
System.out.println(Rev);
Program 8
package String;
// System.out.println(S1.charAt(19)); //StringIndexOutOfBoundsException:
System.out.println(S1.charAt(8));
System.out.println(S1.charAt(4));
// .equals - content comparison means the two given string based on the content
// of the given string
String S2 = "Test";
String S3 = "Java";
String S4 = "Test";
String S5 = new String("Test");
System.out.println(S2.equals(S3)); // False
System.out.println(S2.equals(S4)); // True
System.out.println(S2.equals(S5)); // True
Ranjeet Kendre
// IsEmpty
String S6 = "Java";
System.out.println(S6.length()); //5
String S7 = "";
// System.out.println(S7.charAt(0));
System.out.println(S6.isEmpty());
System.out.println(S7.isEmpty());
// Replace
String S9 = "Java is simple language and Java is programming lan";
System.out.println(S9);
System.out.println(S9.replace('a', 'b'));
System.out.println(S9.replace('J', 'F'));
System.out.println("****************************");
System.out.println(S9.replaceAll("Java", "Js"));
System.out.println(S9);
// Split
System.out.println(arr[i]);
}
System.out.println(arr1[i]);
}
System.out.println("****");
sum += num;
// sum = sum+num
}
System.out.println(sum);
Program 9
package String;
// equalignorecase
String S1 = "JAVA";
String S2 = "java";
System.out.println(S1.equals(S2)); // False
System.out.println(S1.equalsIgnoreCase(S2)); // true
// SubString
System.out.println(S3.length());
System.out.println("**********");
System.out.println(S3.substring(4)); //
System.out.println(S3.substring(4, 8));
Ranjeet Kendre
System.out.println(S3.substring(9, 16));
// IndexOF
System.out.println(S4.length());
// Lowercase
String S5 = "JAVA";
System.out.println(S5.toLowerCase());
// ToUppercase
String S6 = "java";
System.out.println(S6.toUpperCase());
// Trim
System.out.println(S7);
System.out.println(S7.trim());
String S8 = "12/12/2024";
System.out.println(num);
}
String a = "Hello";
String b = "Java";
int x = 10;
Ranjeet Kendre
int y = 20;
System.out.println(x + y); // 30
System.out.println(a + b); // HelloJava
System.out.println(a + b + x + y); // HelloJava1020
System.out.println(x + y + a + b); // 30HelloJava
System.out.println(a + b + (x + y)); // HelloJava30
}
Ranjeet Kendre
Commonly used Java String methods with explanations and examples
1. length()
Returns the number of characters in the string.
String text = "Hello, World!";
int length = text.length(); // 13
2. charAt(int index)
Returns the character at the speci ed index.
String text = "Hello";
char ch = text.charAt(1); // ‘e'
5. contains(CharSequence s)
Checks if the string contains the speci ed sequence of characters.
String text = "Hello, World!";
boolean contains = text.contains("World"); // true
8. trim()
Removes leading and trailing whitespace from the string
String text = " Hello, World! ";
String trimmed = text.trim(); // "Hello, World!”
fi
fi
fi
fi
fi
fi
ffi
fi
fi
ffi
fi
Ranjeet Kendre
9. replace(char oldChar, char newChar) and replace(CharSequence target,
CharSequence replacement)
Replaces occurrences of the speci ed character or substring with a new character or
substring.
String text = "Hello, World!";
String replaced = text.replace("World", "Java"); // "Hello, Java!"
String replacedChar = text.replace('o', 'a'); // "Hella, Warld!"
13. valueOf()
Converts various data types to a string. This is a static method.
int number = 123;
String text = String.valueOf(number); // “123"
14. isEmpty()
Checks if the string is empty (length() == 0).
String text = "";
boolean isEmpty = text.isEmpty(); // true
fi
fi
fi
ff
Ranjeet Kendre
Type Casting
Type casting in Java refers to converting one data type to another. Java provides two types of
casting:
Types of casting
Implicit casting happens automatically when you assign a smaller data type value to a larger data
type. This is known as widening, as there is no risk of losing data.
Explicit casting is required when you want to assign a larger data type to a smaller data type. This is
known as narrowing, and it requires the programmer to manually specify the conversion.
Program 1
Ranjeet Kendre
Program 2
Program 3
Ranjeet Kendre
Program 4
Program 5
1. This Keyword
The this keyword refers to the current instance of a class. It’s often used to distinguish between
class fields and parameters with the same name or to invoke other constructors within the same
class.
2. Super Keyword
Program 1
Program 2
Program 3
Program 4
Program 5
Logical Programs
Program 2
Ranjeet Kendre
Final nally and nalize di erence
Program 1
fi
fi
ff
Ranjeet Kendre
Program 2
Program 3
Program 4
Ranjeet Kendre
Program 5
Ranjeet Kendre
Exception Handling
Example :
Statement 1
Statement 2
Statement 3 //Exception occurs
Statement 4
Statement 5
Suppose there are 5 statements in a Java program and an exception occurs at statement
3;
the rest of the code will not be executed, i.e., statements 3 to 5 will not be executed.
However,
when we perform exception handling, the rest of the statements will be executed That
why we use exception handling in Java.
2 Types of exception
2. Un-checked exceptions
1. ArithmeticException
2. NullPointerException
3. NumberformatException
4. ArrayIndexOutofboundException
5. Classcastexception
6. Stringoutofboundexception
Keyword Description
try -- The "try" keyword is used to specify a block where we should place an
exception code.
It means we can't use try block alone. The try block must be followed by either
catch or nally.
fi
fl
fl
Ranjeet Kendre
catch -- The "catch" block is used to handle the exception. It must be preceded by try
block which means
we can't use catch block alone. It can be followed by nally block later.
nally -- The " nally" block is used to execute the necessary code of the program.
It is executed whether an exception is handled or not.
throw -- The "throw" keyword is used to throw an exception.
throws -- The "throws" keyword is used to declare exceptions.
It speci es that there may occur an exception in the method.
It doesn't throw an exception. It is always used with method signature.
Di erence b/w
Throw- Java throw keyword is used throw an exception explicitly in the code, inside the
function or the block of code.
Throws - Java throws keyword is used in the method signature to declare an exception
which might be thrown by the function
while the execution of the code.
Throw - We are allowed to throw only one exception at a time i.e. we cannot throw
multiple exceptions.
Throws -We can declare multiple exceptions using throws keyword that can be thrown by
the method. For example, main()
throws IOException, SQLException.
Program 1
package ExceptionHandling;
import java.io.FileInputStream;
System.out.println("PC");
System.out.println("Hello");
System.out.println("Hi");
System.out.println(10/0);
System.out.println("Program completed");
//Types of exception
//Checked exception
//1. FileNotfoundexception
//InteruptedException
//IOException
fi
ff
fi
fi
fi
Ranjeet Kendre
//Unchecked exception
//1.Arithmetic exception
//2.ArrayIndexOutoboundexception
//3.Negativesizearrayexception
//4.ClassCastexception
//5.NullPointerexceprion
//6.StringIndexOutoboundexception
//7.NumberformatException
}
Program 2
package ExceptionHandling;
import java.util.Scanner;
System.out.println("Program is started");
//Example 2
System.out.println("Program is completed");
//Example 3
String S1 = "123456";
String S2 = "Java";
int num =Integer.parseInt(S1);
//int num1 =Integer.parseInt(S2); //.NumberFormatException:
System.out.println(num);
// System.out.println(num1);
System.out.println("Program is completed");
//Example 4
String S4= " ";
String S5= null;
System.out.println(S4.length());
System.out.println(S5.length()); //java.lang.NullPointerException
}
Ranjeet Kendre
Program 3
package ExceptionHandling;
import java.util.Scanner;
/**
* try{
*
* statement
*
* } catch(Exception name){
*
* statement ; }
*
*/
System.out.println("Program is started");
System.out.println("Enter a number");
try {
System.out.println(100 / num);
}
catch (ArithmeticException e) {
System.out.println("Invalid data");
System.out.println("Hello");
}
String S1 = "123456";
String S2 = "Java";
try {
} catch (NumberFormatException e) {
System.out.println("Hello");
}
System.out.println("Program is completed”);
Program 4
package ExceptionHandling;
//MultipleCatchBlocks
System.out.println("Program is started");
String S1 = null;
try {
System.out.println(S1.length()); //Null
}catch (NullPointerException e) {
Ranjeet Kendre
System.out.println(e.getMessage());
e.getMessage();
System.out.println("Handle Exception 2");
}
catch (ArrayIndexOutOfBoundsException e) {
e.getMessage();
System.out.println("Handle Exception 3");
}
catch (Exception e) {
finally {
System.out.println("This is and finally block");
}
System.out.println("Program completd");
Program 5
package ExceptionHandling;
try {
} finally {
}
/**
* try{
*
* statement
*
* } catch(Exception name){
*
* statement ; } finally{
*
* }
*
* Case 1 - Exception occurred ,cath blocked handle --finally block
will
* executed Case 2 - Exception occurred ,cath blocked not handle --
finally block
* will executed Case 3 - Exception not occurred ,cath blocked
ignored --finally
* block will executed
*/
System.out.println("Program is started");
String S1 = null;
try {
System.out.println(S1.length()); // Null
} catch (ArrayIndexOutOfBoundsException e) {
Ranjeet Kendre
finally {
System.out.println("You entered into finally block");
}
}
Program 6
package ExceptionHandling;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
// */
//
//
System.out.println("Program started");
//
// Thread.sleep(1000);
//
// System.out.println("Program completed");
//
try {
FileInputStream Fi = new FileInputStream("Java.Txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// System.out.println("Program completed");
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.getMessage();
e.printStackTrace();
}
}
Ranjeet Kendre
Program 7
package ExceptionHandling;
try {
ExceptionHandling6.checkAge(15);
System.out.println("PC");
System.out.println("PS");
} else {
System.out.println("Eligible to vote");
}
}
}
Program 8
package ExceptionHandling;
try {
return 11;
}
finally {
System.out.println("calculation compeleted");
// Staackoverflowiserror
// outofmemoryError
}
Program 9
package ExceptionHandling;
public class Stackoverlowerror {
Stackoverlowerror.number(); //java.lang.StackOverflowError
}
public static void number() {
if(number<=100000) {
System.out.println("Java Programming");
number++;
number();
}}}
Ranjeet Kendre
OOPS — OOPS Stands for object-oriented programming system/structure.
1. Inheritance
2. Polymorphism
3. Abstraction
4. Encapsulation
1. Inheritance :
One class acquires property of another class with the help of extends keywords is known as
inheritance.
The most important use of inheritance in java is code reusability. The code that is present in parent
class can be directly used by the child class
Types of inheritance
2. Multilevel inheritance
Multilevel Inheritance takes place between 3 or more than 3 classes.
In Multilevel Inheritance 1 sub class acquires properties of another super class & that class acquires
properties of another super class & phenomenon continuous.
3. Hierarchical Inheritance:
Multiple sub classes can acquire properties of 1 super class is known as hierarchical Inheritance.
4. Multiple Inheritance:
1 subclass acquiring properties of 2 super classes at the same time is known as Multiple Inheritance.
Java doesn't support Multiple Inheritance using class because of diamond ambiguity problem.
By using interface we can achieve Multiple Inheritance.
Note: object class is the super most class in all java
5.Hybrid inheritance :
The hybrid inheritance is the combination of two or more than two types of inheritance.
Example - Consider a scenario where A, B, and C are three classes. The C class inherits A and B
classes. If A and B classes have the same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.
Ranjeet Kendre
Since compile-time errors are better than runtime errors, Java renders compile- time error if you inherit
2 classes. So whether you have same method or different, there will be compile time error.
Program 1
package Inheritance_SingleLevel;
System.out.println("Car -- Swift");
}
Program 2
package Inheritance_SingleLevel;
System.out.println("Bike -- FZ");
}
S1.Bike();
S1.Home();
S1.Car();
S1.Money();
}
}
Ranjeet Kendre
Program 3
package Inheritance_SingleLevel;
System.out.println("Bike -- FZ");
2. Multilevel inheritance
Program 1.
package Inheritance_Multilevel;
System.out.println("Text Message");
}
Ranjeet Kendre
}
Program 2
package Inheritance_Multilevel;
import Inheritance_Hie.father;
System.out.println("Audio Calling");
}
}
Program 3
package Inheritance_Multilevel;
//Text msg
//Audio calling
System.out.println("Video Calling");
}
}
Program 4
package Inheritance_Multilevel;
//Text msg
//AC
//VC
System.out.println("Payment");
}
}
Ranjeet Kendre
Program 5
package Inheritance_Multilevel;
V1.TextMsg();
System.out.println();
V2.AudioCalling();
System.out.println();
WhatsAppV3 V3 = new WhatsAppV3();
V3.VideoCalling();
V3.AudioCalling();;
V3.TextMsg();
System.out.println();
WhatsAppV4 V4 = new WhatsAppV4();
V4.Payement();
V4.TextMsg();
V4.AudioCalling();
V4.VideoCalling();
}
Ranjeet Kendre
3. Hierarchical Inheritance:
Program 1
package Inheritance_Hie;
System.out.println("Car -- Swift");
}
package Inheritance_Hie;
System.out.println("Bike");
}
}
Program 3
package Inheritance_Hie;
System.out.println("Mobile");
}
Program 4
package Inheritance_Hie;
Program 5
package Inheritance_Hie;
S1.Bike();
S1.Car();
S1.Home();
S1.Money();
Ranjeet Kendre
S1.Money1();
Son3.Money1();
System.out.println();
Son2 S2 = new Son2();
S2.Mobile();
S2.Car();
S2.Home();
S2.Money();
System.out.println();
Son3 S3 = new Son3();
S3.Laptop();
// S3.Mobile();
S3.Home();
S3.Car();
S3.Money();
}
4.Multiple inheritance - 1 subclass acquiring properties of 2 super classes at the same time is known
as Multiple Inheritance.
Java doesn't support Multiple Inheritance using class because of diamond ambiguity problem.
By using interface we can achieve Multiple Inheritance. Note: object class is the super most class in
java
Ranjeet Kendre
5.Hybrid inheritance
The hybrid inheritance is the combination of two or more than two types of inheritance.
Ranjeet Kendre
Access Modifiers or specifiers
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or
class. We can change the access level of fields, constructors, methods, and class by applying the access
modifier on it.
6. Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
7. Default: The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If you do not specify any access level, it will be the default.
8. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.
9. Public: The access level of a public modifier is everywhere. It can be accessed from within the
class, outside the class, within the package and outside the package.
Program 1
package AccessModifiers;
public Public1() {
}
public static void main(String[] args) {
P1.M1();
System.out.println(P1.number);
}
System.out.println("Public m1 method");
}
Program 2
package AccessModifiers;
P2.M1();
System.out.println(P2.number);
System.out.println(D1.Test);
D1.T1();
P4.P1();
System.out.println(P4.name);
}
Program 3
package AccessModifiers;
Program 4
package AccessModifiers;
System.out.println(D1.Test);
D1.T1();
}
void T1() {
System.out.println("Default method");
Program 5
package AccessDiff;
import AccessModifiers.Default1;
import AccessModifiers.Private1;
import AccessModifiers.Protected1;
import AccessModifiers.Public1;
//P1
//name
public static void main(String[] args) {
}
Ranjeet Kendre
2. Polymorphism
It is one of the oops principle where one object showing different Behaviour at different stage is
known as Polymorphism.
Types of Polymorphism
In Compile time Polymorphism method declaration and Definition are binded during the
compilation time based on argument or input parameter is known as compile time poly.
Method overloading
When the method name is same with different argument/input param with different data types
within the same class is called as method overloading.
It is also known as early binding.
We can overload the non static and static method. We can overload the main method
You can any number of method in a class but JVM class main () methods which receives string
array as arguments only.
In Run time Polymorphism method declaration and Definition are binded during the run time or
execution time based on input parameter or argument.
The process of compiler trying to resolve the method call from given overloaded method definitions
is called overload resolution.
Ranjeet Kendre
Ranjeet Kendre
Program 1
Program 2
Ranjeet Kendre
Program 3
Program 4
Ranjeet Kendre
Program 5
Program 6
Ranjeet Kendre
Program 7
Program 8
Ranjeet Kendre
Program 9
In Run time Polymorphism method declaration and Definition are binded during the run time or
execution time based on input parameter or argument.
The process of compiler trying to resolve the method call from given overloaded method definitions
is called overload resolution.
Ranjeet Kendre
Program 1
Program 2
Ranjeet Kendre
Program 3
Program 4
Ranjeet Kendre
Program 5
Program 6
Ranjeet Kendre
Program 7
Program 8
Ranjeet Kendre
Program 9
Program 10
Ranjeet Kendre
Program 11
Program 12
Ranjeet Kendre
Program 12
Program 13
Ranjeet Kendre
In Java, method overloading is a feature that allows a class to have more than one method with the
same name, but with different parameter lists (method signatures). It is a way to achieve compile-
time polymorphism, where the correct method to call is determined at compile time based on the
method's parameters.
In Java, method overriding allows a subclass to provide a specific implementation of a method that
is already defined by its parent class. The overriding method must have the same name, return type,
and parameters as the method in the parent class.
Method overriding is used to achieve runtime polymorphism.
Ranjeet Kendre
Rules for Method Overriding in Java:
1. Same Method Signature: The method in the child class must have the same name, return
type, and parameter list as the method in the parent class.
2. Access Modifier: The access modifier of the overriding method cannot be more restrictive
than the method in the parent class.
For example:
◦ If the parent method is protected, the overriding method can be protected or public,
but not private.
3. Return Type: The return type of the overriding method should either be the same as the
parent method or a subtype (Child type also allowed) (covariant return type).
4. Static Methods: Static methods cannot be overridden. If a static method is redefined in a
subclass, it's considered method hiding, not overriding.
5. Final Methods: A final method cannot be overridden. If a method in the parent class is
marked as final, the subclass cannot provide its own implementation.
6. Private Methods: Private methods cannot be overridden as they are not accessible outside
their class.
7. Constructor Cannot Be Overridden: Constructors cannot be overridden because they are
not inherited by subclasses.
3. Abstraction
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
Abstract Class
Another way, it shows only essential things to the user and hides the internal details, for example,
sending SMS where you type the text and send the message. You don't know the internal
processing about the message delivery.
A method which is declared as abstract and does not have imply is known as the abstract method.
• Concrete class:
A class which provides definations for all the incomplete methods which are present in abstract
class with the help of extends keywords is called concrete /child class.
Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of a car or applying brakes will stop the car, but he does not
know how on pressing the accelerator the speed is actually increasing, he does not know about
the inner mechanism of the car or the implementation of the accelerator, brakes, etc in the car.
There are two ways in which the objects can be initialised while inheriting the properties of the
parent
and child classes. They are:
Child c = new Child() : The use of this initialisation is to access all the members present in both
parent and child classes, as we are inheriting the properties.
Parent p = new Child() : This type of initialisation is used to access only the members present in
the parent class and the methods which are overridden in the child class. This is because the
parent class is upcasted/top casting to the child class.
Ranjeet Kendre
Program 1
Program 2
Ranjeet Kendre
Program 3
Program 4
Ranjeet Kendre
Program 5
Program 6
Ranjeet Kendre
Program 7
◦ You cannot create an instance of an abstract class directly. Instead, you must create
an instance of a concrete subclass that implements all the abstract methods.
3. Purpose of Abstract Classes:
◦ Abstract classes are used to provide a common template or shared code for
subclasses. They allow you to de ne some functionality in a base class and leave
other functionality to be implemented by subclasses.
fi
Ranjeet Kendre
Interface :
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body.
It is used to achieve abstraction and multiple+hybrid inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.
Features of interface.
1. Variables declared inside the interface are by default static and final.
2. Methods declared inside the interface are by default public and abstract.
3. Constructor concept is not applicable for interface.
4. Object of interface can not be created.
5. Interface supports multiple inheritance.
6. We can achieve 100% abstraction in interface till ( 1.7)
Implementation class :
A class which provides definitions for all the incomplete methods which are present in
interface with the help of implements keyword is called Implementation class
5. No Constructors:
◦ Interfaces do not have constructors because they cannot be instantiated directly.
Instead, classes that implement the interface instantiate it.
fi
Ranjeet Kendre
Program 1
Program 2
Ranjeet Kendre
Program 3
Program 4
Ranjeet Kendre
Program 5
Ranjeet Kendre
Or
Ranjeet Kendre
Ranjeet Kendre
What is Collection framework
The Collection framework represents a unified architecture for storing and manipulating a
group of objects.
Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.
Java Collection framework provides many interfaces Set, list ,Queue, Duque, Classes
(ArrayList, Vector, Linkedlist, PriorityQueue, Hashset, LinkedHashset, TreeSet)
Array ArrayList/Collection
Collection is the interface where you group objects into a single unit. Collections is a utility class
that has some set of operations you perform on Collection
List interface is the child interface of collection IF. if we want to represent a group of
individual obj as a single entity where duplicate are allowed and insertion order is preserved
then we can used list interface.
List in Java provides the facility to maintain the ordered collection. It contains the index-based
methods to insert, update, delete and search the elements. It can have the duplicate elements
also. We can also store the null elements in the list.
1. ArrayList:
◦ Backed by a dynamic array.
◦ Fast random access.
◦ Not synchronized.
2. LinkedList:
◦ Backed by a doubly linked list.
◦ Faster insertions and deletions compared to ArrayList.
◦ Not synchronized.
3. Vector:
◦ Legacy implementation backed by a dynamic array.
◦ Synchronized, hence thread-safe.
◦ Slower compared to ArrayList.
4. Stack:
◦ Extends Vector and represents a last-in-first-out (LIFO) stack of objects.
Ranjeet Kendre
ArrayList
The ArrayList class in Java is a part of the Java Collection Framework and implements the List
interface. It provides a resizable array, which means the size of the list can dynamically grow or
shrink as elements are added or removed.
1. Dynamic Array: Automatically resizes itself when elements are added or removed.
2. Maintains Insertion Order: Elements are stored in the order they are inserted.
3. Allows Duplicates: Duplicate elements are permitted.
4. Random Access: Provides fast access to elements using an index.
5. Null Elements: Supports storing null as an element.
6. Not Synchronized: Not thread-safe by default but can be synchronized using utility
methods.
Program 1
package List;
import java.util.ArrayList;
import java.util.Iterator;
//Array
arr[0] = 50;
arr[9] = 80;
// System.out.println(arr);
//System.out.println(arr.length);
//Array List
AL.add(20); //0
AL.add(50); //1
AL.add("Java"); //2
AL.add(true);
AL.add(49.4f);
Ranjeet Kendre
AL.add('R');
AL.add(null);
AL.add("Python");
AL.add(20);
AL.add(44.5);
AL.add(50); //10
System.out.println(AL);
//2.Size - return the number of element in this list
System.out.println(AL.size());
//3.Remove
System.out.println(AL.remove(2));
AL.add("Automation");
System.out.println(AL);
//
System.out.println(AL.get(9));
System.out.println(AL.contains(20)); //True
System.out.println(AL.contains(2000)); //false
System.out.println(AL.contains("Python"));
AL.set(3, 2000);
System.out.println(AL);
//7.IsEmpty
System.out.println(AL.isEmpty());
System.out.println(AL1.isEmpty());
System.out.println(AL.get(i));
}
//Iterator
System.out.println();
Ranjeet Kendre
Iterator it = AL.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
System.out.println();
while(obj.hasNext()) {
System.out.println(obj.next());
}
}
Program 2
package List;
import java.util.ArrayList;
import java.util.Collections;
AL1.add(400); //0
AL1.add("Java"); //1
AL2.add(33);
//AL2.add("Test");
for(Object It :AL1) {
System.out.println(It);
}
AL3.add("A");
AL3.add("C");
AL3.add("S");
AL3.add("Z");
AL3.add("R");
AL3.add("Q");
System.out.println(AL3);
System.out.println(AL3.size()); //
System.out.println();
//AddAll
ArrayList AL4 = new ArrayList();
AL4.addAll(AL3);
System.out.println(AL4);
Ranjeet Kendre
//Remove ALL
AL4.removeAll(AL3);
System.out.println(AL4); //
//Sort
Collections.sort(AL3);
System.out.println(AL3);
//Des sort
Collections.sort(AL3,Collections.reverseOrder());
System.out.println(AL3);
Program 3
package List;
import java.util.ArrayList;
import java.util.Arrays;
System.out.println(arr);
System.out.println(AL);
}
Ranjeet Kendre
2. LinkedList :
The LinkedList class in Java is part of the Java Collection Framework and implements the
List, Deque, and Queue interfaces. It represents a doubly-linked list and allows efficient
insertion and deletion operations compared to ArrayList.
Program 1
package List;
import java.util.Iterator;
import java.util.LinkedList;
LL2.add(44);
//Add
LL1.add(10); //0
LL1.add('B');
LL1.add("Java");
LL1.add(true);
LL1.add(null);
LL1.add("Automation");
LL1.add(44.5);
System.out.println(LL1);
//Size
int len = LL1.size();
System.out.println(len);
System.out.println(LL1.size());
//Remove
//System.out.println(LL1.remove(1));
System.out.println(LL1);
//get
System.out.println(LL1.get(3));
fi
Ranjeet Kendre
//add
LL1.add(3,"Test");
System.out.println(LL1);
LL1.addFirst("Selenium");
System.out.println(LL1);
//AddLAst
LL1.addLast("Java");
System.out.println(LL1);
System.out.println(LL2.isEmpty());
for(int i=0;i<LL1.size();i++) {
System.out.println(LL1.get(i));
}
System.out.println();
System.out.println();
Iterator str = LL1.iterator();
while(str.hasNext()) {
System.out.println(str.next());
}
Program 2
package List;
import java.util.Collections;
import java.util.LinkedList;
//Add element
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Grapes");
fruits.add("Orange");
System.out.println(fruits);
//access element
System.out.println(fruits.getFirst()); //
System.out.println(fruits.getLast());
Ranjeet Kendre
//Remove
fruits.removeFirst();
System.out.println(fruits);
fruits.removeLast();
System.out.println(fruits);
System.out.println(fruits.contains("Apple")); //
//Update element
fruits.set(0, "Mango");
System.out.println(fruits);
LL1.add("A");
LL1.add("BB");
LL1.add("R");
LL1.add("F");
LL1.add("E");
LL2.addAll(LL1);
System.out.println(LL2);
//Remvoe all
LL2.removeAll(LL1);
System.out.println(LL2);
Collections.sort(LL1);
System.out.println(LL1);
Collections.sort(LL1,Collections.reverseOrder());
System.out.println(LL1);
}
}
Ranjeet Kendre
3.Vector
The Vector class in Java is a part of the Java Collection Framework and is located in the java.util
package. It implements the List interface and is used to store elements in a dynamic array-like
structure that is synchronized, making it thread-safe.
Program 1
package List;
import java.util.Iterator;
import java.util.Vector;
//CC *3/2+1
//CC*2
V1.add('A');
V1.add('r');
V1.add('r');
V1.add('r');
V1.add('r');
V1.add('r');
V1.add('r');
V1.add('r');
V1.add('r');
V1.add('r');
System.out.println(test);
V1.add('f');
System.out.println(test1);
V1.add(1,55);
System.out.println(V1);
System.out.println();
Iterator it = V1.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
Program 2
package List;
import java.util.Vector;
colors.add("Red");
colors.add("Blue");
colors.add("Green");
colors.addElement("Java");
System.out.println(colors);
System.out.println(colors.get(0));
colors.set(1, "yellow");
System.out.println(colors);
}
}
Ranjeet Kendre
Ranjeet Kendre
2. Set Interface
The Set interface in Java's Collection Framework is a part of the java.util package. It represents a
collection that does not allow duplicate elements .It is one of the key interfaces in the Java
Collections Framework and extends the Collection interface.
1. No Duplicate Elements: A Set does not allow duplicates. If you try to add a duplicate
element, the operation will not affect the set.
2. Unordered Collection: Elements in a Set are not guaranteed to be in any specific order
(except in specific implementations like LinkedHashSet or TreeSet).
3. Implements Collection Interface: Since Set extends Collection, it inherits all the methods
of the Collection interface.
HashSet in Java
The HashSet class in Java is part of the java.util package and implements the Set interface. It is a
collection that uses a hash table to store elements and ensures that there are no duplicate elements
in the collection.
1. No Duplicates: A HashSet does not allow duplicate elements. If you try to add a duplicate,
it will simply ignore it.
2. Unordered: The order of elements in a HashSet is not maintained. It depends on the hash
value of the elements.
3. Allows Null: A HashSet can store one null element.
4. Not Synchronized: HashSet is not thread-safe.
LinkedHashSet in Java
The LinkedHashSet class is part of the Java Collections Framework and extends the HashSet class.
It implements the Set interface and maintains a linked list of the entries in the set. This allows
LinkedHashSet to maintain the insertion order of elements, unlike HashSet.
1. Maintains Insertion Order: Elements are stored in the order they were inserted.
2. No Duplicates: Like all Set implementations, LinkedHashSet does not allow duplicate
elements.
3. Allows Null: Can store a single null element.
4. Performance: Similar to HashSet but slightly slower
5. Not Synchronized: Not thread-safe.
Ranjeet Kendre
Program 1
package SetInterface;
import java.util.HashSet;
import java.util.Iterator;
HS.add("Java");
HS.add(444);
HS.add(true);
HS.add('D');
HS.add(null);
HS.add(null);
System.out.println(HS);
System.out.println(HS.add(444)); //false
System.out.println(HS.add("Java1")); //True
System.out.println(HS);
HS1.add("Apple");
HS1.add("Banana");
HS1.add("Cherry");
HS1.add("Apple");
System.out.println(HS1);
System.out.println(HS1.contains("Apple"));
//Remove an element
HS1.remove("Apple");
System.out.println(HS1);
Ranjeet Kendre
HashSet <Integer> HS2 = new HashSet<Integer>();
HS2.add(10);
HS2.add(20);
HS2.add(30);
HS2.add(40);
System.out.println(num);
}
//Using iterator
System.out.println();
Iterator obj = HS2.iterator();
while(obj.hasNext()) {
System.out.println(obj.next());
}
}
Program 2
package SetInterface;
import java.util.HashSet;
Cities.add("Pune");
Cities.add("Mumbai");
Cities.add("London");
Cities.add("Tokyo");
System.out.println(Cities);
System.out.println(cityarray);
Program 3
package SetInterface;
import java.util.HashSet;
HS1.add(1);
HS1.add(2);
HS1.add(3);
HS1.add(44);
HS1.add(33);
HS2.add(3);
HS2.add(44);
HS2.add(33);
//Union
HS1.addAll(HS2);
System.out.println(HS1); //
//Intersection
HS1.retainAll(HS2);
System.out.println(HS1);
Ranjeet Kendre
}
Program 4
package SetInterface;
import java.util.Iterator;
import java.util.LinkedHashSet;
LHS.add("Apple");
LHS.add("Cherry");
System.out.println(LHS.add("Cherry"));
LHS.add("Banana");
LHS.add(null);
LHS.add(null);
System.out.println(LHS);
System.out.println(LHS.size());
Iterator it = LHS.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
System.out.println(LHS.isEmpty());
System.out.println(LHS.contains("Apple"));
System.out.println(LHS.contains("Appl1e"));
}
}
Ranjeet Kendre
Program 5
package SetInterface;
import java.util.Iterator;
import java.util.TreeSet;
names.remove("David");
System.out.println(names);
System.out.println(numbers);
System.out.println(names.contains("Rahul"));
System.out.println(names.contains("Rahu1l"));
System.out.println(names.size());
}
}
}
Ranjeet Kendre
Difference between List and Set
List Set
The Queue interface in Java is part of the Java Collections Framework and represents a data
structure that follows the FIFO (First-In-First-Out) principle. Elements are added at the end (rear)
and removed from the front (head) of the queue.
• LinkedList
• PriorityQueue
• ArrayDeque
1. FIFO Order: Items are processed in the order they are inserted.
2. Insertion/Removal: Specialized methods to add and remove elements.
3. Thread-Safety: Some implementations like LinkedQueue provide thread-safe queues.
Implementations of Queue
1. LinkedList: Implements both List and Queue. Useful for FIFO operations.
2. PriorityQueue: Implements a priority-based queue where elements are ordered by their
natural ordering
Program 1
package Queue;
import java.util.LinkedList;
import java.util.Queue;
queue.add("Bob");
queue.offer("Rohit");
queue.add("Alice");
queue.add("Ketan");
System.out.println(queue);
System.out.println("head of the quque --"+queue.peek());
// System.out.println(queue.remove());
// System.out.println(queue);
Ranjeet Kendre
System.out.println(queue.poll());
System.out.println(queue);
System.out.println(queue.isEmpty());
Program 2
package Queue;
import java.util.PriorityQueue;
PO.add('A');
PO.add('B');
PO.add('C');
PO.add('D');
System.out.println(PO);
PO.offer('F');
System.out.println(PO);
//2.element -- Head
System.out.println(PO.element());
//System.out.println(PO1.element());
//3.Peak
System.out.println(PO.peek());
System.out.println(PO1.peek());
//3. Remove
System.out.println(PO.remove());
System.out.println(PO);
System.out.println(PO.poll());
System.out.println(PO);
// System.out.println(PO1.remove()); //NoSuchElementException
System.out.println(PO1.poll()); //Null
}
}
Ranjeet Kendre
Important collection question
Collection Framework is a combination of classes and interface, which is used to store and
manipulate the data in the form of objects. It provides various classes such as ArrayList,
Vector, Stack, and HashSet, etc. and interfaces such as List, Queue, Set, etc. for this purpose.
Array and Collection are somewhat similar regarding storing the references of objects and
manipulating the data, but they differ in many ways. The main differences between the array
and Collection are defined below:
◦ Arrays are always of fixed size, i.e., a user can not increase or decrease the length of
the array according to their requirement or at runtime, but In Collection, size can be
changed dynamically as per need.
◦ Arrays can only store homogeneous or similar type objects, but in Collection,
heterogeneous objects can be stored.
◦ Arrays cannot provide the ?ready-made? methods for user requirements as sorting,
searching, etc. but Collection includes readymade methods to use.
Collection framework implements various interfaces, Collection interface and Map interface
(java.util.Map) are the mainly used interfaces of Java Collection Framework. List of interfaces
of Collection Framework is given below:
3. Set interface: Set (java.util.Set) interface is a collection which cannot contain duplicate
elements. It can only include inherited methods of Collection interface
4.Queue interface: Queue (java.util.Queue) interface defines queue data structure, which
stores the elements in the form FIFO (first in first out).
5. Map interface: A Map (java.util.Map) represents a key, value pair storage of elements.
Map interface does not implement the Collection interface. It can only contain a unique key
but can have duplicate elements. There are two interfaces which implement Map in java that
are Map interface and Sorted Map.
Ranjeet Kendre
4) What is the difference between List and Set?
The List and Set both extend the collection interface. However, there are some differences
between the both which are listed below.
◦ The List can contain duplicate elements whereas Set includes unique items.
◦ The List is an ordered collection which maintains the insertion order whereas Set is an
unordered collection which does not preserve the insertion order.
◦ The List interface contains a single legacy class which is Vector class whereas Set
interface does not have any legacy class.
◦ The List interface can allow n number of null values whereas Set interface only allows
a single null value.
The default size of load factor is 0.75. The default capacity is computed as initial capacity *
load factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.
Arrays.asList(item)
We can convert an ArrayList to Array using toArray() method of the ArrayList class. Consider
the following syntax to convert the ArrayList to the List object.
List_object.toArray(new String[List_object.size()])
To reverse an ArrayList, we can use reverse() method of Collections class. Consider the
following example.
LinkedLists are better to use for the update operations whereas ArrayLists are better to use for
the search operations.
Multi-dimensional array: An array with multiple rows and/or columns, often referred to as an
array of arrays. For example, a 2D array:
int[][] multiArray = {
{1, 2, 3},
{4, 5, 6}
};
10. Can you change the size of an array after it has been created?
• Answer: No, Java arrays have a fixed size once they are created. To "resize" an array, you
can create a new array of the desired size and copy the elements from the original array. A
more flexible alternative is to use an ArrayList, which resizes dynamically.
Ranjeet Kendre
Java String Interview Question
1.What is a String in Java, and how is it different from StringBuilder and StringBuffer?
Answer: String in Java is an immutable class, meaning once a String object is created, it cannot be
modified. Any operation that appears to change a String actually creates a new String object.
• StringBuilder: A mutable sequence of characters, suitable for cases where the string is
modified frequently (not thread-safe).
• StringBuffer: Similar to StringBuilder but is thread-safe, meaning it is synchronized and
safe for use in multithreaded environments.
12.Can you explain the difference between == and equals() for String comparisons?
• Answer:
◦ == checks if two String references point to the same object in memory.
◦ equals() checks if two String objects have the same sequence of characters.
String a = "hello";
String b = new String("hello");
System.out.println(a == b); // false (different objects)
System.out.println(a.equals(b)); // true (same content)
Ranjeet Kendre
Exception Handling Interview questions
1.What is an exception?
Exception is an abnormal condition which occurs during the execution of a program and disrupts
normal flow of the program. This exception must be handled properly.If it is not handled, program
will be terminated abruptly.
2) How the exceptions are handled in Java? OR Explain exception handling mechanism in
Java?
Exceptions in Java are handled using try, catch and finally blocks.
try block : The code or set of statements which are to be monitored for exception are kept in this
block.
catch block : This block catches the exceptions occurred in the try block.
finally block : This block is always executed whether exception is occurred in the try block or not
and occurred exception is caught in the catch block or not.
4. Can we write only try block without catch and finally blocks?
No, It shows compilation error. The try block must be followed by either
catch or finally block. You can remove either catch block or finally block but not both.
5) Explain the hierarchy of exceptions in Java?6).What are run time exceptions in Java. Give
example?
The exceptions which occur at run time are called as run timeexceptions. These exceptions are
unknown to compiler. All sub classes of java.lang.RunTimeException and java.lang.Error are
run time exceptions. These exceptions are unchecked type of exceptions. For example,
NumberFormatException, NullPointerException, ClassCastException,
ArrayIndexOutOfBoundException, StackOverflowError etc.
11) Which class is the super class for all types of errors and exceptions in Java?
java.lang.Throwable is the super class for all types of errors and exceptions in Java.
Handle Exception
try{
// Specify the statement which casues exception
catch(Exception Type){
//Write the code
}
finally{
}
1. Exception occure,catch blockhandles,finally block aslo executed
2. Exception occure,catch block not handle,finally block executed
3. Exceptoon not occure,catch block will ignore ,finally block execute
There are two method to handle exception
1. Try catch block ( Handling check and unchecked exception)
2. Throws keyword (Handle only for checked excepti
In this method, an exception will always be thrown, so no return statement is needed. However, the
method still declares an int return type, but it never actually returns any value.
Ranjeet Kendre
Important interview questions
Primitive types are predefined (already defined) in Java. Non-primitive types are created by
the programmer and is not defined by Java (except for String ).
2.Memory size of primitive is fixed and. Memory size of non primitive is not fixed /defined.
3.What are the default values for the primitive data types in Java are as follows
byte: 0
short: 0
int: 0
long: 0L
float: 0.0f
double: 0.0d
char: (null character)
boolean: false
Yes, you can call a static method using an object reference in Java, but it is not
recommended because it can lead to confusion about the method's nature. Static methods
belong to the class itself rather than to any instance of the class, so the preferred way to call
a static method is using the class name.
Ranjeet Kendre
7.What is the use of control statement in java
Control statements in Java are fundamental constructs that control the flow of execution in a
program. They enable you to dictate which parts of your code get executed under certain
conditions, allowing for decision-making, looping, and branching.
8.What are control statements?
Answer: Control statements are used to control the flow of execution in a program based on
certain conditions or loops. They are mainly categorized into conditional statements (like if,
else, else-if ,switch).
10.What is the difference b/w static method and non static methods
Static Method:
• Access: A static method belongs to the class itself rather than any instance/object of
the class. It can be called directly using the class name without creating an instance.
• Keyword: Declared using the static keyword (e.g., static void methodName() in
Java).
• Scope: Static methods can only access other static variables and static methods of the
class. They cannot directly access non-static (instance) variables or methods.
• Purpose: Typically used when a method’s functionality is independent of any
particular instance. For example, utility or helper methods.
Ranjeet Kendre
Non-Static (Instance) Method:
• Access: A non-static method is tied to an instance of the class. It can only be called on
an object (instance) of that class.
• No static Keyword: Declared without the static keyword.
• Scope: Non-static methods can access both static and non-static (instance) variables
and methods. They have full access to the class’s state.
• Purpose: Used when behavior is specific to the instance, as non-static methods can
modify the object’s state.
Key Differences:
Aspect Static Method Non-Static Method
Belongs to Class Instance (object)
Accessed by Class name (without object) Object (instance of class)
Access to class Can access both static and non-
Can access only static variables/methods
members static members
Independent of any instance (utility, Speci c to an instance (modify
Use case
helper functions) object state)
Key Differences:
Aspec Class Object
Det ni An instance of a class that represents a
A blueprint or template for creating objects.
tion speci c entity.
Natur Abstract: It de nes properties and behaviors Concrete: It holds speci c data and can
e but holds no actual data. perform actions.
Creati Declared once using the class keyword. Created multiple times using the new
on keyword.
fi
fi
fi
fi
fi
Ranjeet Kendre
Mem Does not occupy memory until an object is Occupies memory as each object stores its
ory
Exam created. own data.
Car class de nes general attributes like An object myCar has speci c values like
ple "Toyota",
Purpo model color
De nes ,the .
properties and behaviors that Represents"Red".
an actual instance with data that
se objects will have. can be manipulated.
• Method:
◦ Used for defining behavior (operations) for objects.
◦ Can have any name.
◦ Must specify a return type (or void if it returns nothing).
◦ Called explicitly using the object.
Polymorphism is a concept by which we can perform a single task in different ways. That is,
when a single entity (object) behaves differently in different cases, it is called polymorphism.
In other words, if a single object shows multiple forms or multiple behaviours, it is called
polymorphism.
a. Inheritance represents the parent-child relationship between two classes. On the other hand,
polymorphism takes the advantage of that relationship to make the program more dynamic.
b. Inheritance helps in code reusability in child class by inheriting behavior from parent class.
On the other hand, polymorphism enables child class to redefine already defined behavior
inside parent class.
Without polymorphism, it is not possible for a child class to execute its own behavior.
In Compile time Polymorphism method declaration and Definition are bonded during the
compilation time based on argument or input parameter is known as compile time
polymorphism.
7. What is Runtime Polymorphism (Dynamic Polymorphism)?
Run time Polymorphism method declaration and Definition are binded during the run time or
execution time based on input parameter or argument is known as Run Time Polymorphism.
Ans: The connecting (linking) between a method call and method definition and method
declaration is called binding
Ans: There are two types of binding in java. They are as follows:
Ans: The binding that happens during compilation is called static binding in java. This binding
is resolved at the compiled time by the compiler.
Ans: Java compiler just checks which method is going to be called through reference variable
and method definition exists or not.
It does not check the type of object to which a particular reference variable is pointing to it.
Ans: Static binding is also called early binding because it takes place before the program
actually runs.
Ans: The binding which occurs during runtime is called dynamic binding in java. This binding
is resolved based on the type of object at runtime.
Ans: In the dynamic binding, the actual object is used for binding at runtime. JVM resolved
the method calls based on the type of object at runtime. The type of object cannot be
determined by the compiler.
Yes
No
Yes
No
Method overloading cannot be done by changing the return type of methods. Broadly speaking
yes return type of overriding method can be different. But it's not
Output: If the return type is void or primitive then the data type of parent class method and
overriding method should be the same. e.g. if the return type is int, float, string then it should
be same
Output: If the return type of the parent class method is derived type then the return type of the
overriding method is the same derived data type of subclass to the derived data type.
24. What is the difference between Method overloading and Method overriding.
Inheritance is a process where a One class acquires property of another class with the help of
extends keywords is known as inheritance.
Ans: Inheritance is one of the main pillars of OOPs concept. Some objects share certain properties
and behaviours. By using inheritance, a child class acquires all properties and behaviours of parent
class.
a. Single inheritance
b. Multi-level inheritance c. Hierarchical inheritance d. Multiple inheritance
e. Hybrid inheritance
Ans: Is-A relationship represents Inheritance. It is implemented using the “extends” keyword. It is
used for code reusability.
Ans: A class from where a subclass inherits features is called superclass. It is also called base class
or parent class.
A class that inherits all the members (fields, method, and nested classes) from other class is called
subclass. It is also called a derived class, child class, or extended class.
extends: extends is a keyword that is used for developing the inheritance between two classes and
two interfaces.
A static method of superclass is inherited to the subclass as a static member and non- static method
is inherited as a non-static member only.
Ans: No.
We can minimize the length of duplicate code in an application by putting the common code in the
superclass and sharing it amongst several subclasses. Due to reducing the length of code, the
redundancy of the application is also reduced.
Ans:
Multiple inheritance means that one class extends two superclasses or base classes but in Java, one
class cannot extend more than one class simultaneously. At most, one class can extend only one
class.
Therefore, to reduce ambiguity, complexity, and confusion, Java does not support multiple
inheritance through classes.
Ans: When one class is extended by only one class, it is called single level inheritance. In single-
level inheritance, we have just one base class and one derived class.
fi
fi
fi
Ranjeet Kendre
A class which is extended by a class and that class is extended by another class forming chain
inheritance is called multilevel inheritance.
Ans: A class that has many superclasses is known as multiple inheritance. In other words, when a
class extends multiple classes, it is known as multiple inheritance.
Ans: Multiple inheritance can be implemented in Java by using interfaces. A class cannot extend
more than one class but a class can implement more than one interface.
19. What is Hybrid inheritance in java? How will you achieve it?
Ans: A hybrid inheritance in java is a combination of single and multiple inheritance. It can be
achieved through interfaces.
20. How will you restrict a member of a class from inheriting its subclass?
Ans: We can restrict members of a class by declaring them private because the private members of
superclass are not available to the subclass directly. They are only available in their own class.
Ans: No, we can access only superclass members but not the subclass members.
22. Can we access both superclass and subclass members if we create an object of subclass?
23. What happens if both superclass and subclass have a eld with the same name?
Ans: No.
fi