0% found this document useful (0 votes)
2 views38 pages

Java Document

Its Java documents for QA Professionals, it has complete guide and explanations. it is complete explanation with examples,

Uploaded by

siddeshbasanna
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)
2 views38 pages

Java Document

Its Java documents for QA Professionals, it has complete guide and explanations. it is complete explanation with examples,

Uploaded by

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

Java Basics

What is Java:
Java is a high-level, object-oriented programming language known for its platform
independence, meaning code written once can run anywhere with a Java Virtual Machine (JVM).
Java is an object-oriented programming (OOP) language because everything in java is an object,
means it is built around the concept of objects-entities that contains data (fields) and
behaviour (methods). An object represents any entity with both state (such as properties or
variables) and behavior (such as methods or functions).
Java is called platform independent because programs written in Java can run on any operating
system (Windows, Linux, macOS, etc.) without modification. Means the syntax is same for all OS,
this is achieved through the Java Virtual Machine (JVM).
• Java source code (.java) is compiled into bytecode (.class files).
• Bytecode is not tied to any specific operating system or hardware

JVM (Java Virtual Machine) is platform dependent:


• Each operating system (Windows, Linux, macOS, etc.) has its own implementation of the JVM.
• The JVM must translate bytecode into native machine instructions that the underlying OS
and hardware understand.
• So, while the bytecode is the same everywhere, the JVM itself is customized for each platform.
• Java Compiler (javac) → Converts .java source code into .class bytecode.
• Bytecode → Platform independent, same everywhere.
• JVM → Platform dependent, because it’s the bridge that converts bytecode into native code
for the specific OS.
• Java is platform independent.
• JVM is platform dependent.

Difference between JDK, JRE, and JVM


• JVM (Java Virtual Machine) –
- It is a virtual machine, does not physically exist.
- Converts Java bytecode into machine specific code for execution. And it is platform dependent.
• JRE (Java Runtime Environment) –
- Includes JVM + Java libraries to run Java programs (no compiler).
- It provides the necessary environment setup to run Java applications.
• JDK (Java Development Kit) –
- It is a software development kit used by developers to write, compile, and debug Java
programs.
- It includes the JRE (Java Runtime Environment) and development tools like the compiler
(javac), debugger, and other utilities.
- The JDK is platform-dependent. It is primarily used for development purposes and is not
required for running Java applications.

Variables
Variable is a container which can hold data, to represent data we need variables.
Local Variable Global or Instance Variable Static Variable
Declared and initialized inside the body of Declared inside the class but outside of Declared using a “static”
the method, block, or constructor. the method, block or constructor. If not keyword. It cannot be local.
initialized, the default value is 0.
It has access only within the method in Variables are created when an instance Variables are created to
which it is declared and is destroyed later of the class is created and destroyed create a single copy in the
from the block or when the function call is when it is destroyed. memory shared among all
returned. objects at a class level.

1
class TestVariables
{
int data = 20; // instance variable
static int number = 10; //static variable
void someMethod()
{
int num = 30; //local variable
}
}

Data Types:
Primitive: byte, short, int, long, float, double, char, Boolean.
Non-primitive: String, Arrays, Classes,

Primitive vs Non primitive (reference) data types


Primitive Non-Primitive
Stores only one type of data Stores multiple data types of data
Primitive data types start with lower case Starts with uppercase letter
Ex: byte, short, int, char, Boolean Ex: Array List, HashMap
Fixed size Flexible
Used for simple data structure Used for complex data structure
These data types immutable by default Can be mutable or immutable depending on the
object (ArrayList, String etc.…)
Data types doesn’t supports null values supports null values

Operators:
Java operators are special symbols that perform operations on variables/values.
• Arithmetic: +, -, *, /, %
• Relational/Comparision: ==, !=, >, <, >=, <=
• Logical: &&, ||, !
• Assignment: =, +=, -=
• Increment/Decrement: ++, --

Java Keywords:
Java keywords are also known as reserved words. Keywords are particular words that act as
a key to a code. These are predefined words by Java so we cannot be used as a variable or
object name or class name.

Java Control Statements | Control Flow in Java


Java provides three types of control flow statements.
1. Decision Making / conditional statements
o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement

2
Conditional Statements in Java.
1. conditional statements:
ifStatement:
The ifstatement is used to execute a block of code if a specified condition is true.
Syntax:
if (condition)
{
// Code to execute if the condition is true
}

Example1:
int x = 20;
int y = 18;
if (x > y) {
[Link]("x is greater than y");
}
Output: “x is greater than y”.

Example 2:
int person_age=25;
if(person_age>=18);
{
[Link]("eligible for vote");
}
Output: eligible for vote.

if...else Statement:
The elsestatement is used to execute a block of code if the condition specified in the ifstatement
is false.
Syntax:
if (condition)
{ (No semicolon)
// Code to execute if the condition is true
}
else
{ (No semicolon)
// Code to execute if the condition is false
}
Example 1:
int time = 20;
if (time < 18) {
[Link]("Good day.");
}
else {
[Link]("Good evening.");
}

Example 2:
int person_age=15;
if(person_age>=18)
{
[Link]("eligible for vote"); //eligible for vote
}
else {
[Link]("Not eligible for vote"); //Not eligible for vote
}
Output: Not eligible for vote.

Example:
// if else condition -- even or odd
int num=15;

3
if(num%2==0)
{
[Link]("even number"); //even number for int =10;
}
else
{
[Link]("odd number"); //odd number for int =15;
}
Output: odd number

else if Statement:
The else ifstatement allows you to specify a new condition to test if the first condition
in the if statement is false.
Syntax:
if (condition1) {
// Code to execute if condition1 is true
}
else if (condition2) {
// Code to execute if condition1 is false and condition2 is true
} else {
// Code to execute if both condition1 and condition2 are false
}
Example 2:
// if else condition -- check number positive, negative or zero
int num=-10;
if(num>0) {
[Link]("posive number"); //posive number, if num = 4 or 5 etc.
}
else if(num<0) {
[Link]("negative number"); //negative number if num= -10, etc..
}
else {
[Link]("zero"); //zero if num = 0.
}
Output: Negative number
Example 3:
// if else condition -- largest of 3 numbers
/* a>b and a>c --- a is largest
* b>a and b>c --- b is largest
* c>a and c>b --- c is largest
int a=-100,
b=50,
c=30;
if(a>b && a>c)
{
[Link]("a is largest number");
}
else if(b>a && b>c)
{
[Link]("b is largest number"); //b is largest number if a=-100, b=50, c=30.
}
else
{
[Link]("c is largest number"); //c is largest number if a=10, b=20,c=30.
}
Output: B is larger number

Example 3:
// multiple statements
if(true)
{
[Link](1); ////1 if condition is true

4
}
else
{
[Link](2); //2 if condition is false
}
Output: 2

nested if-else statements allow us to check multiple conditions and perform different actions
based on those conditions. Let’s explore how they work with some examples:

Basic Nested If-Else:


o In a nested if-else structure, an inner if block is contained within an outer if or else block.
o The inner if block is executed only when the outer if condition is true.
Example:
public class JavaDemo
{
public static void main(String[] args) {
int a = 10;
int b = 20;
if (a == 10) {
if (b == 20) {
[Link]("GeeksforGeeks");
}
}
}
}
Explanation:
o In the first example, both conditions (a == 10 and b == 20) are true, so the inner if block is
executed, resulting in the output “GeeksforGeeks.”
o In the second example, the inner if condition (b != 20) is false, so the else part is executed,
resulting in the output “GFG.”
Remember that you can nest if statements inside each other to handle more complex scenarios. Feel
free to experiment and create deeper levels of nesting as needed!

2. Nested If-Else with an else Block:


o You can also include an else block within the nested structure.
o Example:
public class NestedIfElseExample {
public static void main(String[] args) {
int a = 10;
int b = 20;
if (a == 10)
{
if (b! = 20)
{
[Link]("GeeksforGeeks");
}
else {
[Link]("GFG");
}
}
}
}

Example 2
//Display week names based on week number
public class JavaDemo
{
public static void main(String[] args) {
if(weekno==1) {
[Link]("monday");

5
}
else if(weekno==2) {
[Link]("Tuesday");
}
else if(weekno==3) {
[Link]("Wednesday");
}
else if(weekno==4) {
[Link]("Thursday");
}
else if(weekno==5) {
[Link]("Friday");
}
else if(weekno==6) {
[Link]("Saturday");
}
else {
[Link]("Invalid week");
}
Output: Monday

4. switch Statement (not covered in the snippet):


a. The switch statement allows you to specify many alternative blocks of code
to be executed based on different values of an expression.
Remember to use these conditional statements wisely to create efficient and logical program
flows in your Java code!
Example 2
//Display week names based on week number
int weekno=1;
switch(weekno)
{
case 1: [Link]("Sunday"); break; //Sunday displayed if week no 1
case 2: [Link]("Monday"); break;
case 3: [Link]("Tuesday"); break;
case 4: [Link]("Wednesday"); break;
case 5: [Link]("Thursday"); break;
case 6: [Link]("Friday"); break;
case 7: [Link]("Saturday"); break;
default: [Link]("Invalid week"); break;
}
Output: Sunday

What is the difference between if-else and switch-case?


• if-else: Best for range-based or complex conditions.
• switch-case: Best for fixed value checks.

2. What are Loops in Java, and how are they used?


Loops repeat actions until a condition is met.
• for loop – Known iterations (Initialisation, condition and increment are in a single line)
• while loop – Runs while condition is true (condition, statement and increment)
• do-while loop – Runs at least once
Java provides three primary loop constructs to execute a block of code repeatedly based on a
condition: for, while, and do-while loops. Each serves different use cases depending on the
scenario.
1. For Loop
The for loop is ideal when the number of iterations is known beforehand. It combines initialization,
condition, and increment/decrement in a single line.

6
Syntax:
for (initialization; condition; increment/decrement)
{
//Statement(s)
}

Key Points:
• Initialization happens once at the start.
• The condition is checked before each iteration.
• The loop terminates when the condition becomes false.
for (int i = 0; i <= 10; i++)
{
[Link](i);
}
Output: 0 to 10 numbers displayed

for(int i=2;i<=10;i++)
{
if(i%2==0)
{
[Link](i+"even");
}
else
{
[Link](i+"odd");
}
}
1odd
2even
3odd
4even
5odd
6even
7odd
8even
9odd
10even

Example 3: // 1 ....10 descending


for(int i=10;i>0;i--)
{
[Link](i);
}
Output: 10 9 8 7 6 5 4 3 2 1

2. While Loop
The while loop is used when the condition needs to be checked before executing the loop body. It is
suitable for scenarios where the number of iterations is not predetermined.
Syntax: While(condition)
{
Statements: inc/dec
}
Example:
public class WhileLoopExample {
public static void main(String[] args) {
int i = 0;
while (i <= 10) {
[Link](i);
i++;

7
}
}
}
Output: 1 to 10 printed and displayed

Int i=2;
while(i<=10)
{
If(i%2==0)
{
[Link](i)
}
I++
}

Example:
// Print numbers from 1 to 5
int i = 1;
while (i <= 5) {
[Link](i);
i++;
}
Key Points:
• Entry-controlled loop (condition checked first).
• Executes zero or more times depending on the condition.

3. Do-While Loop
The do-while loop guarantees at least one execution of the loop body before checking the condition.
It is useful when you need to execute the block at least once regardless of the condition.
do
{
Statements Inc/dec
}
while(condition);

Example:
// Print numbers from 1 to 5
int i = 1;
do {
[Link](i);
i++;
} while (i <= 5);
Key Points:
• Exit-controlled loop (condition checked after execution).
• Executes one or more times.
***which loop is preferred to use more:
1. If we know the number of iteration in advance, the for loop is often the most suitable.
2. If we want to execute the loop at least once, the do-while loop is appropriate.
3. If we are uncertain about the number of iterations and the loop termination is based
on condition, the while is a good choice.
Example:
Bike : Source, Destination, Fuel -- for loop is best
Bus : first execute the statement then check the condition -- do-while
loop. Flight : here we satisfy the condition first then statements – while
loop.

8
break and continue in loops
•break – Stops the current flow of program or loop completely.
•continue – Skips the current iteration and moves to the next. It doesn’t break the loop.
Example:
for(int i=1; i<=10; i++)
{
if(i==5)
{
break;
}
[Link](i); // 1 2 3 4 output
}

Difference between == and .equals() in Java?


o == Compares references (whether two variables point to the same object in memory).
o .equals()compares values/content of elements
Example:
String s1 = new String("Test");
String s2 = new String("Test");
[Link](s1 == s2); // false (different memory)
[Link]([Link](s2)); // true (same content)

Array in Java?
An array is the fundamental data structure and is a fixed-size collection of similar data types.
• Allows homogenous data
• Non primitive data type
• Fixed size
• We can store multiple values into a single variable using index.
Array in Java is index-based, the first element of the array is stored at the (Zero)0th index, 2nd
element is stored on 1st index and so on.

Declare array and Add values into array:


//Approach1:
int a[]=new int[5]; //declaration
a[0]=100;
a[1]=200;
a[2]=300; //
assignment
a[3]=400;
a[4]=500;
*/
//Approach2
int a[]= {100,200,300,400,500}; //Array Declaration and Add values into
array
//find length of an array
[Link]("Length of an array:"+[Link]); // Length of an array:5
//read single value from an array
[Link](a[4]); //500...
//reading all value from an array
//Normal for loop

9
int a[]= {100,200,300,400,500}; //declaration & assignment
for(int i=0;i<[Link];i++)
{
[Link](a[i]); //100 200 300 400 500
}
//Enhanced for loop
for (int x:a)
{
[Link](x); //100 200 300 400 500
}

Example: Using Object variable allows all kind of data.


Approach 1: Using Enhanced for loop
public class array {
int a1 =10;
double d=10.5;
char c= 'A';
String s= "welcome";
Boolean b=true;
public static void main(String[] args)
{
//Using Object variable allows all kind of data.
//Approach 1: Using Enhanced for loop
Object a[]= {100,10.5,'A',"welcome",true};
{
for(Object x:a)
{
[Link](x);
}
}
}

int[] arr = new int[5]; // Array


ArrayList<Integer> list = new ArrayList<>(); // ArrayList

➢ How to Check if an Array is Empty or Null?


Example:
int[] arr = null;
if (arr == null || [Link] == 0) {
[Link]("Array is empty or null");
}

Types of arrays:
1) Single dimensional array
2) Two dimensional/multi-dimensional.
1. One-Dimensional Array (1D):
o A 1D array is a fundamental data structure that stores elements in a linear sequence.
o Each element in a 1D array is accessible using a single index.
o It represents a list of variables with the same data type.
o The size of a 1D array is fixed.
o Declaration:
int[] singleArray = new int[5];
2. Two-Dimensional Array (2D):
o A 2D array extends the concept by organizing data in a grid-like structure.
o It consists of a list of lists (arrays) with similar data types.
o Requires two indices to access individual elements: one for the row and another for

10
the column.
o Often used to represent matrices.
o Declaration:
int[][] multiArray = new int[3][4];

// Sorting numbers
import [Link];
public class sortingelementsarray {
public static void main(String[] args) {
int a[]={100,600,200,400,500};
[Link]("before sorting..." + [Link](a));
[Link](a); //sorting command
[Link]("After sorting..." + [Link](a));
}
// for string variables
string a[]={“a”,”c”,”d”,”b”,”e”};
[Link]("before sorting..." + [Link](a));
[Link](a); //sorting command
[Link]("After sorting..." + [Link](a));
}
}
Output: before sorting...
[100, 600, 200, 400, 500]
After sorting...
[100, 200, 400, 500, 600]
Output: before sorting...
[a, c, d, b, e]
After sorting...
[a, b, c, d, e]

//Sorting even and odd numbers


public class ListIteratorExample {
public static void main(String args[]){
int a[]={10,20,30,40,55,60,75};
int even=0; int odd=0; for(int x:a)
{
if(x%2==0)
{
even++;
}
else
{
odd++;
}
}
[Link]("even count: "+even);
[Link]("odd count: "+odd);
}
}
Even count: 5
Odd count: 2

//Print elements in reverse/descending order.


public class reverseorderarray { //using while loop.
public static void main(String[] args) {
int a[]= {100,200,300,400,500};
//Approach 1
int i=4;
while(i>=0;)
{

11
[Link](a[i]); i--;
}
//Approach 2
for(int i=[Link]-1;i>=0;i--)
{
[Link](a[i]);
}
}
}
Output: 500 400 300 200 100

Difference between Array and ArrayList in Java?


• Array: Fixed size, can store both primitive and object types.
• ArrayList: Dynamic size, can store only objects (wrapper classes for primitives).
Array ArrayList
It is fundamental data structure It is java collection framework
Fixed size and static Dynamic size
Using length method to calculate size of array It uses [Link]() method
It supports both single and multi-dimensional It supports only single dimensional array
array
Fast performance bcz fixed size Slower (due to resizing)
Can store primitive datatypes only Stores objects(non-primitive) only
Supports only heterogenies data Supports only homogenies data
It doesn’t have built in methods (add, remove It supports built in methods (add, remove
etc.. etc..

Automation projects prefer ArrayList because test case counts often change.

String in Java, and why is it immutable?


• A String is a sequence of characters stored as an object.
• Immutable means once created, the value cannot be changed.
• If you modify it, a new object is created in memory.
Example:
String test = "Login";
test = test + " Test"; // New object created

In QA, immutability ensures test data consistency during execution.

Difference between String, StringBuilder, and StringBuffer?


• String: Immutable, slower in frequent modifications.
• StringBuilder: Mutable, faster, not thread-safe.
• StringBuffer: Mutable, thread-safe but slower than StringBuilder.
✓ In automation, StringBuilder is preferred for building large API requests dynamically.
✓ String buffer was introduced in java 1 v but string builder was java 5.
✓ Both are mutable.
✓ StringBuffer is synchronized (thread-safe) while StringBuilder is not (not thread safe).
✓ StringBuffer slower due to synchronisation while StringBuilder faster due to no
synchronisation.
Example:
StringBuilder sb = new StringBuilder("Hello"); [Link](" World"); // Faster
StringBuffer sbf = new StringBuffer("Hello"); [Link](" World"); // Thread-Safe

12
Constructors in Java
Constructors in Java are special methods used to initialize objects. They run automatically when
you create an object using the new keyword, and they set up the initial state of that object.

🔑 Key Features of Constructors


• Constructor name should be same as the class name.
• It has no return type, not even void.
• It is automatically invoked when an object is created.
• Can be overloaded (multiple constructors with different parameter lists).
• Used to provide default values or custom initialization.

🔹 Types of Constructors in Java


1. Default Constructor
• It has no parameters.
• It initializes objects with default values (e.g., 0 for numbers, null for objects).

class Car {
String brand;
int year;
// Default constructor
Car() {
brand = "Unknown";
year = 2000;
}
}
public class Main {
public static void main(String[] args) {
Car c = new Car();
[Link]([Link] + " - " + [Link]);
}
}

2. Parameterized Constructor
• Accepts arguments to initialize object with specific values.
class Car {
String brand;
int year;
// Parameterized constructor
Car(String b, int y) {
brand = b;
year = y;
}
}
public class Main {
public static void main(String[] args) {
Car c = new Car("Tesla", 2024);
[Link]([Link] + " - " + [Link]);
}
}

3. Copy Constructor (Not built-in, but can be created manually)


• Definition: A constructor that creates a new object as a copy of an existing object.
• Purpose: Duplicate an object’s state.
Example:

class Car {

13
String brand;
int year;
// Parameterized constructor
Car(String b, int y) {
brand = b;
year = y;
}
// Copy constructor
Car(Car other) {
brand = [Link];
year = [Link];
}
}
public class Main {
public static void main(String[] args) {
Car c1 = new Car("BMW", 2023);
Car c2 = new Car(c1); // Copy constructor
[Link]([Link] + " - " + [Link]);
}
}

Constructor Overloading
• Multiple constructors in the same class with different parameter lists.
Public class cars{
// constructor with one argument
cars(String name){
[Link]("String: " + name);
}
// constructor with two arguments
cars(String name, int year){
[Link](name " " + age);
}

Public class carDemo {


public static void main(String[] args){

// Creating the objects of the class named 'cars'


// by passing different arguments
cars car1 = new cars("TATA");
// Invoke the constructor with two arguments
cars car2 = new cars("Punch", 2026);
}
}

❖ How is it use Constructor in Selenium POM?


• A constructor is a special method used to initialize objects.
• In POM, constructors often initialize web elements with PageFactory:
public LoginPage(WebDriver driver) {
[Link] = driver;
[Link](driver, this);
}

• This ensures that all elements are ready when a page object is created.

14
Core Differences Between Constructor and Method
Constructor Method
Used to initialize an object’s state when it is Used to define behavior or operations that an
created. object can perform.
Must have the same name as the class. Can have any valid identifier name (usually
describes the action).
No return type (not even void). Must have a return type (void or any data type).
Called automatically when an object is Called explicitly using the object reference or class
created using new. name (for static methods).
Not inherited by subclasses, but a subclass Inherited by subclasses (unless
can call a superclass constructor declared private or overridden).
using super().
Can be overloaded (multiple constructors Can be overloaded and overridden.
with different parameter lists).
If no constructor is defined, Java provides No default method is provided; must be explicitly
a default no-argument constructor. defined.
Can use this() to call another constructor in Can use this to refer to the current object,
the same class, or super() to call a and super to call a superclass method.
superclass constructor.

Can We Override a Constructor?


❌ No, constructors cannot be overridden.

Object-Oriented Programming (OOP) in Java


OOP is a programming paradigm that organizes code into objects — reusable units that combine
data (fields) and behavior (methods).
It improves modularity, scalability, and reusability.
Class
• A class is a blueprint or template
• It defines the properties and behaviours of objects.
• It doesn’t require physical existence.
Object
• An object is an instance of a class
• It encapsulates data and provides methods to interact with that data.
• It is the instance of class.
• It does require physical existence.
Example:
class Car {
String color = "Red";
void drive() {
[Link]("Driving..."); }
}

public class Main {


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

15
Framework of OOP is supported by four key pillars:
1. Encapsulation
Encapsulation is the wrapping/bundling data and the methods within a single unit/class.
It acts as a protective barrier to unauthorized access.
To achieve encapsulation in Java, we can follow steps:
• Declare class variables as private to ensure they are hidden from other classes.
• Provide public getter and setter methods to allow controlled access and modification of these
private variables.
• Encapsulation is used for storing sensitive test data (like credentials).

Example: Banking Systems


A BankAccount class keeps the balance variable private, requiring all changes to occur through
deposit() or withdraw() methods that enforce business rules

Real time example in framework


Used in Page Object Model (POM) to keep web elements and methods private.
public class LoginPage {
private WebDriver driver;
By username = [Link]("username");
public void enterUsername(String user) {
[Link](username).sendKeys(user);
}
}
Encapsulation Page classes encapsulate web elements and actions, exposing only necessary methods

2. Inheritance
Inheritance allows one class to acquire the properties and behaviours of another class.
The extends keyword is used to establish this relationship, allowing the subclass to inherit all non-
private members of the superclass.
• Types of inheritance:
a) Single (one child, one parent),
b) Multilevel (a chain of inheritance), and
c) hierarchical (multiple children, one parent).

• Limitations: To avoid ambiguity—specifically the "Diamond Problem"—Java does not


support multiple inheritance through classes but allows it through interfaces.

Real time example in framework


Used in Base Class, to initializes WebDriver, webDriver waits, setup, teardown. Test classes extend
this base to reuse setup logic.
public class BaseTest {
WebDriver driver;
@BeforeMethod
public void setUp() {
driver = new ChromeDriver();
}
}

public class LoginTest extends BaseTest {


@Test
public void testLogin() {
setUp(); /* test steps */

16
}
}
➢ This avoids code duplication across tests.

What Would Happen If Java Allowed Multiple Inheritance?


❌ It would cause the "Diamond Problem".
Example:
class A {
void show() {
[Link]("A");
}
}
class B extends A {
void show() {
[Link]("B");
}
}
class C extends A, B {
} // Compilation Error

➢ Java solves this by using interfaces instead of multiple inheritance.

3. Polymorphism
Polymorphism, meaning "many forms," allows a single entity like a method or operator to perform
different actions depending on the context.
• One thing have many forms
Example:
class TestRunner {
void runTest(String name) {
[Link](name);
}
void runTest(String name, int id) {
[Link](name + " " + id);
}
}
➢ We are using this concept in between page classes and test cases by using “extends” keyword.

Method Overloading (Static Polymorphism)


• Multiple methods within the same class should have same name but different parameter.
• The return type may or may not be same.
• It is known as compile-time (static) polymorphism because the compiler determines which
method to invoke during compilation based on the method signature.
• It is static binding
• It may or may not require Inheritance.
• Within the same class
• Purpose: It improves code readability and consistency by allowing a single method name to
perform similar tasks with different inputs.
Example of Overloading:
class Example {
void show(int a) {
[Link]("Integer: " + a);
}
void show(double a) {
[Link]("Double: " + a);

17
}
void show(int a, int b) {
[Link]("Sum: " + (a + b));
}
public static void main(String[] args) {
Example obj = new Example();
[Link](10);
[Link](5.5);
[Link](10, 20);
}
}
We use Implicit wait in Selenium. Implicit wait is an example of overloading. In Implicit wait
we use different time stamps such as SECONDS, MINUTES, HOURS etc.,

Method Overriding (Dynamic Polymorphism)


• Multiple methods within the same class should have same names and same parameters.
• The return should be same.
• It is known as runtime (dynamic) polymorphism because the Java Virtual Machine (JVM)
determines which version of the method to execute at runtime based on the actual object
type.
• Using the @Override annotation to ensure the method is correctly overriding a parent method,
which helps catch errors during compilation.
• It always required an inheritance relationship between classes.
• It operated Between superclass and subclass
• Cannot override static, final, or private methods.
Code Example of Overriding:
class Animal {
void sound() {
[Link]("Some generic animal sound");
}
}
class Cat extends Animal {
@Override
void sound() {
[Link]("Meow"); // Specific implementation for Cat
}
}
➢ Method Overriding: Used in Selenium WebDriver (ChromeDriver, FirefoxDriver).
4. Abstraction
• focuses on hiding internal the complexity/logic from the end-user. It exposing only essential
features.
It can be achieved by interface and abstract classes only.
• Abstract Classes: These are classes that cannot be instantiated and serve as incomplete
blueprints, often containing abstract methods that subclasses must implement.
• Interfaces: These define a contract or a list of behaviours that a class must provide, allowing
for the inheritance of multiple behaviours.

Hiding internal details, showing only essential methods.


abstract class Browser {
abstract void launch();
}
class Chrome extends Browser {
void launch() {
[Link]("Launching Chrome");
}

18
}
Real time example in framework
In Page Object Model design pattern, we write locators (such as id, name, xpath etc.,) and the
methods in a Page Class. We utilize these locators in tests but we can’t see the implementation of
the methods.
Example:
public abstract class BasePage {
public abstract void clickElement(String locator);
}

public class LoginPage extends BasePage {


@Override
public void clickElement(String locator) {
[Link]([Link](locator)).click();
}
}
Here, tests interact with clickElement() without worrying about WebDriver internals.

Abstract Class
An abstract class is a class that cannot be instantiated directly. It can contain both abstract
methods (without implementation) and concrete methods (with implementation). It is used when
classes share common behavior but also need to define specific implementations.
Key Features:
• Can have both abstract and concrete methods.
• Can include member variables (final, non-final, static, or non-static).
• Can have constructors to initialize variables.
• Supports single inheritance (a class can extend only one abstract class).
• Access modifiers (public, protected, private) can be applied to methods and variables.

Example:
abstract class Shape {
String name;
Shape(String name) {
[Link] = name;
}

public void moveTo(int x, int y) {


[Link](name + " moved to x = " + x + ", y = " + y);
}

abstract public double area();


abstract public void draw();
}

class Circle extends Shape {


int radius;
Circle(int radius, String name) {
super(name);
[Link] = radius;
}

@Override
public double area() {
return [Link] * radius * radius;
}

19
@Override
public void draw() {
[Link]("Drawing Circle");
}
}

Use Case:
Use abstract classes when you have related classes sharing common code or when you need
methods with access modifiers other than public .

Interface
An interface is a reference type that defines a contract for classes to implement. It contains abstract
methods by default, but from Java 8 onwards, it can also include default and static methods with
implementations.
Key Features:
• All methods are abstract by default (until Java 8).
• Variables are implicitly public , static , and final .
• Supportsmultiple inheritance (a class can implement multiple interfaces).
• Cannot have constructors or instance fields.

Example:
interface Drawable {
void draw();
}
class Circle implements Drawable {
public void draw() {
[Link](“successful”);
Use Case:
Use interfaces when you need to define a contract for unrelated classes or when multiple inheritance
is required.
Key Differences
• Methods: Abstract classes can have both abstract and concrete methods, while interfaces
(until Java 8) only have abstract methods.
• Variables: Abstract classes can have various types of variables, but interface variables are
always public , static , and final .
• Inheritance: Abstract classes support single inheritance, while interfaces support multiple
inheritance.
• Constructors: Abstract classes can have constructors; interfaces cannot.
When to Use
✓ Use abstract classes when classes share common behavior or require non-public
methods/fields.
✓ Use interfaces When multiple classes should follow a common behaviour, but have different
implementations. when multiple inheritance is needed.

➢ Can We Initialize a Variable in an Interface?


✅ Yes, but only with public, static, final values.
Example:
interface Test {
int a = 10; // Implicitly public, static, final
}

20
➢ Why is object creation not possible for Abstract classes?
Abstract classes may have incomplete methods (abstract methods), so they cannot be
instantiated directly.
➢ Can We Instantiate an Interface?
No, interfaces cannot be instantiated.
➢ Can We Create an Object of an Abstract Class?
❌ No, but we can create an instance using an anonymous inner class.
❖ What is static in Java?
✅ static is a keyword used for memory management.
Where used? Purpose
Static Variable Shared among all objects.
Static Method Can be called without creating an object.
Static Block Runs before the main()method.
Example:
class Example {
static int count = 0;
static void display() {
[Link]("Static Method Called");
}
static { // Static Block
[Link]("Static Block Executed");
}
}
➢ Can We Overload Static Methods?
✅ Yes, but method signature must be different.
class Example {
static void show() {
[Link]("Static Method 1");
}
static void show(int a) {
[Link]("Static Method 2: " + a);
}
}

➢ Can We Override Static Methods?


❌ No, static methods cannot be overridden.
✅ They can be hidden by defining another static method.
➢ What is the use of static variables?
Static variables are shared among all instances of a class. They store class- level data
instead of instance-specific data.
➢ What is this keword in Java?
- Refers to the current object instance.
- Distinguishing Instance & Local Variables:
class Example {
int x;
Example(int x) {
this.x = x; // `this` refers to the instance variable
}
}

21
➢ Can We Overload main()?
✅ Yes, it is possible only through JVM, JVM only calls main(String[] args).
Example:
public class Test {
public static void main(String[] args) {
[Link]("Main method");
}

public static void main(int a) {


[Link]("Overloaded main method: " + a);
}
}
➢ Can We Override main()?
No, because main() is static, and static methods cannot be overridden.
➢ Why is the main method static?
The main method is static because it is the entry point of the Java application and needs to
be called without creating an object of the class.
➢ Can We Execute Java Without main()?
✅ Before Java 7 (Using Static Block), Not Possible in Java 8+.
➢ What Happens If main() is Declared as Private?
The program compiles, but it fails to run because the JVM cannot find the main() method.
Error: Main method not found in class Test
➢ Can We Overload Private Methods?
✅ Yes, private methods can be overloaded within the same class.
Example:
class Test {
private void display(int a) {
[Link](a);
}
private void display(String b) {
[Link](b);
}
}

➢ What is Synchronization in Java?


Synchronization in Java is the mechanism that ensures only one thread can access a shared
resource at a time, preventing data inconsistency and race conditions in multithreaded programs.
- It’s essential in multithreaded applications to avoid race conditions.
➢ What is the ‘this’ keyword in Java?
Refers to the current object instance.
➢ What is the ‘super’ keyword in Java?
- The super keyword is used to differentiate parent class members from child class members,
especially in cases of overriding or shadowing. It ensures proper inheritance behavior and
constructor chaining.
- It helps in calling parent class methods, constructors, and variables when they are hidden or
overridden in the child class.”
Example: In a BaseTest class having setup() method, we can call it in child test class:
[Link]();

22
❖ Static Binding vs Dynamic Binding
Static Binding Dynamic Binding
Method call is resolved at compile time. Method call is resolved at runtime.
It also known as Early Binding It also known as Late Binding
It applicable To Static methods, final Applicable To Overridden methods (runtime
methods, private methods, and method polymorphism).
overloading.
Decision based on reference type. Decision based on actual object type.
Faster performance (no runtime overhead). Slower performance (requires runtime lookup).
Support compile-time polymorphism. Supports runtime polymorphism.
Ex: Method overloading, static method calls. Ex: Method overriding.

Example:
class Animal {
static void staticMethod() {
[Link]("Animal static method");
}
void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
static void staticMethod() {
[Link]("Dog static method");
}
@Override
void sound() {
[Link]("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();

// Static Binding (based on reference type)


[Link](); // Output: Animal static method

// Dynamic Binding (based on actual object type)


[Link](); // Output: Dog barks
}
}
✅ Key Takeaway:
✓ Static Binding → Happens for methods that cannot be overridden (static, final, private).
✓ Dynamic Binding → Happens for overridden instance methods and enables runtime polymorphism.

❖ Difference b/w Throw vs. Throws


Aspect throw throws
Purpose Used to explicitly throw an exception Declares exceptions a method might throw
Usage Inside method or block In method signature
Number Only one exception object at a time Multiple exceptions can be declared, separated by
allowed commas
Position Statement inside code Part of method declaration
Example throw new void readFile() throws IOException,
IOException("Error"); SQLException

23
Example of throw:
throw new ArithmeticException("Cannot divide by zero");
Example of throws:
void test() throws IOException {
throw new IOException("File not found");
}

❖ Can We Use Multiple catch Blocks?


✅ Yes, multiple catchblocks can be used.

❖ Difference between final, finally, and finalize()


final: Used for constants, prevents inheritance or overriding,
• final value once initialised cannot be changed,
• final method cannot be overridden and
• final class is cannot be inherited.
• It prevents inheritance.
finally: Used in exception handling, after the try-catch block, It executes always either exception
occurred or not.
finalize(): Called by garbage collector before object is destroyed.
Example:
try {
int x = 10 / 0;
} catch (Exception e) {
[Link]("Exception caught");
} finally {
[Link]("Code executed");
}

❖ Can We Extend a Final Class?


❌ No, a finalclass cannot be extended.

❖ Explain Exception Handling in Java


• Exception is the abnormal condition, and it can occur either by syntax errors or logical errors
• Handled using try, catch, finally, throw, throws.
Example:
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero");
} finally {
[Link]("Finally block executes always");
}

Two types of Java exceptions.


✅ Checked Exceptions (Compile-time exceptions)
• Must be handled using try-catch or throws.
• Examples: IOException, SQLException.

✅ Unchecked Exceptions (Runtime exceptions)


• Occur due to programming mistakes.
• Examples: NullPointerException, ArithmeticException.

24
❖ Access Modifiers in Java and Their Scope
Modifier Scope
private Only within the same class
default Within the same package
protected Same package + subclasses
public Accessible from anywhere
Example:
class Test {
private int a = 10; // Only inside this class protected int
b = 20; // Accessible in subclasses public int c = 30; //
Accessible everywhere
}

In Selenium: Use private for WebElement variables, and public methods for accessing them to maintain
encapsulation.

❖ What is Meant by Thread?


✅ A Thread is a lightweight subprocess used for parallel execution.
✅ In Java, threads can be created using:
• Extending Thread class
• Implementing Runnable interface

Example:
class MyThread extends Thread { public void run() {
[Link]("Thread is running...");
}
}
public class Test {
public static void main(String[] args) { MyThread t1 = new
MyThread(); [Link]();
}
}

❖ What is Multithreading in Java?


• Allows concurrent execution of two or more threads.
• Increases performance in multi-core systems.
Example:
class MyThread extends Thread {
public void run() {
[Link]("Thread running: " + [Link]().getName());
}
}
public class Demo {
public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link]();
}
}

25
❖ What is a Singleton Class in Java?
✅ A Singleton class ensures only one instance is created.
Example:
class Singleton {
private static Singleton instance;
private Singleton() {} // Private Constructor
public static Singleton getInstance() { if
(instance == null) {
instance = new Singleton();
}
return instance;
} }
✅ Used in Selenium for WebDriver instance management.
❖ What is Autoboxing and Unboxing?
✅ Autoboxing: Converting Primitive → Wrapper Class
✅ Unboxing: Converting Wrapper Class → Primitive
Example:
// Autoboxing
Integer num = 10; // int → Integer

// Unboxing
int x = num; // Integer → int

❖ What is a Wrapper Class in Java?


Object representation of primitive types.
Example:
int x = 5;
Integer y = [Link](x);

Used in Collections, as they store only objects.

❖ Difference between ArrayList and LinkedList


Feature ArrayList LinkedList
Storage Dynamic array Doubly linked list
Access speed Faster (O(1)) Slower (O(n))
Insertion/Deletion Slower Faster
Use case Read-heavy Insert/delete-heavy

❖ What are Collections in Java?


Collections are a framework of classes and interfaces in the [Link] package that provide ready-made data
structures (like List, Set, Map, and Queue) to store, organize, and manipulate groups of objects efficiently.
They replace manual array handling with flexible, reusable, and standardized tools
A framework for storing/managing groups of objects.
• List – Store multiple web elements, Ordered, allows duplicates.
• Set – Store unique data, Unordered, no duplicates.
• Map – Key-value pairs.

➢ Difference b/w Set vs. Map in Java


✓ “A Set in Java is a collection that stores only unique elements, while a Map stores key-value pairs
where keys are unique but values can be duplicated.”
✓ • Set → Focuses on uniqueness of elements.
• Map → Focuses on association of keys and values pairs.

26
✓ • Set: No duplicates allowed; allows one null element.
• Map: allows only one null key, values can be duplicated, multiple null values allowed.
✓ • Set: Iteration only (no direct access).
• Map: Access values via keys ([Link](key)).
✓ “Both rely on hashing for average constant-time performance in operations like add, contains, and
get.”
Example of Set:
Set<String> set = new HashSet<>();
[Link]("A");
[Link]("B");
[Link]("A"); // Duplicate ignored
[Link](set); // Output: [A, B]
Example of Map:
Map<Integer, String> map = new HashMap<>();
[Link](1, "A");
[Link](2, "B");
[Link]([Link](1)); // Output: A

➢ How does HashMap work internally?


It uses an array of buckets and stores key-value pairs using hashing.
Always stores data in key-value format.
HashMap<Integer, String> map = new HashMap<>();
[Link](1, "Login Test");

QA uses HashMap for storing test case data dynamically.

➢ What is HashMap? Can We Store Objects in HashMap?


✅ HashMap stores key-value pairs. We can store objects as keys or values.
Example:
import [Link].*;
class Employee {
int id;
String name;
Employee(int id, String name) {
[Link] = id;
[Link] = name;
}
}
public class HashMapDemo {
public static void main(String[] args) {
HashMap<Integer, Employee> map = new HashMap<>();
[Link](1, new Employee(101, "Alice"));
[Link](2, new Employee(102, "Bob"));
Employee e = [Link](1);
[Link]([Link]); // Output: Alice
}
}

➢ Difference Between HashMap and HashSet


1. A HashMap is a collection that stores data in key-value pairs, whereas a HashSet is a collection that
stores only unique values without any mapping.”
2. “Internally, HashSet actually uses a HashMap. The elements of the set are stored as keys in the
map, and a dummy constant object is used as the value.”
3. • HashMap: Keys must be unique, but values can be duplicated.

27
• HashSet: Only unique elements are allowed; duplicates are ignored.
4. • HashMap: Allows one null key and multiple null values.
• HashSet: Allows a single null element.
5. • HashMap: Access values via keys ([Link](key)).
• HashSet: No direct access; you iterate over elements.
6. So in short, HashMap is about key-value mapping, while HashSet is about uniqueness of elements. Both
rely on hashing, but they serve different purposes.

➢ Why Override hashCode() When Overriding equals()?


✅ Reason: In collections (like HashMap, HashSet), objects are stored based on hashCode. If
equals()is overridden but hashCode()is not, objects that are logically equal may not be treated as
equal in collections.
Example:
class Student {
int id;
String name;
Student (int id, String name) {
[Link] = id;
[Link] = name;
}
@Override
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != [Link]()) return false;
Student student = (Student) obj;
return id == [Link] && [Link]([Link]);
}

@Override
public int hashCode() { // Ensures objects with same data get the same hash
return id;
}
}

➢ Where Did You Use HashMap in Your Project?


✅ Example Usage in Automation Framework:
• Scenario: Storing test data for different test cases.
• Use Case: Instead of using Excel or a JSON file, I used a HashMapto store key-value pairs
dynamically.
Example:
HashMap<String, String> testData = new HashMap<>();
[Link]("username", "admin");
[Link]("password","Admin123");

// Using the HashMap in Selenium


[Link]([Link]("username")).sendKeys([Link]("username"));
[Link]([Link]("password")).sendKeys([Link]("password"));

✅ This makes data retrieval faster and efficient during test execution.

➢ How to iterate over a Collection?


for (String test : testCases) {
[Link](test);
}

28
Or using Iterator:
Iterator<String> it =
[Link](); while
([Link]()) {
[Link]([Link]());
}

➢ What is [Link]() and Its Use?


[Link]() in Java is a method used to print output to the console, and it automatically
moves the cursor to the next line after printing. It is one of the most commonly used statements for
displaying messages, debugging, and showing results in Java programs.
System: A built-in final class in the [Link] package that provides access to system-level
resources like input, output, and error streams.
out: A static member of the System class, which is an instance of the PrintStream class. It
represents the standard output stream (usually the console).
println(): A method of the PrintStream class that prints the given argument and appends a
newline character at the end.
➢ What is Call by Value and Call by Reference?
✅ Call by Value: When we pass a primitive type (e.g., int, double, char) to a method, Java copies
the value into a new variable inside the method. Changes inside the method do not affect the original
variable.
✅ Call by Reference: When you pass an object to a method, Java copies the reference (memory
address) to the method.
Both the original and the copied reference point to the same object in memory, so changes to the
object's fields are visible outside the method.
However, reassigning the reference inside the method does not affect the original reference.
Example (Call by Value in Java - Primitive Types)
class Example {
void change(int x) {
x = 50;
}
public static void main(String[] args) {
Example obj = new Example();
int num = 10;
[Link](num);
[Link](num); // Output: 10 (Original value unchanged)
}
}

Example (Call by Reference - Objects are Passed by Reference)


class Example {
int num = 10;
void change(Example obj) {
[Link] = 50;
}
public static void main(String[] args) {
Example obj = new Example();
[Link](obj);
[Link]([Link]); // Output: 50 (Value changed)
}
}

29
➢ How to Achieve Serialization and Deserialization?
✅ Serialization: Converting an object into a byte stream for saved into file or transferred over network.
✅ Deserialization: Converting byte stream back into an object.
Example:
import [Link].*;
class Student implements Serializable {
int id;
String name;

Student(int id, String name) {


[Link] = id;
[Link] = name;
}
}
public class SerializationDemo {
public static void main(String[] args) throws IOException, ClassNotFoundException {
// Serialization
Student s1 = new Student(1, "John");
FileOutputStream fos = new FileOutputStream("[Link]");
ObjectOutputStream oos = new ObjectOutputStream(fos);
[Link](s1);
[Link]();

// Deserialization
FileInputStream fis = new FileInputStream("[Link]");
ObjectInputStream ois = new ObjectInputStream(fis);
Student s2 = (Student) [Link]();
[Link]();

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


}
}
Note: Serializable interface does not have any method because it is marker interface(no methods). It only
informs to JVM, JVM can handles the serialization process.
➢ What is File Handling in Java?
File handling refers to creating, reading, writing, updating, and deleting files using the [Link]
package. It allows programs to store and retrieve data permanently, beyond temporary memory
usage.
Reading/writing files using File, FileReader, BufferedReader, etc.
In QA, used for reading test data from .txt or .csv.
"FileInputStream is used for reading binary data as bytes, while FileReader is specialized for
reading text data as characters. For example, if I’m processing an image or PDF, I’d use
FileInputStream. If I’m reading a log file or configuration file, I’d use FileReader. The key
distinction is that FileInputStream works at the byte level, whereas FileReader works at the
character level with Unicode support."

To read a file in Java


BufferedReader br = new BufferedReader(new FileReader("[Link]"));
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
[Link]();

30
To write into a file in Java
FileWriter writer = new FileWriter("[Link]");
[Link]("Test Passed");
[Link]();

1. File Class ([Link])


Represents file or directory pathnames. Common methods:
• createNewFile() → Creates a new empty file.
• delete() → Deletes a file.
• exists() → Checks if file exists.
• getName() → Returns file name.
• getAbsolutePath() → Returns full path.
• length() → Returns file size in bytes.
• mkdir() → Creates a directory.

2. Streams in Java
Streams handle input/output operations. Two main types:
• Byte Streams (binary data like images, audio, video)
o FileInputStream → Reads bytes from a file.
o FileOutputStream → Writes bytes to a file.
o BufferedInputStream / BufferedOutputStream → Faster performance with
buffering.
• Character Streams (text data, Unicode support)
o FileReader → Reads characters from a file.
o FileWriter → Writes characters to a file.
o BufferedReader → Reads text efficiently, supports readLine().
o BufferedWriter → Writes text efficiently.

➢ How to handle dates in Java?


1. LocalDate (Date only)
Represents a calendar date (year, month, day).
LocalDate today = [Link](); // Current date
LocalDate specificDate = [Link](2026, 4, 27); // Custom date
[Link]("Today: " + today);
[Link]("Specific: " + specificDate);

2. LocalTime (Time only)


Represents time (hours, minutes, seconds).
LocalTime now = [Link]();
[Link]("Current Time: " + now);

3. LocalDateTime (Date + Time)


Combines both date and time.
LocalDateTime current = [Link]();
[Link]("Current DateTime: " + current);

4. Formatting & Parsing


Use DateTimeFormatter for custom formats.
import [Link];
import [Link];

LocalDateTime dt = [Link]();
DateTimeFormatter formatter = [Link]("dd-MM-yyyy HH:mm:ss");
String formatted = [Link](formatter);

31
[Link]("Formatted: " + formatted);
➢ How to generate random data in Java?
In Java, you can generate random data using built-in classes like Random, [Link](),
ThreadLocalRandom, or SecureRandom,
public class RandomExample {
public static void main(String[] args) {
Random rand = new Random();
int randomInt = [Link](100); // 0 to 99
double randomDouble = [Link](); // 0.0 to 1.0
boolean randomBool = [Link]();
[Link]("Int: " + randomInt);
[Link]("Double: " + randomDouble);
[Link]("Boolean: " + randomBool);
}
}

Basic Java Coding Examples


1. Reverse a String without using reverse() method
public class ReverseString {
public static void main(String[]args) {
String str = "Automation";
String rev = "";
for (int i = [Link]() - 1; i >= 0; i--) {
rev += [Link](i);
}
[Link]("Reversed: " + rev);
}
}
Why QA needs this: Useful when validating reverse data transformations in APIs or UI.

2. Reverse Words in a Sentence


Split by spaces, reverse each word individually.
public class ReverseWords {
public static void main(String[] args) {
String str = "I love Java";
String[] words = [Link](" ");
for (int i = [Link] - 1; i >= 0; i--) {
[Link](words[i] + " ");
}
}
}

3. Reverse an Integer Without Using Built-in Method


class ReverseInteger {
public static void main(String[] args) {
int num = 12345, reversed = 0;
while (num > 0) {
int digit = num % 10;
reversed = reversed * 10 + digit; num /= 10;
}

[Link]("Reversed Number: " + reversed);


}
}

4. Reverse an Array
public class ReverseArray {

32
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
for (int i = [Link] - 1; i >= 0; i--) {
[Link](arr[i] + " ");
}
}
}
QA use: Data order validation.

5. Check if a String is a Palindrome


A palindrome reads the same backward and forward.
public class PalindromeCheck {
public static void main(String[] args) {
String str = "madam";
String rev = new
// Method 1
StringBuilder(str).reverse().toString();
if ([Link](rev)){
[Link]("Palindrome");
} else {
[Link]("Not Palindrome"); }
// Method 2
String rev = new StringBuilder(str).reverse().toString();
[Link]([Link](rev) ? "Palindrome" : "Not Palindrome");
}
}
}
QA use: Checking same input/output values in transformations.

6. Check if a Number is a Palindrome


class PalindromeNumber {
public static void main(String[] args) {
int num = 121, reversed = 0, temp = num;

while (temp > 0) {


int digit = temp % 10;
reversed = reversed * 10 + digit;
temp /= 10;
}
if (num == reversed) {
[Link](num + " is a Palindrome");
} else {
[Link](num + " is not a Palindrome");
}
}
}

7. Count Vowels in a String


public class CountVowels {
public static void main(String[] args) {
String str = "Quality Assurance";
int count = 0;
for (char c : [Link]().toCharArray()) {
if ("aeiou".indexOf(c) != -1) count++;
}
[Link]("Vowels: " + count);
}
}
QA use: Validating text data.

8. Swap Two Numbers Without Temporary Variable

33
public class SwapNumbers {
public static void main(String[] args) {
int a = 5, b = 10;
a = a + b;
b = a - b;
a = a - b;
[Link]("a=" + a + ", b=" + b);
}
}
QA use: Testing logic manipulation without extra memory.

9. Find Factorial of a Number


public class Factorial {
public static void main(String[] args) {
int num = 5, fact = 1;
for (int i = 1; i <= num; i++) {
fact *= i;
}
[Link]("Factorial: " + fact);
}
}
QA use: Mathematical validations in reports or APIs.

10. Fibonacci Series


public class Fibonacci {
public static void main(String[] args) {
int n = 7, a = 0, b = 1;
[Link](a + " " + b);
for (int i = 2; i < n; i++) {
int c = a + b;
[Link](" " + c);
a = b; b = c;
}
}
}
QA use: Data pattern validation.

11. Find Largest Number in Array


public class LargestInArray {
public static void main(String[] args) {
int[] arr = {10, 45, 23, 78, 56};
int max = arr[0];
for (int num : arr) {
if (num > max) max = num;
}
[Link]("Largest: " + max);
}
}

12. Count Words in a String


public class WordCount {
public static void main(String[] args) {
String str = "Automation testing with Java";
String[] words = [Link]().split("\\s+");
[Link]("Words: " + [Link]);
}
}
QA use: Checking text fields.

13. Find Duplicate Elements in Array


public class FindDuplicates {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 2, 4, 5, 1};

34
for (int i = 0; i < [Link]; i++) {
for (int j = i+1; j < [Link]; j++) {
if (arr[i] == arr[j])
[Link]("Duplicate: " + arr[i]);
}
}
}
}

14. Check Prime Number


public class PrimeCheck {
public static void main(String[] args) {
int num = 13;
boolean prime = true;
for (int i = 2; i <= num/2; i++) {
if (num % i == 0) {
prime = false; break; }
}
[Link](prime ? "Prime" : "Not Prime");
}
}

1. Check if two Strings are Anagrams


Sort both strings and compare.
import [Link];
public class AnagramCheck {
public static void main(String[] args) {
String s1 = "listen";
String s2 = "silent";
char[] a = [Link]();
char[] b = [Link]();
[Link](a);
[Link](b);
[Link]([Link](a, b) ? "Anagram" : "Not Anagram");
}
}

2. Find Second Largest Number


public class SecondLargest {
public static void main(String[] args) {
int[] arr = {10, 45, 78, 56};
int largest = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int num : arr) {
if (num > largest) {
second = largest; largest = num;
} else if (num > second && num != largest) {
second = num;
}
}
[Link]("Second Largest: " + second);
}
}

3. Sum of Digits
public class SumDigits {
public static void main(String[] args) {
int num = 12345, sum = 0;
while (num > 0) {
sum += num % 10; num /= 10;
}
[Link]("Sum: " + sum);
}

35
}

4. Remove White Spaces from String


public class RemoveSpaces {
public static void main(String[] args) {
String str = " Hello World ";
[Link]([Link]("\\s+", ""));
}
}

5. Convert String to Integer


public class StringToInt {
public static void main(String[] args) {
String s = "123";
int num = [Link](s);
[Link](num + 10);
}
}

6. Find Missing Number in Array


public class MissingNumber {
public static void main(String[] args) {
int[] arr = {1, 2, 4, 5};
int n = 5, total = n*(n+1)/2, sum = 0;
for (int num : arr)
sum += num;
[Link]("Missing: " + (total - sum));
}
}

7. Find duplicate characters in a String


Use a HashMapto count character occurrences.
import [Link].*;
public class DuplicateChars {
public static void main(String[] args) {
String str = "testing";
Map<Character, Integer> map = new HashMap<>();
for (char ch : [Link]()) {
[Link](ch, [Link](ch, 0) + 1);
}
for ([Link]<Character, Integer> e : [Link]()) {
if ([Link]() > 1)
[Link]([Link]() + " = " + [Link]());
}
}
}

8. Find the largest and smallest number in an array


Use [Link]() or manual comparison.
public class MinMaxArray {
public static void main(String[] args) {
int[] arr = {5, 9, 2, 10, 3};
int min = arr[0], max = arr[0];
for (int n : arr) {
if (n < min) min = n;
if (n > max) max = n;
}
[Link]("Min: " + min + ", Max: " + max);
}
}

36
9. Find the second highest number in an array
Sort and pick the second last element.
import [Link];
public class SecondHighest {
public static void main(String[] args) {
int[] arr = {10, 4, 7, 9, 3};
[Link](arr);
[Link]("Second highest: " +arr[[Link] - 2]);
}
}

10. Use Java 8 Stream to filter even numbers from a list


Use filter() and forEach() with lambda expressions.
import [Link].*;
import [Link].*;
public class EvenNumbers {
public static void main(String[] args) {
List<Integer> nums = [Link](1, 2, 3, 4, 5, 6)
}
[Link]()
.filter(n->n %2 =0)
.forEach(([Link]);
}

// Print week number based on week name (swich case)


public class weekNumBasedOnweekname
{
//private static Object invalid;
public static void main(String args[])
{
//Approach
int weeknum = 2;
switch (weeknum)
{
case 1: [Link]("week name is: sunday");break;
case 2: [Link]("week name is: monday");break;
case 3: [Link]("week name is: tuesday");break;
case 4: [Link]("week name is: wednesday");break;
case 5: [Link]("week name is: thursday");break;
case 6: [Link]("week name is: friday");break;
case 7: [Link]("week name is: saturday");break;
default: [Link]("week num is invalid");break;
}
}
Output: week name is: monday

// Smallest of 3 numbers (if…else) --- similar to above but reverse operation


// Approach 1
if (a<b && a<c)
{
[Link]("a is lower");
}
else if (b<a && b<c)

37
{
[Link]("b is lower");
}
if (c<a && c<b)
{
[Link]("c is lower");
}
// Using turnary operator
//int largest1=a>b?a:b;
//int largeno = c>largest1?c:largest1;
// or
int num = c<(a<b?a:b)?c:(a<b?a:b);
[Link](num+": is lower");
b is lower
20: is lower

//Largest of 2 numbers (if…else, ternary operator)


public class Firstjavaprog
{
public static void main(String args[])
{
int a=101; int b=20; int c=50;
/*
Scanner sc =new Scanner([Link]);
[Link]("enter value of a: ");
int a=[Link]();
[Link]("enter value of c");
int c=[Link]();
*/
// Approach 1
if (a>b && a>c)
{
[Link]("a is greater");
}
else if (b>a && b>c)
{
[Link]("b is greater");
}
if (c>a && c>a)
{
[Link]("c is greater");
}
// Using turnary operator
//int largest1=a>b?a:b;
//int largeno = c>largest1?c:largest1;
// or
int num = c>(a>b?a:b)?c:(a>b?a:b);
[Link](num+": is greater");
}
}
a is greater
101: is greater

38

You might also like