0% found this document useful (0 votes)
10 views172 pages

Java Notes

The document provides an overview of Automation Testing, focusing on Java as the primary programming language used with Selenium for automation. It covers essential Java concepts such as data types, variables, methods, control statements, and loops, along with their syntax and examples. The document serves as a guide for learning Java programming in the context of automation testing, detailing project structure and coding best practices.

Uploaded by

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

Java Notes

The document provides an overview of Automation Testing, focusing on Java as the primary programming language used with Selenium for automation. It covers essential Java concepts such as data types, variables, methods, control statements, and loops, along with their syntax and examples. The document serves as a guide for learning Java programming in the context of automation testing, detailing project structure and coding best practices.

Uploaded by

Shraddha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 172

Ranjeet Kendre

Date -20 -Sep-2024

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.

Programming Language example -

C , C++, C#, Java, .net. Ruby , R, Python.


Most of the company are using JAVA with selenium so we going to learn in our class Java.

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 :

Project creation Steps in eclipse

Java Project —> (Demo)


Multiple Packages —> (Test1,Test2, Test3)

1 Package —> Multiple Classes —> (Sample1, Sample 2) 1 Class —> Multiple Methods —> Main
method

1 Main method —> Multiple printing statement

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 -

public static void main(String [] args){


// Code/ Program
}

The curly braces { } marks the beginning and ending of the block of the code.

Code statement must end with a semicolon( ; )


System.out.println(“Automation"); — Printing statement
Ranjeet Kendre

20 -Sep-2024

First Section syllabus

1. Variables
2. Data Type
3. Methods
4. Loops
5. Control statements
6. Keywords & identifiers
7. Types of variables
8. Constructor

1. Variables :

1. Variables are nothing but piece of memory use to store information


Note - One variable can store 1 information at a time.
2. Variables also used in code/information reusability.
3.To utilise variables in java programming language we need to follow below steps:

1.Variable declaration (Allocating/Reserving memory).


2.Variable Initialisation (Assigning or inserting value)
3.Usage

Program 1.
Ranjeet Kendre

Program 2

Program 3
Ranjeet Kendre

Date -21 Sep 2024


Program 4

Date - 23 Sep 2024

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.

2. In java programming it is mandatory to declared data type before declaration of


variables;

There are two types of data types


1. Primitive data type
2. Non -Primitive data type. -

There are 8 primitive data type in java

1.Byte. - 1 Byte —> 8 Bit. —> -128 to 127


2. Short - 2 Byte —> 16 Bit —> -32768 to 32767
3. Int - 4 Byte —-> 32 Bit —> 2147483648 to 2147483647
Ranjeet Kendre
4. Long - 8 Byte —-> 64 Bit —> 9223372036854775807
5. Boolean. —- > 1 Bit
6. Char. — > 2 Byte - 16 Bit
7. Float. — >. 4 Byte - 32 Bit
8. Double — >. 8 Byte - 64 Bit

Program 1
Ranjeet Kendre
Program 2

Program 3
Ranjeet Kendre
Program 4
Date - 25 Sep 2024

2. Non 2. 2.Primitive data type


Example —> String , Array, Classes
Memory size of non primitive is not fixed /defined
Ranjeet Kendre
Methods :
1. A method is a block of code or collection of statements or a set of code grouped
together to perform a certain task or operation.

2. It is used to achieve the reusability of code.

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

4.Method is executed only when we call or invoke it

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

2.User Define/ Regular Method


1. Static regular method
1. Static regular method call from same class.
2. Static regular method call from different/another class

2. Non static regular method


1.Non- Static regular method call from same class.
2.Non- Static regular method call from different/another class
Ranjeet Kendre

Program 1

Program 2
Ranjeet Kendre

Program 3. - Date 26/09/2024

Program 4
Ranjeet Kendre

Program 5

Program 6
Ranjeet Kendre

Program 7

Date - 27/09/2024
2. Non static regular method

Example. - public void test(){


//body
}
How to call non static methods
first we need to create an instance/object of the class, post which we can call using
objectrefrencevariableName. methodName()

Syntax to create java object

Class_name object_reference_name = new Class_name();

What is object in java

In object-oriented programming terminology, an object is a member of Java class. It is also known


as instance of the class.
Note that objects are created at run time. In simple words, object is a real word entity.
For example, dog, car, pen, desk, etc.
Ranjeet Kendre

Program 8

Program 9
Ranjeet Kendre

Program 10

Program 11
Ranjeet Kendre

Program 12
Ranjeet Kendre
Date - 30/09/2024

4. Parameters and Arguments method


Information can be passed to methods as parameter. Parameters act as variables inside the
method.Parameters are specified after the method name, inside the parentheses. You can add as
many parameters as you want, just separate them with a comma.

5. Return Statement in Java


In Java programming, the return statement is used for returning a value when the execution of the
block is completed.

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

1. Arithmetic operators. —>> + - * / %


2. Logical operators. — >. && and operator , || OR operator
3. Assignment operator —>. =, += ,-=
4. Relational Operator - <. , > , <=, , >=, != ,=, ==.
5. Increment operator. -++
6. Decrement 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.

It is one of the fundamental features of Java, which provides a smooth flow of


program.
1. Simple If Statement
2. If else statement
3. if-else-if ladder statement
Ranjeet Kendre
4. Nested if statement
5. Switch statement
1. Simple if statement
It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression
evaluates to true
Syntax:
if(condition) {
statement 1; //executes when condition is true
}

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
}

if-else if ladder works in the following steps that are as follows:


1. The first specified condition evaluates to true. If the condition is true, statement1 will execute and
the rest part of else if ladder will skip.
2. If the specified condition is false, the second if condition evaluates to true. If the second
condition is true, statement2 will execute, and the rest part of the ladder will skip.
3. If the second condition is false, the third condition and the rest of the conditions (if required) are
evaluated (or tested) until a condition is met or all of the conditions prove to be false.
4. If all of the conditions are false, the final else statement (i.e. statement4) associated with the top
if statement will be executed.
5. The statement associated with final else acts as a default condition. That is, if all of the above
conditional tests fail, the statement associated with the last else will be executed.
If there is no final else statement and none of the conditions is true, no action will take place.
Ranjeet Kendre

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

1. For loop - Most com used


2. While Loop
3. Do while loop
4. For Each /Advance for loop

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.

3. Increment/Decrement: It increments or decrements the variable value.

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

Static/class global variable creating outside the method/function is know as global


variable.

1. Static/Class global variable


A variable that declared as static is called as static variable. It cannot be local var
2. Non static variable
A variable that declared as without using static keywords.and outside the method

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

5. Meaningful Names (Convention):


• It is a common convention to use meaningful names that describe the purpose of the variable or
function, enhancing code readability.
◦ Example:
▪ Instead of x, use totalSum for a sum value.

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

Below is the list of reserved keywords in Java:

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

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

int[] numbers = {1, 2, 3, 4, 5}; // Array of integers

numbers[0] = 1;
numbers[1] = 2;

4.Accessing Array Elements


System.out.println(numbers[0]); // Prints the first element

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];

2.Multi-Dimensional Array: Arrays of arrays (e.g., 2D arrays for matrices).


int[][] matrix = new int[3][3];

Sorting an Array
Arrays.sort(numbers);

Advantages of Arrays in Java

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 {

public static void main(String[] args) {

// int arr [] = new int[4];


// arr[5] = 44;
// Array is a collection of similar type of data or element

// We can store only fixed set of element in java array


// array is a index based and first element is of array stores at oth index and
// last index index ins N-1)Length of arraY_)

// single dimensional array

int arr[] = new int[10]; //0 to 9

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

int A2[] = { 10, 20, 30, 40, 50 };

int len = A2.length;

System.out.println(len); //10

System.out.println(arr[4]);

System.out.println(A2.length);

// NegativeArraySizeException

for(int i=0 ; i< 10; i++) {

System.out.println(arr[i]);
}
}
}
Ranjeet kendre

Program 2

package Arrays;

import java.util.Arrays;

public class Array2 {

public static void main(String[] args) {

int arr[] =new int[10];

boolean [] B1 = new boolean[5];

B1[0] =true;

//B1[1] = 10;

B1[4] =false;

System.out.println(B1[0]);
System.out.println(B1[2]);
System.out.println(B1[4]);

char ch [] = new char[4]; //Array dec

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;

public class Array3 {

public static void main(String[] args) {

//1.Size is fixed - To overcome this problem - We use collection - arraylist


//2.Store only similar type data - We use Object array

int i[] = new int[5]; //Size of array - N-1


i[1] =10;
i[4] =30;
// i[5] =50;

int i1[] = {1,2,4};

System.out.println(i1);

//System.out.println(i[4]);
System.out.println(i[4]);

Program 4

package Arrays;

import java.util.HashSet;

public class Array4 {

public static void main(String[] args) {

Array4 a4 = new Array4();

String str [] = new String[4]; // NegtiveArraysizeexcetion


String str1 [] = new String[4];
String []str2 = new String[4];

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();

for(int Test=0 ;Test<=str.length-1 ;Test++) {

System.out.println(str[Test]);

Program 5

package Arrays;

public class Array5 {

public static void main(String[] args) {

Object obj[] = new Object[6];// Heterogeneous type of data /Non


similar type of data

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]);

for (int i = 0; i < obj.length; i++) {

System.out.println(obj[i]);
}

Program 6

package Arrays;

public class Array6 {

public static void main(String[] args) {

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]);

int size = arr.length;

System.out.println(size);

Program 7

package Arrays;

public class Array7 {

public static void main(String[] args) {

String str1 [] = new String[5];

String str [][] = new String[5][5]; //2D Array /MultiDim arrays


//Row Col

Object Obj [][] = new Object[5][5];

System.out.println("Row -->"+str.length); //5


System.out.println("Row -->"+str[3].length); //5

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]);

for(int Row=0 ;Row<str.length;Row++) { //Row

for(int Col=0;Col<=str[3].length-1 ;Col++) {

System.out.print(str[Row][Col]+" ");
}
System.out.println();
}

Program 8

package Arrays;

public class Array8 {

public static void main(String[] args) {


Ranjeet kendre

int arr[][] = new int[4][3]; //

System.out.println(arr.length);

System.out.println(arr[2].length);

int arr1[][] = {{1,2,3},{3,4,5},{5,6,7},{55,66,77}}; //4*3

System.out.println(arr1.length); //4
System.out.println(arr1[2].length); //3

int col =arr1[3].length;

//for(int Row=0)

System.out.println(arr1[0][2]);
// System.out.println(arr1[3][3]);

for(int Row=0 ; Row<arr1.length;Row++) {

for(int Col=0 ;Col<col ;Col++) {

System.out.print(arr1[Row][Col]+" ");
}
System.out.println();
}

Program 9
package Arrays;

public class ArrayLogicalprogram1 {

public static void main(String[] args) {

int A2[] = { 10, 20, 30, 40, 50 ,60,10}; // 150

int len = A2.length;


Ranjeet kendre

int sum = 0;

for (int i = 0; i <= len - 1; i++) {

sum = sum + A2[i];


}

System.out.println("Sum of given array --->" + sum);

Program 10

package Arrays;

public class duplicateelement {

public static void main(String[] args) {

int Arr[] = { 10, 20, 30, 40, 50, 10, 20,50 };

//size of arrays is 7

int len =Arr.length; //7

for(int i=0 ;i<len ;i++) { //0 0<7 - True 1<7 - true

for(int j=i+1; j<len;j++) { //1 <7 true 7<7 - false false

if(Arr[i]==Arr[j]) { //10==20 - False 10==30 - false 10==40


10==50 10==10 10==20 10==50

System.out.print(Arr[j]+" "); //10,20


}
}
}

}
Ranjeet kendre

Program 11

package Arrays;

public class LogicalProgram2 {

public static void main(String[] args) {

String Str = "Auto generated";

//Expected out - otuA detareneg dohtem duts

String[] words = Str.split(" ");


// 0 - Auto 1.gene 2. method 3 stub

String Rev = "";

for(String word : words) { //


//Auto
String RevWord = "";
//3
for(int i=word.length()-1 ;i>=0 ;i--) {

RevWord = RevWord+word.charAt(i);
}

Rev = Rev+RevWord+" ";

}
System.out.println(Rev);

}
Ranjeet Kendre
Java String

In Java, string is an object/class that represents a sequence of characters.

1. String is an object/class that represents a sequence of characters.


2. String is a class present inside "java.lang" package.
3. String is used to store collection of characters/numbers
4. String objects are immutable in nature/can’t be change.
5. String class is final class can't be inherited/extends to other classes.

There are two ways to create String object:

1.By string literal. — Ex :String S = "welcome";


2.By new keyword - String S = new String("Welcome");

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.

3. Code optimization and performance

Why String class is Final in Java?

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.

Java String compare

1.By Using equals() Method


2.By Using == Operator

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

• In Java, a String is an object that represents a sequence of characters.


• Strings are immutable, meaning once a String object is created, its value cannot be
changed.
• String literals in Java are stored in a special memory area known as the String
Constant Pool.

2. Creating Strings

String str1 = "Hello"; // Using a String literal


String str2 = new String("Hello"); // Using the `new` keyword

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

• == Operator: Checks if two references point to the same object (reference


comparison).
• .equals(): Checks if the values of two strings are equal (content comparison).
• .compareTo(): Lexicographically compares two strings and returns an integer:
◦ 0 if they are equal.
◦ Negative if the first string is lexicographically less than the second.
◦ Positive if the first string is lexicographically greater.
Ranjeet Kendre

Program 1

package String;

public class String1 {

public static void main(String[] args) {

// There are two ways to create string object

// 1.String Literal
// 2. By using new keyword

// String Literal

// String vername = "value";

String Str = "Automation";


String Str1 = "Automation";

// By using new keyword


String Str2 = new String("Welcome");
String Str3 = new String("Welcome");

}
Ranjeet Kendre

Program 2

package String;

public class String2 {

public static void main(String[] args) {

//How many object will be created


String S1 = "Test";
String S2 = "Test";
String S3 = new String("Java");
String S4 = new String("Test");
String S5 = new String("Automation");

System.out.println(S1==S4); //True
System.out.println(S1.equals(S4)); //True

}
Ranjeet Kendre

Program 3

package String;

public class String3 {

public static void main(String[] args) {

String S1 = new String("Java"); //20


String S2 = new String("Java"); //21
String S3 = new String("java"); //22

System.out.println(S1==S2); // Java == Java //False


System.out.println(S1.equals(S2)); // True

System.out.println(S1==S3);
System.out.println(S1.equals(S3));

String S4 ="Java"; //28


String S5 ="Java"; //28
String S6 = "Test"; //36

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;

public class String4 {

public static void main(String[] args) {

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;

public class String5 {

public static void main(String[] args) {

//Difference b/w == operator and .equals method

String S1 = "Java";
String S2 = "Python";
String S3 = "Java";

System.out.println(S1==S3); //True
System.out.println(S1.equals(S3)); //True

String S4 = new String(" ");


String S5 = new String("C#");
String S6 = new String(" ");
System.out.println(S4);

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;

public class String6 {

public static void main(String[] args) {

//String utable

String S1 = "Pune"; //21

S1 = "RRR";

System.out.println(S1);

String S2 = "Mumbai"; //33

String S3 = "Pune"; //24

String S4 = "Pune"; //24

S4 = "Solapur";
System.out.println(S1);
System.out.println(S4);

String Str = "Hello";

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;

public class LogicalProgram {

public static void main(String[] args) {

String Str = "Hello";

//gnineve doog olleH


//gnineve doog olleH

int len = Str.length(); //5


Ranjeet Kendre

String Rev = ""; //Rev

for(int i=len-1;i>=0 ;i--) { //True

Rev = Rev + Str.charAt(i); //o


//olleH
}

System.out.println(Rev);

Program 8
package String;

public class StringMethods {

public static void main(String[] args) {

// CharAt Function or method

// It return char value for the specified indecx

String S1 = "Automation"; // 0123456789

// System.out.println(S1.charAt(19)); //StringIndexOutOfBoundsException:

System.out.println(S1.charAt(8));
System.out.println(S1.charAt(4));

// Length - it retrun length or size of the string


System.out.println(S1.length());

// .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());

String S8 = null; // java.lang.NullPointerException:


// System.out.println(S8.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

String Str = "Hi good evening";

String arr[] = Str.split(" ");

for (int i = 0; i < arr.length; i++) {

System.out.println(arr[i]);
}

String arr1[] = Str.split("i");

for (int i = 0; i < arr1.length; i++) {

System.out.println(arr1[i]);
}

System.out.println("****");

for(String str : arr) { //for each loop


System.out.println(str);
}
Ranjeet Kendre

int [] number = {1,2,4,5,6,7};

int sum =0;

for(int num :number) {

sum += num;
// sum = sum+num
}

System.out.println(sum);

Program 9
package String;

public class StringMethods1 {

public static void main(String[] args) {

// equalignorecase

String S1 = "JAVA";

String S2 = "java";

System.out.println(S1.equals(S2)); // False
System.out.println(S1.equalsIgnoreCase(S2)); // true

// SubString

String S3 = "Velocity Classes ";

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

String S4 = "Velocity classes java testingc";

System.out.println(S4.length());

System.out.println(S4.indexOf('c'));// 1st occurrence

System.out.println(S4.indexOf('c', S4.indexOf('c') + 1)); //2md

System.out.println(S4.indexOf('c', S4.indexOf('c', S4.indexOf('c') + 1) + 1)); //3rd

// Lowercase

String S5 = "JAVA";
System.out.println(S5.toLowerCase());

// ToUppercase

String S6 = "java";
System.out.println(S6.toUpperCase());

// Trim

/// it remove starting or ending spaces

String S7 = "Velocity classes java testingc ";

System.out.println(S7);
System.out.println(S7.trim());

// Trim, , CharAT, Split ,SubString

String S8 = "12/12/2024";

String[] Str = S8.split("/");

for (String num : Str) {

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'

3. substring(int beginIndex) and substring(int beginIndex, int endIndex)


Extracts a substring from the string. The rst form extracts from the speci ed index to the
end, while the second form extracts up to but not including endIndex.
String text = "Hello, World!";
String sub = text.substring(7); // "World!"
String sub2 = text.substring(7, 12); // “World"

4. indexOf(String str) and lastIndexOf(String str)


Returns the index of the rst or last occurrence of the speci ed substring. Returns -1 if
not found.
String text = "Hello, World!";
int index = text.indexOf("World"); // 7
int lastIndex = text.lastIndexOf("o"); // 8

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

6. startsWith(String pre x) and endsWith(String su x)


Checks if the string starts or ends with the speci ed pre x or su x.
String text = "Hello, World!";
boolean starts = text.startsWith("Hello"); // true
boolean ends = text.endsWith("!"); // true

7. toLowerCase() and toUpperCase()


Converts all characters in the string to lowercase or uppercase.
String text = "Hello, World!";
String lower = text.toLowerCase(); // "hello, world!"
String upper = text.toUpperCase(); // "HELLO, WORLD!”

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!"

10. split(String regex)


Splits the string into an array of substrings based on the speci ed regular expression.
String text = "Hello, World!";
String[] parts = text.split(", "); // ["Hello", "World!"]

11. equals(Object obj) and equalsIgnoreCase(String anotherString)


Compares two strings for equality. equalsIgnoreCase ignores case di erences.
String text = "Hello";
boolean isEqual = text.equals("hello"); // false
boolean isEqualIgnoreCase = text.equalsIgnoreCase("hello"); // true

12. compareTo(String anotherString)


Compares two strings lexicographically. Returns a negative integer, zero, or a positive
integer if this string is less than, equal to, or greater than the speci ed string.
String text1 = "apple";
String text2 = "banana";
int result = text1.compareTo(text2); // -1 (because "apple" < “banana")

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

UpCasting Implicit Casting (Widening)


DownCasting Explicit Casting (Narrowing)

1. Upcasting / Implicit Casting/ Widening

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.

Byte → Short → Int → Long → Float → Double:


Smaller types can be automatically converted to larger types.

2. DownCasting / Explicit Casting / Narrowing

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.

Double → Float → Long → Int → Short → Byte:


Larger types can be manually converted to smaller types, but there's a risk of data loss.

Program 1
Ranjeet Kendre
Program 2

Program 3
Ranjeet Kendre
Program 4

Program 5
1. This Keyword

This keyword is used to access global variables from same class

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

Super keyword is used to access global variable from different/super/parent class.


The super keyword is used to refer to the superclass (parent class) members or constructors. It’s
often used when overriding methods or to access members and constructors of the superclass.

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

Exception handling - Exception handling is a mechanism to handle runtime error such


classnotfoundexception, webdriverexception,IOExceptio. Nullpointerexcpetion

Advantage of exception handling

The core advantage of exception handling is to maintain the normal ow of the


application. An exception normally
disrupts the normal ow of the application; that is why we need to handle exceptions.

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

There are mainly two types of exceptions: checked and unchecked.


1. Checked exceptions
1.InterruptExxception
2.FilenotfoundException
3.IOException

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 - throw is used within the method.


Throws - throws is used with the method signature.

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;

public class Test {

public static void main(String[] args) {

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;

public class ExceptionHandling1 {

public static void main(String[] args) {

System.out.println("Program is started");

// Scanner sc = new Scanner(System.in);


//
// System.out.println("Enter a number");
//
// int num = sc.nextInt();
//
// System.out.println(100/num);
//
// System.out.println("Program is completed");

//Example 2

int [] arr = new int[5];


//arr[5]=40;

// System.out.println("Enter the position (0-4)");


// int test = sc.nextInt();
//
// System.out.println("Enter a value");
// int test1 = sc.nextInt();
// arr[test] =test1;
// System.out.println(arr[test]);

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;

public class ExceptionHandling2 {

public static void main(String[] args) {

/**
* try{
*
* statement
*
* } catch(Exception name){
*
* statement ; }
*
*/

System.out.println("Program is started");

Scanner sc = new Scanner(System.in);

System.out.println("Enter a number");

int num = sc.nextInt();

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 {

int num1 = Integer.parseInt(S2);

} catch (NumberFormatException e) {

System.out.println("Hello");
}

System.out.println("Program is completed”);

Program 4
package ExceptionHandling;

public class ExceptionHandling3 {

public static void main(String[] args) {

//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());

System.out.println("Handle Exception 1");


}
catch (NumberFormatException e) {

e.getMessage();
System.out.println("Handle Exception 2");

}
catch (ArrayIndexOutOfBoundsException e) {
e.getMessage();
System.out.println("Handle Exception 3");

}
catch (Exception e) {

System.out.println("Handle Exception 4");


}

finally {
System.out.println("This is and finally block");
}
System.out.println("Program completd");

Program 5
package ExceptionHandling;

public class ExceptionHandling4 {

public static void main(String[] args) {

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

System.out.println("Catch block handle exxception");


}

finally {
System.out.println("You entered into finally block");
}
}

Program 6

package ExceptionHandling;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class ExceptionHandling5 {

public static void main(String[] args) {

// throw and throws


/**
try {

//Code that might throw exception


}
catch(ExceptionType e){

code to handle the exception


}
finally{

code that always executed whether the exception thow ot not


}

// */
//
//
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;

public class ExceptionHandling6 {

public static void main(String[] args) {

try {

ExceptionHandling6.checkAge(15);

catch (ArithmeticException test) {


System.out.println("Hello");
}

System.out.println("PC");

public static void checkAge(int age) {

System.out.println("PS");

if (age < 18) {

throw new ArithmeticException("Not eligible to vote - age must


be grater than 18");

} else {

System.out.println("Eligible to vote");

}
}
}

Program 8

package ExceptionHandling;

public class ExceptionHandling7 {

public static void main(String[] args) {

int num = Calculation(0);


System.out.println(num);

int num1 = Calculation(1);


System.out.println(num1);

public static int Calculation(int number) {

try {

int result = 10 / number;


Ranjeet Kendre
return result;
} catch (ArithmeticException e) {

System.out.println("Can not divide by zero");

return 11;
}

finally {
System.out.println("calculation compeleted");

// Staackoverflowiserror
// outofmemoryError
}

Program 9

package ExceptionHandling;
public class Stackoverlowerror {

static int number = 1;


public static void main(String[] args) {

Integer arr[] = new Integer[1000*1000*1000]; //OutOfMemoryError

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.

The main principles of object-oriented programming are Abstraction, Encapsulation,Inheritance and


Polymorphism.

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.

Importance of the inheritances

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

1. Single level inheritance


2. Multilevel inheritance
3. Multiple inheritance
4. Hybrid inheritance
5. Hierarchical inheritance

1. Single level inheritance


It is an operation where inheritance takes place between 2 classes. To perform single level inheritance
only two classes are required.
The class from where properties are acquiring/inheriting is called super class/base class
The class to where properties are inherited/delivered is called sub class/child class.

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.

Question - Why multiple & hybrid inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

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.

1. Single level inheritance


Ranjeet Kendre

Program 1

package Inheritance_SingleLevel;

public class father {

public void Car() {

System.out.println("Car -- Swift");
}

public void Home() {


System.out.println("Home -- 2 BHK");
}

public void Money() {


System.out.println("Money - 2 Lakh");
}

Program 2

package Inheritance_SingleLevel;

public class Son extends father{

public void Bike() {

System.out.println("Bike -- FZ");
}

public static void main(String[] args) {

Son S1 = new Son();

S1.Bike();
S1.Home();
S1.Car();
S1.Money();

}
}
Ranjeet Kendre
Program 3

package Inheritance_SingleLevel;

public class Son3{

public void Bike() {

System.out.println("Bike -- FZ");

2. Multilevel inheritance

Program 1.

package Inheritance_Multilevel;

public class WhatsAppV1 {

public void TextMsg() {

System.out.println("Text Message");
}
Ranjeet Kendre
}

Program 2

package Inheritance_Multilevel;

import Inheritance_Hie.father;

public class WhatsAppV2 extends WhatsAppV1 {

public void AudioCalling() {

System.out.println("Audio Calling");
}
}

Program 3

package Inheritance_Multilevel;

public class WhatsAppV3 extends WhatsAppV2{

//Text msg
//Audio calling

public void VideoCalling() {

System.out.println("Video Calling");
}
}

Program 4

package Inheritance_Multilevel;

public class WhatsAppV4 extends WhatsAppV3{

//Text msg
//AC
//VC

public void Payement() {

System.out.println("Payment");
}
}
Ranjeet Kendre
Program 5

package Inheritance_Multilevel;

public class Test {

public static void main(String[] args) {

WhatsAppV1 V1 = new WhatsAppV1();

V1.TextMsg();

System.out.println();

WhatsAppV2 V2 = new WhatsAppV2();

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;

public class father {

public void Car() {

System.out.println("Car -- Swift");
}

public void Home() {


System.out.println("Home -- 2 BHK");
}

public void Money() {


System.out.println("Money - 2 Lakh");
}

public static void Money1() {


System.out.println("Money - 2 Lakh");
}
}
Ranjeet Kendre
Program 2

package Inheritance_Hie;

public class Son1 extends father{

public void Bike() {

System.out.println("Bike");

}
}

Program 3

package Inheritance_Hie;

public class Son2 extends father {

public void Mobile() {

System.out.println("Mobile");
}

Program 4

package Inheritance_Hie;

public class Son3 extends father{

public void Laptop() {


System.out.println("Laptop");
}
}

Program 5

package Inheritance_Hie;

public class Test extends Son3{


public static void main(String[] args) {

Son1 S1 = new Son1();

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.

There are four types of Java access modifiers:

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 class Public1 {

public int number = 1000;

public Public1() {

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

Public1 P1 = new Public1();

P1.M1();

System.out.println(P1.number);
}

public void M1() {


Ranjeet Kendre

System.out.println("Public m1 method");
}

Program 2

package AccessModifiers;

public class DiffClass {

public static void main(String[] args) {

Public1 P2 = new Public1();

P2.M1();
System.out.println(P2.number);

// Private1 P3 = new Private1();


// P3.D1();
// System.out.println(P3.No);

Default1 D1 = new Default1();

System.out.println(D1.Test);
D1.T1();

Protected1 P4 = new Protected1();

P4.P1();
System.out.println(P4.name);
}

Program 3

package AccessModifiers;

public class Private1 {

private int No = 40;

public static void main(String[] args) {

Private1 P1 = new Private1();


P1.D1();
//System.out.println(P1.no);

private void D1() {


Ranjeet Kendre
System.out.println("Private method");
}

Program 4

package AccessModifiers;

public class Default1 {

String Test = "Java";

public static void main(String[] args) {

Default1 D1 = new Default1();

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;

public class Test extends Protected1{

//P1
//name
public static void main(String[] args) {

Public1 P1 = new Public1();


P1.M1();
System.out.println(P1.number);

Private1 P2 = new Private1();


// P2.D1();
Ranjeet Kendre
// System.out.println(P2.No);

Default1 D1 = new Default1();


// D1.T1();
// System.out.println(D1.Test);

Protected1 P4 = new Protected1();

Test T1 = new Test();


T1.P1();
System.out.println(T1.name);

}
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

1 Compile time Polymorphism


2.Run time Polymorphism

Compile time 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.

Example - Method overloading

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.

Run Time Polymorphism

In Run time Polymorphism method declaration and Definition are binded during the run time or
execution time based on input parameter or argument.

Example - Method overriding


When the method is present in parent class as well as in child class with same name and same
number of arguments/input parameter is called as method overriding.
In overriding method resolution always take care by JVM based on
Run time object no based on reference type that why it is also known as run time polymorphism or
dynamic Polymorphism or late binding.

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

1.Run Time Polymorphism

In Run time Polymorphism method declaration and Definition are binded during the run time or
execution time based on input parameter or argument.

Example - Method overriding


When the method is present in parent class as well as in child class with same name and same
number of arguments/input parameter is called as method overriding.
In overriding method resolution always take care by JVM based on Run time object and based on
reference type that why it is also known as run time polymorphism or dynamic Polymorphism or
late binding.

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.

Rules for Method Overloading in Java:

1. Different Number of Parameters: Methods can be overloaded by changing the number of


parameters.
2. Different Parameter Types: Methods can be overloaded by changing the type of
parameters.
3. Order of Parameters: Methods can also be overloaded by changing the order of parameters
if the types are different.
4. Return Type Does Not Matter: Overloading is not determined by the return type of the
method. Changing only the return type will result in a compilation error.
5. Access Modifiers and Static Methods: The access modifier and the static keyword don't
affect method overloading. You can overload static, private, final methods as well as non-
static methods.

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

A class which is declared with abstract keyword is known as abstract class.


It can have abstract and non abstract methods (Method body).

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.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java


1.Abstract class (0 to 100%)
2. Interface (100%)

Rules of abstract class

1. An abstract class must be declared with an abstract keyword.


2. It can have abstract and non abstract methods
3. We can not crate the object of abstract class
4. It can have constructor and static method method
Ranjeet Kendre
Abstract method

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.

Abstraction real time example :

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

Key Rules of Abstraction in Java


1. Abstract Classes and Abstract Methods:
◦ An abstract class is a class declared with the abstract keyword. It can have
abstract methods (methods without a body) and concrete methods (methods with a
body).
◦ An abstract method is declared with the abstract keyword and does not have an
implementation. Subclasses of an abstract class are responsible for providing
implementations for abstract methods.
2. Cannot Instantiate Abstract Classes:

◦ 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.

Java Interface also represents the IS-A relationship.

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

Java 8 & 9 interface Improvement :


Since Java 8, we can have default and static methods in an interface. Since Java 9, we can
have private methods in an interface.

Key Rules of Interfaces in Java

1. Method Signatures Only (No Method Bodies):


◦ By default, methods in interfaces are public and abstract, meaning they have
no body.
◦ Implementing classes must provide the method body.

2. No Instance Fields (Only Constants Allowed):


◦ Interfaces can only de ne constants, which are public, static, and final by
default.

3. Multiple Inheritance via Interfaces:


◦ Java does not support multiple inheritance with classes, but a class can implement
multiple interfaces.
fi
Ranjeet Kendre
4. Default and Static Methods:
◦ Since Java 8, interfaces can have default methods (with a method body),
allowing you to add new functionality to interfaces without breaking existing
implementations.
◦ static methods can also be de ned in interfaces.

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

Difference between/w abstract class and interface

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)

Difference between array and Array list

Array ArrayList/Collection

1.Array is static in size. 1. ArrayList is dynamic in size.


2. Array size is fixed 2. Size in not fixed
3.No underlying data structure used 3. Implemented using underlying DS

Difference b/w Collection and Collections

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

Hierarchy of Collection FrameworkR


Ranjeet Kendre
List Interface :

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.

Key Features of List Interface:

1. Order: Maintains the order of insertion.


2. Duplicates: Allows duplicate elements.
3. Index-Based Access: Provides methods to access, insert, or remove elements at a specific
index.
4. Null Elements: Permits null as an element (unless restricted by the implementation).

Implementations classes of List Interface:

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.

Key Features of ArrayList:

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;

public class ArrayList1 {

public static void main(String[] args) {

//Array

int arr[] = new int [10] ; //Static + similar data type

arr[0] = 50;
arr[9] = 80;

// System.out.println(arr);

//System.out.println(arr.length);

//Array List

ArrayList AL = new ArrayList(); //DS - 10 //Dynamic array +


non similar type data

ArrayList<Integer> AL1 = new ArrayList<Integer>(); //Static type +


simailar type data

//1.Add -- > to add or insert the element in arrayList

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));

//4.Contains - Returns true if rthe list conatins the specified


element

System.out.println(AL.contains(20)); //True
System.out.println(AL.contains(2000)); //false

System.out.println(AL.contains("Python"));

//5. Get EMthod Retrieve the element - charAt()


System.out.println(AL.get(7));
System.out.println(AL.get(2));

//6.Set - Replace or change the valaue


AL.set(2, "Ruby");
System.out.println(AL);

AL.set(3, 2000);
System.out.println(AL);

//7.IsEmpty
System.out.println(AL.isEmpty());
System.out.println(AL1.isEmpty());

//Read/print the data from given arraylist

//By using simple for loop

for(int i=0 ;i < AL.size() ;i++) {

System.out.println(AL.get(i));
}

//Advance for loop


System.out.println();
//2.
for(Object obj :AL) {
System.out.println(obj);
}

//Iterator
System.out.println();
Ranjeet Kendre
Iterator it = AL.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}

System.out.println();

Iterator obj = AL.iterator();

while(obj.hasNext()) {
System.out.println(obj.next());
}
}

Program 2

package List;

import java.util.ArrayList;
import java.util.Collections;

public class ArrayList2 {

public static void main(String[] args) {

ArrayList AL1 = new ArrayList(); //dynamic + heterogeneous type

AL1.add(400); //0
AL1.add("Java"); //1

ArrayList<Integer> AL2 = new ArrayList<Integer>(); //Static + Homo

AL2.add(33);
//AL2.add("Test");

for(int i=0 ;i<AL1.size();i++) {


System.out.println(AL1.get(i));
}

for(Object It :AL1) {
System.out.println(It);
}

ArrayList AL3 = new ArrayList();

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;

public class ArrayList3 {

public static void main(String[] args) {


// TODO Auto-geneated method stub

String arr[] = {"Test","Python","Java","Selenium"};

System.out.println(arr);

for(String Str : arr) {


System.out.println(Str);
}

//To convert array into arrayList

ArrayList AL = new ArrayList(Arrays.asList(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.

Key Features of LinkedList:


1. Doubly Linked List: Each element (node) contains references to both its previous and next
nodes.
2. Ef cient Insertions and Deletions: Adding or removing elements, especially at the
beginning or middle, is faster than ArrayList.
3. Maintains Insertion Order: Preserves the order in which elements are added.
4. Allows Duplicates and Nulls: Supports duplicate elements and can store null.
5. Implements Queue and Deque Interfaces: Can be used as a queue (FIFO) or deque
(Double-Ended Queue).

Program 1
package List;

import java.util.Iterator;
import java.util.LinkedList;

public class LinkedList1 {

public static void main(String[] args) {

LinkedList LL1 = new LinkedList();


LinkedList LL2 = new 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();

for(Object Obj : LL1) {


System.out.println(Obj);
}

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;

public class LinkedList2 {

public static void main(String[] args) {

//Create link list

LinkedList<String> fruits =new LinkedList<String>();

//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);

LinkedList LL1 = new LinkedList();

LL1.add("A");
LL1.add("BB");
LL1.add("R");
LL1.add("F");
LL1.add("E");

LinkedList LL2 = new LinkedList();

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.

Key Features of Vector:

1. Resizable Array: Automatically grows or shrinks as elements are added or removed.


2. Synchronized: All methods in Vector are synchronized, ensuring thread safety in multi-
threaded environments.
3. Maintains Insertion Order: Preserves the order in which elements are added.
4. Allows Duplicates: Duplicate elements are permitted.
5. Null Elements: Supports storing null values.
6. Legacy Class: Introduced in JDK 1.0, later retrofitted to implement the List interface.

Program 1
package List;

import java.util.Iterator;
import java.util.Vector;

public class Vector1 {

public static void main(String[] args) {

Vector V1 = new Vector(); //Default size = 10

//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');

int test = V1.capacity();

System.out.println(test);

V1.add('f');

int test1 = V1.capacity();

System.out.println(test1);

V1.add(1,55);
System.out.println(V1);

for(int i=0 ;i<V1.size();i++) {


System.out.println(V1.get(i));
Ranjeet Kendre
}

for(Object obj :V1) {


System.out.println(obj);
}

System.out.println();
Iterator it = V1.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}

Program 2

package List;

import java.util.Vector;

public class Vector2 {

public static void main(String[] args) {


// TODO Auto-generated method stub

Vector<String> colors = new Vector<String>();

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.

Key Features of the Set 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.

Key Features of HashSet

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.

Key Features of LinkedHashSet

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;

public class HashSet1 {

public static void main(String[] args) {

HashSet HS = new HashSet(); //AL DC = 10 ,16 Load


Factor Fillratio - 0.75

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);

//If ur trying to add duplicate element it will return


false

HashSet <String> HS1 = new HashSet<String>();

HS1.add("Apple");
HS1.add("Banana");
HS1.add("Cherry");
HS1.add("Apple");

System.out.println(HS1);

//check t=if an element exists

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);

// for(int i=0 ;i<HS2.size();i++) {


// System.out.println(HS2.ge);
// }

for(Integer num :HS2) {

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;

public class HashSet2 {

public static void main(String[] args) {

//Converting HasSet to Array;

HashSet<String> Cities = new HashSet<String>(); //16 -


LF - 0.75

Cities.add("Pune");
Cities.add("Mumbai");
Cities.add("London");
Cities.add("Tokyo");

System.out.println(Cities);

//Converting hashset to array


Ranjeet Kendre

String [] cityarray = Cities.toArray(new String[1]);

System.out.println(cityarray);

for(String Str :cityarray) {


System.out.println(Str);
}

Program 3

package SetInterface;

import java.util.HashSet;

public class HashSet3 {

public static void main(String[] args) {

//default initial capacity (16) and load factor (0.90).


HashSet HS1 = new HashSet(100, 0.90f); //100

HS1.add(1);
HS1.add(2);
HS1.add(3);
HS1.add(44);
HS1.add(33);

HashSet HS2 = new HashSet(100, 0.90f); //16

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;

public class LinkedHashSet1 {

public static void main(String[] args) {

LinkedHashSet <String>LHS = new LinkedHashSet<String>();

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());

for(String str : LHS) {


System.out.println(str);
}

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;

public class TreeSet1 {

public static void main(String[] args) {

TreeSet<Integer> numbers = new TreeSet<Integer>();


numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
numbers.add(10);

TreeSet<String> names = new TreeSet<String>();


names.add("David");
names.add("Rahul");
names.add("Rohit");

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());

for(String str :names) {


System.out.println(str);
}
Iterator it = names.iterator();
while(it.hasNext()) {
System.out.println(it.next());

}
}

}
Ranjeet Kendre
Difference between List and Set

List Set

1. Duplicate are allowed 1.Duplicate are not allowed


2.Insertion order preserved 2.Insertion order is not preserved
3.Multiple null element can be stored 3.Null Element can store only once
4.Element by their position can be access 4.Element by their position can not be access
5. List implementations classes are 5. Set implementations classes are HashSet,
ArrayList, Linked List,Vector Linked HashSet,TreeSet
Ranjeet Kendre
Queue in Java Collection Framework

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.

The Queue interface is implemented by various classes like:

• LinkedList
• PriorityQueue
• ArrayDeque

Key Features of Queue

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;

public class LinkedListQueue {

public static void main(String[] args) {

Queue<String> queue = new LinkedList<String>();

//Add element to the quque

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;

public class Pqueue1 {

public static void main(String[] args) {

PriorityQueue PO = new PriorityQueue();


PriorityQueue PO1 = new 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

for(Object obj :PO) {


System.out.println(obj);
}

}
}
Ranjeet Kendre
Important collection question

1) What is the Collection framework in Java?

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.

2) What are the main differences between array and collection?

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.

3) Explain various interfaces used in Collection framework?

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:

1. Collection interface: Collection (java.util.Collection) is the primary interface, and every


collection must implement this interface.
2. List interface: List interface extends the Collection interface, and it is an ordered collection
of objects. It contains duplicate elements. It also allows random access of elements.

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).

4. Dequeue interface: it is a double-ended-queue. It allows the insertion and removal of


elements from both ends. It implants the properties of both Stack and queue so it can perform
LIFO (Last in first out) stack and FIFO (first in first out) queue, operations.

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.

5) What is the default size of load factor in hashing based collection?

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.

6. What is the difference between Array and ArrayList?

7) How to convert ArrayList to Array and Array to ArrayList?


We can convert an Array to ArrayList by using the asList() method of Arrays class. asList()
method is the static method of Arrays class and accepts the List object. Consider the following
syntax:

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()])

8.How to reverse ArrayList?

To reverse an ArrayList, we can use reverse() method of Collections class. Consider the
following example.

9.When to use ArrayList and LinkedList?

LinkedLists are better to use for the update operations whereas ArrayLists are better to use for
the search operations.

10. What is the hashCode()?


Ranjeet Kendre
The hashCode() is a method that returns an integer hash code.

12. Mention the implementing List and Set interface


Class implementing List interface: 1) ArrayList, 2) Vector, and 3) LinkedList. Class
implementing Set interface: 1) HashSet, and 2) TreeSet.

13. What is Iterator()


The Iterator() is an interface that provides methods to iterate Collection. Iterator can take the
place of Enumeration in Java. It allows the caller to remove elements from the collection. The
method provides a generic way for traversal using elements of the collection and
implementing iterator design pattern.

14) What is the difference between Iterator and ListIterator?

15) What is the difference between Iterator and Enumeration?

16) What is the difference between ArrayList and LinkedList?





Ranjeet Kendre
Ranjeet Kendre
Arrays important interview question

1. What is an Array in Java?


• Answer: An array in Java is a collection of elements of the same data type, stored in
contiguous memory locations. Arrays are fixed in size and can hold primitive types or
objects. They are zero-indexed, meaning the first element has an index of 0. Arrays provide
constant-time access to elements, making them efficient for storing and accessing a
collection of data of the same type.

2. How do you declare and initialize an array in Java?


Answer: Arrays can be declared and initialized in several ways:
int[] numbers; // Preferred syntax
int numbers[]; // Alternative syntax

int[] numbers = new int[5]; // An array of integers with 5 elements


int[] numbers = {1, 2, 3, 4, 5}; // Declaration and initialization with values

3.What is the difference between a one-dimensional and a multi-dimensional array?


One-dimensional array: An array with a single row of elements.
int[] singleArray = {1, 2, 3};

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}
};

4.What are some limitations of arrays in Java?


Answer:
• Fixed size: Once an array is created, its size cannot be changed.
• Homogeneous data: All elements must be of the same type.
• No built-in methods for common operations: Arrays lack built-in methods for operations
like searching, sorting, or resizing. For such operations, you need to use java.util.Arrays or
java.util.Collections.

5.How can you sort an array in Java?


• Answer: You can sort an array using the Arrays.sort() method. This sorts the array in
ascending order by default.
int[] numbers = {5, 3, 8, 1};
Arrays.sort(numbers); // numbers is now {1, 3, 5, 8}

6 Can we store null values in an array in Java?


• Answer: Yes, an array of reference types (e.g., String[], Integer[]) can hold null values.
Primitive type arrays (int[], double[]) cannot hold null since they store actual values.
Ranjeet Kendre
7.How do you convert an array to a List in Java?
• Answer: You can use Arrays.asList() to convert an array to a List. Note that this list is
backed by the array, so changes to the array will reflect in the list and vice versa.
String[] array = {"A", "B", "C"};
List<String> list = Arrays.asList(array);

8. Can you store different data types in a single array?


• Answer: No, arrays in Java are homogenous, meaning they can only store elements of the
same data type. However, if you declare an array of type Object, you can store any type of
object in it, as all classes in Java are subclasses of Object. But this is not generally
recommended due to type safety issues.

9.How do you convert an ArrayList to an array in Java?


Answer: You can convert an ArrayList to an array using the toArray() method.
ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
String[] array = list.toArray(new String[0]);

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.

2.How can you create a String in Java?


• Answer: You can create a String in Java in two ways:
◦ Using string literals: "Hello"
◦ Using the new keyword: new String("Hello") When using a literal, Java checks the
string pool for existing objects to reuse memory. Using new always creates a new
String object in the heap memory, regardless of the string pool.

3.What is the Java String pool, and why is it important?


• Answer: The String pool (also known as the interned pool) is a special memory area in Java
where string literals are stored. When you create a string literal, Java first checks if the same
literal is already in the pool. If it is, it returns the reference to that literal instead of creating a
new object, optimizing memory usage.

4.How do you compare two Strings in Java?


• Answer:
◦ Using ==: Compares memory references, so it returns true only if both variables
point to the same memory location.
◦ Using equals(): Compares the contents of two String objects for equality, returning
true if the content matches.
◦ Using compareTo(): Used for lexicographical comparison. It returns 0 if strings are
equal, a negative integer if the first string is lexicographically less, and a positive
integer if greater.

5.Explain immutability in Strings and its advantages.


Answer: In Java, String is immutable, meaning that once a String object is created, it cannot be
changed. If a String operation appears to change it, a new object is created instead.
• Advantages:
◦ Thread Safety: Strings can be shared across threads without synchronization.
◦ Caching in the String Pool: Reusability in memory.
◦ Security: Immutable objects are less susceptible to tampering, especially for
sensitive data.

6.What is StringBuilder and StringBuffer, and why are they used?


• Answer: StringBuilder and StringBuffer are used for mutable strings.
◦ StringBuilder: Faster, not synchronized, and best for single-threaded environments.
◦ StringBuffer: Synchronized and thread-safe, making it slower but suitable for multi-
threaded contexts.
Ranjeet Kendre
7.How do you remove whitespaces from a String in Java?
• Answer: Use trim() to remove leading and trailing whitespace, or use replaceAll() with a
regex to remove all whitespace:
String str = " Hello World ";
str = str.trim(); // Removes leading and trailing whitespace
str = str.replaceAll("\\s+", ""); // Removes all whitespace

8. Explain the difference between String.contains() and String.indexOf().


• Answer:
◦ contains(): Returns true if the string contains the specified sequence of characters.
◦ indexOf(): Returns the index of the first occurrence of the specified character or
substring; returns -1 if not found.

9.How do you convert a String to an integer in Java?

Answer: Use Integer.parseInt() or Integer.valueOf()


String str = "123";
int number = Integer.parseInt(str);

10.Why is String immutable in Java? Explain its implications.


• Answer: The String class is immutable for several reasons:
◦ Security: Many Java classes use strings for security-sensitive operations, such as
network connections, user authentication, and file handling. Immutability prevents
strings from being altered once they're used, ensuring consistency.
◦ String Pool Efficiency: Immutability allows sharing instances from the string pool,
reducing memory overhead.
◦ Thread Safety: Immutability makes strings inherently thread-safe, so multiple
threads can share string instances without synchronization issues.

11.What is the difference between String.replace() and String.replaceAll()?


Answer:
• replace(): Replaces all occurrences of a literal sequence of characters or a specific character,
treating inputs as literal.
• replaceAll(): Replaces all substrings that match a regular expression.

String str = "Java123";


str.replace("123", "456"); // "Java456"
str.replaceAll("\\d", "X"); // "JavaXXX" (replaces all digits)

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.

3.What is the difference between error and exception in Java?


Errors are mainly caused by the environment in which an application is running. For example,
OutOfMemoryError happens when JVM runs out of memory. Where as exceptions are
mainly caused by the application itself. For example, NullPointerException occurs when an
application tries to access null object.

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.

7.what are checked and unchecked exceptions in java?


Checked exceptions are the exceptions which are known to compiler. These exceptions are checked
at compile time only. Hence the name checked exceptions. These exceptions are also called compile
time exceptions. Because, these exceptions will be known during compile time. Unchecked
exceptions are those exceptions which are not at all known to compiler. These exceptions occur
only at run time. These exceptions are also called as run time exceptions. All sub classes of
java.lang.RunTimeException and java.lang.Error are unchecked exceptions.

8) What is the use of printStackTrace() method?


printStackTrace() method is used to print the detailed information about the exception occurred.
Ranjeet Kendre
9) Give some examples to checked exceptions?
ClassNotFoundException, SQLException, IOException

10) Give some examples to unchecked exceptions?


NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException

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

12.What is the difference between checked and unchecked exceptions?


• Answer:
◦ Checked Exceptions: These are exceptions that are checked at compile-time. They
must be either caught in a try-catch block or declared in the method signature with
throws. Examples include IOException, SQLException.
◦ Unchecked Exceptions: These are exceptions that occur at runtime and are not
checked at compile-time. They do not need to be declared or caught. Examples
include NullPointerException, ArithmeticException.

13.Explain the difference between final, finally, and finalize.


• Answer:
◦ final: A keyword used to declare constants, prevent method overriding, and prevent
inheritance.
◦ finally: A block used in exception handling to execute code regardless of whether an
exception is thrown or not.
◦ finalize: A method in the Object class that is called by the garbage collector before an
object is removed from memory. It can be overridden to release resources, but its use
is generally discouraged in favor of try-with-resources.

14.How can you create a finally block without a try or catch?


• Answer: It’s not possible to have a finally block without a try or catch block directly. finally
always needs a preceding try block to execute.
Ranjeet Kendre
15.What happens if System.exit() is called in a try or catch block? Will finally still execute?
• Answer: If System.exit() is called in a try or catch block, the JVM terminates immediately,
and the finally block does not execute. System.exit() is one of the few cases that prevent
finally from executing.

16.What is the NoClassDefFoundError, and how does it differ fromClassNotFoundException?


• Answer:
◦ NoClassDefFoundError: This error occurs when a class that was available at
compile-time cannot be found at runtime due to missing dependencies.
◦ ClassNotFoundException: This checked exception occurs when an application tries
to load a class using Class.forName() or ClassLoader and the class cannot be found.

17.Can a method have a return type even if it throws an exception?


Answer: Yes, a method can still declare a return type even if it throws an exception. However, if an
exception is thrown before reaching a return statement, the method won’t return any value. The
exception will cause the method to exit immediately, and any return statement after the exception
will not execute.

public int exampleMethod() throws Exception {


if (someCondition) {
throw new Exception("An error occurred");
}
return 42; // This return statement is skipped if the exception is thrown
}

18.Can you return a value from a catch block?


• Answer: Yes, you can return a value from a catch block. If an exception is thrown in the try
block, the catch block can handle the exception and provide an alternative return value.

public int safeDivision(int a, int b) {


try {
return a / b;
} catch (ArithmeticException e) {
System.out.println("Division by zero! Returning default value.");
return 0; // Return a default value if an exception occurs
}
}

19.Can a method with a void return type throw an exception?


• Answer: Yes, a method with a void return type can throw an exception. It simply does not
return any value but may still exit due to an exception

public void riskyOperation() throws Exception {


if (someRiskCondition) {
throw new Exception("Operation failed");
}
// No return statement needed
Ranjeet Kendre
}

20.Can a method with a non-void return type have no return statement?


• Answer: Yes, if every possible code path in the method either throws an exception or calls
another method that doesn’t return. In such cases, the method can technically avoid having a
return statement since an exception is guaranteed to terminate the method.

public int riskyComputation(int x) throws Exception {


if (x < 0) {
throw new Exception("Negative input not allowed");
}
throw new Exception("Computation not supported yet");
}

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

1. What are the eight primitive data types in Java?

Java has eight primitive data types


1. byte - 1 byte
2. short. - 2 byte
3. int - 4 byte
4. long - 8 byte
5. float - 8 byte
6. double. - 8 byte
7. char - 2 byte
8. boolean. - 1 bit

2.Difference between primitive and non primitive data type in java

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

4.How to Call a Static Method in Java?


We can call a static method using the class name followed by a dot and the method name.

5.How to Call a Static Method in Java?


To call a non-static method in Java, you need to first create an instance (or object) of the
class that contains the method. Non-static methods belong to instances of the class, so you
must create an object to access them.

6.Can we call static method using object reference name in java

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).

9.What are the different types of loops in programming?


Answer: The most common loops are:
for loop: Used when you know the number of iterations in advance.
while loop: Used when the number of iterations is not known, and you want to repeat as
long as a condition is true.
do-while loop: Similar to while, but guarantees at least one iteration.

10.What is a local variable?


• Answer: A local variable is declared inside a method, constructor, or block and can
only be accessed within that method or block.

11.What is a static variable?


• Answer: A static variable (also called a class variable) is shared among all instances
of the class. It is declared using the static keyword.

11.Can a local variable be static?


• Answer: No, local variables cannot be declared as static because static variables are
associated with the class and local variables are associated with methods, which have
different scopes. Static variables exist for the entire lifetime of the class, while local
variables exist only during the execution of the method.

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)

13.What is the difference between class and object


Class:
• A class is a blueprint or a template that defines the structure and behavior (methods
and fields) of objects.
• It represents a generic concept or category, but it doesn’t hold any actual data or
perform any actions until instantiated.
• A class defines the properties (fields) and behaviors (methods) that its objects will
have.
• It can be thought of as a blueprint for creating multiple objects with similar
characteristics.
Object:
• An object is an instance of a class. It is a real-world entity that has states (attributes)
and behaviors.
• Objects hold actual data in the fields defined by the class and can perform the
methods defined by the class.
• Each object has its own copy of the attributes, but it shares the class definition.
• Objects are created using the new keyword in most OOP languages like Java.

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.

14.What is a constructor in Java?


• A constructor in Java is a special method that is called when an object of a class is
created. It is used to initialize the object's state (i.e., assigning values to the fields).
The constructor has the same name as the class and does not have a return type.

15.What are the types of constructors in Java?


• Default Constructor: A constructor with no parameters, which is automatically
provided by Java if no other constructors are defined.
• Parameterized Constructor: A constructor that takes arguments to initialize an
object with specific values.

16.Can a constructor be final, static, abstract, or synchronized in Java?


• Final: No, constructors cannot be declared final because they cannot be inherited or
overridden.
• Static: No, constructors cannot be static because they are called during object
creation, and static methods belong to the class rather than instances.
• Abstract: No, constructors cannot be abstract because abstract methods are meant to
be overridden in subclasses, while constructors are tied to object creation.
• Synchronized: No, constructors cannot be synchronized because only methods can
be synchronized, and constructors are not inherited.

17.What is the difference between a constructor and a method?


• Constructor:
◦ Used for initializing objects.
◦ Has the same name as the class.
◦ No return type, not even void.
◦ Called automatically when an object is created.

• 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.

18.Can a constructor call another constructor of the same class?


• Yes, a constructor can call another constructor of the same class using the this()
keyword. This is called constructor chaining within the same class.
fi
fi
fi
Ranjeet Kendre
19. Can a constructor call the constructor of the superclass?
• Yes, a constructor can call the constructor of the superclass using the super()
keyword. This is typically done to initialize the superclass fields or execute superclass
initialization logic.

20.What happens if a constructor is private?


• A private constructor restricts the instantiation of a class from outside the class.
This is useful in implementing singleton patterns or factory methods.

21.Can you overload constructors in Java?


• Yes, constructors can be overloaded in Java by defining multiple constructors with
different parameter lists (number, type, or order of parameters).

22.What is the purpose of the this() keyword in constructor overloading?


• The this() keyword is used to call another constructor within the same class. It helps
avoid duplication of code and improves constructor chaining.

23.What is the role of the default constructor if a parameterized constructor is defined?


• If you define a parameterized constructor, Java does not provide a default
constructor. If you still need a no-argument constructor, you must explicitly define
it.

24.Can constructors throw exceptions?


• Yes, constructors can throw exceptions, just like methods. If a constructor throws an
exception, it must declare it using the throws keyword.

25.What will be the access modifier of the default constructor?


• The access modifier of the default constructor depends on the class modifier. If no
constructor is defined, Java provides a default constructor with the same access
modifier as the class.
◦ For a public class, the default constructor will be public.
◦ For a package-private class (no modifier), the default constructor will have
package-private access.

26.Who provides the default constructor?


• Java's compiler provides the default constructor automatically when no other
constructors (neither default nor parameterized) are explicitly defined in the class. It
initializes fields with default values (e.g., 0 for integers, null for objects).

27.What is inheritance in Java?


• Inheritance is a mechanism in object-oriented programming where one class (child/
subclass) acquires the properties and behaviors (fields and methods) of another class
(parent/superclass). Inheritance allows for code reuse and establishes a natural
hierarchy between classes.
Ranjeet Kendre
28.What are the types of inheritance in Java?
• Single Inheritance: A class inherits from only one parent class.
• Multilevel Inheritance: A class inherits from a parent class, and then another class
inherits from that subclass.
• Hierarchical Inheritance: Multiple classes inherit from a single parent class.
• Multiple inheritance :a class inheriting from more than one class
• Hybrid inheritance
Note: Java does not support multiple and hybrid inheritance (a class inheriting from
more than one class) directly to avoid ambiguity (commonly known as the diamond
problem). However, multiple inheritance is supported through interfaces.

29.Can a class extend multiple classes in Java?


• No, a class in Java cannot extend more than one class. Java only allows single
inheritance with classes to avoid ambiguity. However, a class can implement
multiple interfaces.

30.What is multilevel inheritance in Java?


• Multilevel inheritance is when a class is derived from a class that is also derived
from another class. In other words, there is a hierarchy of inheritance involving more
than one level.

30.What is the advantage of inheritance in Java?


• Code Reusability: You can reuse fields and methods of the existing class.
• Method Overriding: Inheritance allows you to override the methods of the parent
class to define specific behavior in the child class.
• Polymorphism: Through inheritance, polymorphism can be achieved, which allows a
subclass object to be treated as an instance of the parent class.

31.Can constructors be inherited in Java?


• No, constructors cannot be inherited in Java. However, a subclass constructor can call
the constructor of its parent class using the super() keyword.

33.What is hierarchical inheritance in Java?


• Hierarchical inheritance is when multiple classes inherit from a single parent class.

34.What are access specifiers in Java?


• Access specifiers (or access modifiers) in Java determine the visibility and
accessibility of classes, methods, and variables. They control how these components
can be accessed from other classes and packages.

35.What are the types of access specifiers in Java?


• There are four main types of access specifiers in Java:
1. Public: The member is accessible from any other class.
2. Private: The member is accessible only within its own class.
Ranjeet Kendre
3. Protected: The member is accessible within its own package and by
subclasses (even if they are in different packages).
4. Default (no modifier): If no access specifier is provided, the member is
accessible only within its own package.

36.What is the public access specifier.


• Members declared as public can be accessed from any other class in any package.
This is the least restrictive access level.
37.What is the private access specifier.
• Members declared as private can only be accessed within the same class. They are not
visible to any other class, even subclasses.

38.What is the protected access specifier.


• Members declared as protected can be accessed within the same package and by
subclasses, even if they are in different packages.

39.What is the default access specifier?


• If no access specifier is provided, the member has default access. Members with
default access are accessible only within classes in the same package.

40.Can you access private members of a class from a subclass?


• No, private members cannot be accessed directly from a subclass. They are only
accessible within the class in which they are declared.

41.Can protected members be accessed outside the package?


• Protected members can be accessed outside the package only through inheritance (i.e.,
by subclasses). They cannot be accessed by other classes in a different package that
do not inherit from the parent class.

42.Can access specifiers be applied to constructors?


• Yes, constructors can have any of the access specifiers (public, private, protected, or
default). The access level of the constructor determines how and where instances of
the class can be created.

43.Can you change the access level of a method in a subclass?


• Yes, you can change the access level of a method in a subclass, but it cannot be made
more restrictive than the access level in the superclass. For example, if a method in
the superclass is protected, you can change it to public, but not to private.
Ranjeet Kendre
Polymorphism Interview Questions and Answers

1. What is Polymorphism in Java OOPs?

Ans: Polymorphism in java is one of the core concepts of object-oriented programming


system. Polymorphism means “many forms” in Greek. That is one thing that can take many
forms.

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.

2. What are the types of Polymorphism in Java?

Ans: There are two types of polymorphism in java.


▪ Compile time Polymorphism
▪ Runtime Polymorphism

3. How is Inheritance useful to achieve Polymorphism in Java?


Ans: Inheritance represents the parent-child relationship between two classes and
polymorphism take the advantage of that relationship to add dynamic behavior in the code (or
to make the program more dynamic).
4. What are the advantages of Polymorphism?
Or what is the use of polymorphism?
Ans: There are the following advantages of polymorphism in java:
a. Using polymorphism, we can achieve flexibility in our code because we can perform
various operations by using methods with the same names according to requirements.
b. The main benefit of using polymorphism is when we can provide implementation to an
abstract base class or an interface.
5. What are the differences between Polymorphism and Inheritance in Java?
Ans: The differences between polymorphism and inheritance in java are as follows:

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.

6.What is Compile time polymorphism (Static polymorphism)?

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.

8. What is Binding in Java?

Ans: The connecting (linking) between a method call and method definition and method
declaration is called binding

9. What are the types of binding in Java?

Ans: There are two types of binding in java. They are as follows:

a. Static Binding (also known as Early Binding).


b. Dynamic Binding (also known as Late Binding).

10. What is Static binding in Java?

Ans: The binding that happens during compilation is called static binding in java. This binding
is resolved at the compiled time by the compiler.

11. How Java compiler performs static binding?

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.

12. Why static binding is also called early binding in Java?

Ans: Static binding is also called early binding because it takes place before the program
actually runs.

13. Give an example of static binding.

Ans: An example of static binding is method overloading.

14. What is Dynamic binding in Java?

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.

15. How JVM performs dynamic binding in Java?

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.

16. Why Dynamic binding is also called late binding in java?


Ans: Dynamic binding is also called late binding or runtime binding because binding occurs
during runtime.

17. Give an example of dynamic binding in Java.

Ans: An example of dynamic binding is method overriding.

18.Can we overload the static method

Yes

19. Can we override the static method

No

20 .Can we override the private method

Yes

21.Can we override the private method

No

22.Can return type be different in overloading?

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

straight forward as there are some cases involved in this.

23. Can overridden methods have different return types?

Case 1: If the return type is a primitive data type or void.

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

Case 2: If the return type is derived/non-primitive data type:

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.

25.What is the difference between Method Hiding and Method overriding.




Ranjeet Kendre
Java Inheritance Interview Questions & Answers

1. What is Inheritance in Java?

Inheritance is a process where a One class acquires property of another class with the help of
extends keywords is known as inheritance.

2. Why do we need to use 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.

There are the following reasons to use inheritance in java.

▪ We can reuse the code from the base class.


▪ Using inheritance, we can increase features of class or method by overriding. ▪ Inheritance is used
to use the existing features of class.
▪ It is used to achieve runtime polymorphism i.e method overriding.

3. What are the types of inheritance in Java?

Ans: The various types of inheritance are as follows:

a. Single inheritance
b. Multi-level inheritance c. Hierarchical inheritance d. Multiple inheritance
e. Hybrid inheritance

4. What is Is-A relationship in Java?

Ans: Is-A relationship represents Inheritance. It is implemented using the “extends” keyword. It is
used for code reusability.

5. What is super class and subclass?

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.

6. How is Inheritance implemented/achieved in Java?

Ans: Inheritance can be implemented or achieved by using two keywords:

extends: extends is a keyword that is used for developing the inheritance between two classes and
two interfaces.

7. Which class in Java is superclass of every other class?

Ans: In Java, Object class is the superclass of every other class.


Ranjeet Kendre
8.Can a class extend more than one class?

Ans: No, one class can extend only a single class.

9. Are static members inherited to subclass in Java?

Ans: Static block cannot be inherited to its subclass.

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.

10. Can we extend (inherit) nal class?

Ans: No, a class declared with final keyword cannot be inherited.

11. Can a nal method be overridden?

Ans: No, a final method cannot be overridden.

12. Can we inherit private members of base class to its subclass?

Ans: No.

13. Which keyword do you use to de ne a subclass?

Or, which keyword is used to inherit a class? Ans: extends keyword.

14. What are the advantages of inheritance in Java?

Ans: The advantages of inheritance in java are as follows:

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.

Inheritance can also make application code more flexible to change.

15. Why multiple inheritance is not supported in java through class?

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.

16. What is single inheritance and multi-level inheritance?

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.

17. What is Multiple inheritance in Java?

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.

18. How does Multiple inheritance implement in Java?

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.

21. Can we access subclass members if we create an object of superclass?

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?

Ans: Yes, we can access both superclass and subclass members.

23. What happens if both superclass and subclass have a eld with the same name?

Ans: Only subclass members are accessible if an object of subclass is instantiated.

33. Is interface inherited from the Object class?

Ans: No.
fi

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy