Java Document
Java Document
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
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,
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.
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:
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
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
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
}
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.
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
}
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]
11
[Link](a[i]); i--;
}
//Approach 2
for(int i=[Link]-1;i>=0;i--)
{
[Link](a[i]);
}
}
}
Output: 500 400 300 200 100
Automation projects prefer ArrayList because test case counts often change.
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.
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]);
}
}
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);
}
• 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.
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).
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).
16
}
}
➢ This avoids code duplication across tests.
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.
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.,
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);
}
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;
}
@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.
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);
}
}
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");
}
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();
23
Example of throw:
throw new ArithmeticException("Cannot divide by zero");
Example of throws:
void test() throws IOException {
throw new IOException("File not found");
}
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.
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]();
}
}
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
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
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.
@Override
public int hashCode() { // Ensures objects with same data get the same hash
return id;
}
}
✅ This makes data retrieval faster and efficient during test execution.
28
Or using Iterator:
Iterator<String> it =
[Link](); while
([Link]()) {
[Link]([Link]());
}
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;
// Deserialization
FileInputStream fis = new FileInputStream("[Link]");
ObjectInputStream ois = new ObjectInputStream(fis);
Student s2 = (Student) [Link]();
[Link]();
30
To write into a file in Java
FileWriter writer = new FileWriter("[Link]");
[Link]("Test Passed");
[Link]();
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.
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);
}
}
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.
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.
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]);
}
}
}
}
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
}
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]);
}
}
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
38