Java Introduction
Understand Java, its features, applications and basic program structure.
Java is a high-level, object-oriented, general-purpose programming language developed by Sun Microsystems. It is designed with an emphasis on simplicity, security, portability, and reliability.
Java follows the principle: Write Once, Run Anywhere (WORA) Java programs are compiled into bytecode, which can run on any system that has a Java Virtual Machine (JVM).
Why Is Java Popular?
Simple and Readable Syntax
Java has a structured and readable syntax. Its syntax is similar to languages such as C and C++, but Java removes many complex features such as pointers and manual memory management.
Large Ecosystem
Java has a large collection of libraries and frameworks used for: Web development, Enterprise applications, Android development, Database applications, Cloud applications.
Web Development
Java can be used to develop web applications and APIs. For example, Spring Boot is widely used to create REST APIs and backend applications.
Data & AI
Java is used very widely, especially for backend, enterprise, banking, and large-scale applications.
Your First Java Program
The System.out.println() function is commonly used to display
information in the console.
System.out.println("Hello, Java!")
Java Installation & Setup
Install Java and prepare your development environment using Visual Studio Code.
Before writing Java programs, you need to install the JDK (Java Development Kit). The JDK provides the tools required to develop, compile, and run Java programs. After installing the JDK, Visual Studio Code can be used to create, run, and debug Java programs.
1. Install Java JDK
Download and install a Java JDK such as JDK 21 (LTS) or a newer supported LTS version. During installation, Java will be installed on your computer.
The JDK contains the Java compiler and other tools required for Java development.
The Java compiler is called javac.
2. Check Whether Java Is Installed
Open Command Prompt or the VS Code Terminal and execute:
java --version
You should see something similar to:
java 21.x.x
Also check the Java compiler:
javac --version
You should see something similar to:
javac 21.x.x
The java command is used to run Java programs, while
javac is used to compile Java source code.
3. Create Your First Java File
Create a file named Hello.java and add:
public class Hello {
public static void main(String[] args) {
String name = "Java";
System.out.println("Welcome to " + name);
}
}
In this program, String name = "Java"; creates a String
variable called name. The System.out.println()
statement displays the message in the console.
The output will be:
Welcome to Java
4. Run the Java File
Open the VS Code Terminal and navigate to the folder containing
Hello.java.
First, compile the Java program using:
javac Hello.java
After compilation, a Hello.class file will be created.
This file contains Java bytecode that can be executed by the JVM
(Java Virtual Machine).
Now run the program using:
java Hello
The output will be:
Welcome to Java
5. Install Java Extension in VS Code
To get Java development features in Visual Studio Code, open the Extensions panel.
You can open the Extensions panel using:
Ctrl + Shift + X
Search for:
Extension Pack for Java
Install the Extension Pack for Java. It provides features such as:
- Java syntax highlighting
- Code completion
- Error detection
- Debugging
- Running Java programs
- Java project support
javac and
java every time.
javac compiles Java source code, and the
java command runs the compiled Java program.
Datatypes, Variables & Operators
Learn how Java stores values, defines variables, and performs different types of operations on data.
Variables
A variable is a named memory location used to store a value. In Java, every variable must have a data type that specifies what kind of value it can store.
Unlike Python, Java is a statically typed language. This means the data type of a variable must be specified when declaring the variable.
String name = "Arun";
int age = 22;
double salary = 25000.50;
System.out.println(name);
System.out.println(age);
System.out.println(salary);
In the above example:
Stringstores text.intstores whole numbers.doublestores decimal numbers.name,age, andsalaryare variable names.
Common Java Datatypes
Java data types are mainly divided into two categories: primitive data types and non-primitive (reference) data types.
Primitive data types directly store simple values. Java has
eight primitive data types: byte, short,
int, long, float,
double, char, and boolean.
| Datatype | Example | Purpose |
|---|---|---|
byte |
byte age = 22; |
Small whole numbers |
short |
short number = 1000; |
Whole numbers larger than byte |
int |
int age = 22; |
Commonly used for whole numbers |
long |
long population = 8000000000L; |
Large whole numbers |
float |
float price = 99.50f; |
Decimal numbers with single precision |
double |
double salary = 25000.50; |
Decimal numbers with double precision |
char |
char grade = 'A'; |
Stores a single character |
boolean |
boolean active = true; |
Stores true or false |
String |
String name = "Arun"; |
Stores a sequence of characters |
Primitive and Non-Primitive Data Types
Java data types can be understood using two main categories.
| Category | Examples | Description |
|---|---|---|
| Primitive | byte, short, int, long |
Used to store numeric values |
| Primitive | float, double |
Used to store decimal values |
| Primitive | char |
Used to store a single character |
| Primitive | boolean |
Stores true or false |
| Non-Primitive | String, Array, Class, Object |
Used for more complex data |
Checking Data Type
Java is statically typed, so the data type of a variable is already
known when the variable is declared.
Unlike Python, Java does not use type() in the same way.
For example:
int age = 22;
System.out.println(((Object) age).getClass().getSimpleName());
For most beginner Java programs, you normally know the type from the declaration itself:
int age = 22;
double salary = 25000.50;
String name = "Arun";
boolean active = true;
Operators
Operators are symbols used to perform operations on values and variables. Java provides several types of operators, including arithmetic, relational, logical, assignment, unary, and ternary operators.
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations.
| Operator | Name | Example |
|---|---|---|
+ |
Addition | a + b |
- |
Subtraction | a - b |
* |
Multiplication | a * b |
/ |
Division | a / b |
% |
Modulus | a % b |
Arithmetic Operator Example
int a = 10;
int b = 3;
System.out.println(a + b);
System.out.println(a - b);
System.out.println(a * b);
System.out.println(a / b);
System.out.println(a % b);
7
30
3
1
Relational Operators
Relational operators are used to compare two values.
The result of a comparison is always a boolean
value: either true or false.
| Operator | Meaning | Example |
|---|---|---|
== |
Equal to | a == b |
!= |
Not equal to | a != b |
> |
Greater than | a > b |
< |
Less than | a < b |
>= |
Greater than or equal to | a >= b |
<= |
Less than or equal to | a <= b |
int a = 10;
int b = 3;
System.out.println(a > b);
System.out.println(a < b);
System.out.println(a == b);
System.out.println(a != b);
false
false
true
Logical Operators
Logical operators are mainly used to combine multiple conditions.
| Operator | Name | Example |
|---|---|---|
&& |
Logical AND | a > 5 && b < 5 |
|| |
Logical OR | a > 5 || b > 5 |
! |
Logical NOT | !(a > b) |
int age = 25;
boolean citizen = true;
System.out.println(age >= 18 && citizen);
System.out.println(age < 18 || citizen);
System.out.println(!citizen);
Assignment Operators
Assignment operators are used to assign or update values in variables.
| Operator | Example | Equivalent To |
|---|---|---|
= |
a = 10 |
a = 10 |
+= |
a += 5 |
a = a + 5 |
-= |
a -= 5 |
a = a - 5 |
*= |
a *= 5 |
a = a * 5 |
/= |
a /= 5 |
a = a / 5 |
Increment and Decrement Operators
The ++ operator increases a value by 1, while the
-- operator decreases a value by 1.
int count = 10;
count++;
System.out.println(count);
count--;
System.out.println(count);
10
10 / 3 produces 3.
If you want a decimal result, use a floating-point value such as
10.0 / 3, which produces approximately 3.3333.
int, double, char, and
boolean, along with reference types such as
String, arrays, classes, and objects.
Statements & Loops
Learn how Java executes statements, makes decisions, and repeatedly executes a block of code using loops.
A statement is an instruction that tells Java to perform
a specific operation. Java programs are made up of multiple statements,
and each statement is generally terminated with a semicolon
;.
Statements allow a program to create variables, perform calculations, make decisions, and repeat operations.
Types of Statements in Java
Java statements can be broadly categorized into the following types:
- Declaration Statements
- Expression Statements
- Conditional Statements
- Looping Statements
- Jump Statements
1. Declaration Statements
A declaration statement is used to declare a variable and specify its data type.
int age;
double salary;
String name;
Variables can also be declared and initialized at the same time.
int age = 22;
double salary = 25000.50;
String name = "Arun";
2. Expression Statements
Expression statements perform an operation such as assigning a value, incrementing a variable, or calling a method.
int a = 10;
a = 20;
a++;
System.out.println(a);
3. Conditional Statements
Conditional statements are used when a program needs to make a decision based on a condition.
Java provides the following conditional statements:
ifif-elseelse-ifnested ifswitch
if Statement
The if statement executes a block of code only when
the specified condition is true.
int age = 20;
if (age >= 18) {
System.out.println("Eligible to vote");
}
Output:
Eligible to vote
if-else Statement
The if-else statement provides two possible execution paths.
If the condition is true, the if block is executed.
Otherwise, the else block is executed.
int age = 16;
if (age >= 18) {
System.out.println("Eligible to vote");
} else {
System.out.println("Not eligible to vote");
}
Output:
Not eligible to vote
else-if Statement
The else-if ladder is used when there are multiple
conditions to check.
int marks = 85;
if (marks >= 90) {
System.out.println("Grade A+");
} else if (marks >= 80) {
System.out.println("Grade A");
} else if (marks >= 70) {
System.out.println("Grade B");
} else if (marks >= 60) {
System.out.println("Grade C");
} else {
System.out.println("Fail");
}
else-if ladder are checked from top to
bottom. Once a condition becomes true, its block is executed and the
remaining conditions are skipped.
Nested if Statement
A nested if statement means placing one
if statement inside another if statement.
int age = 25;
boolean citizen = true;
if (age >= 18) {
if (citizen) {
System.out.println("Eligible to vote");
}
}
switch Statement
The switch statement is used when a variable needs to be
compared against multiple fixed values.
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
break statement stops the execution of the current
switch case. Without break, execution can
continue into the next case.
Loops in Java
A loop is used to execute a block of code repeatedly while a specified condition is satisfied.
Loops are useful when the same operation needs to be performed multiple times. For example, printing numbers from 1 to 100 can be done using a loop instead of writing 100 separate statements.
Java provides the following main types of loops:
- for loop
- while loop
- do-while loop
- for-each loop
1. for Loop
The for loop is commonly used when the number of iterations
is known in advance.
The basic syntax is:
for (initialization; condition; update) {
// code to execute
}
Example:
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
Output:
1
2
3
4
5
The three parts of a for loop are:
- Initialization: Creates or initializes the loop variable.
- Condition: Determines whether the loop should continue.
- Update: Changes the loop variable after each iteration.
2. while Loop
The while loop repeatedly executes a block of code as long
as the specified condition is true.
It is useful when the number of iterations is not known beforehand.
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
Output:
1
2
3
4
5
while
loop. Otherwise, the condition may always remain true and create
an infinite loop.
3. do-while Loop
The do-while loop is similar to the while loop,
but the block of code is executed at least once before
the condition is checked.
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
Output:
1
2
3
4
5
Consider this example:
int i = 10;
do {
System.out.println(i);
} while (i < 5);
Even though i < 5 is false, the program prints
10 once because the do block executes before
the condition is checked.
4. for-each Loop
The for-each loop is mainly used to iterate through
arrays and collections.
For example, an array can be processed without manually managing an index.
int[] numbers = {10, 20, 30, 40, 50};
for (int number : numbers) {
System.out.println(number);
}
Output:
10
20
30
40
50
In this loop, number receives each element of the
numbers array one at a time.
Nested Loops
A loop inside another loop is called a nested loop. Nested loops are commonly used for working with tables, matrices, patterns, and two-dimensional arrays.
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print(j + " ");
}
System.out.println();
}
Output:
1 2 3
1 2 3
1 2 3
break Statement
The break statement is used to immediately terminate
a loop or a switch statement.
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}
Output:
1
2
3
4
When i becomes 5, the break
statement terminates the loop.
continue Statement
The continue statement skips the current iteration
and moves to the next iteration of the loop.
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println(i);
}
Output:
1
2
4
5
When i becomes 3, the
continue statement skips that iteration.
break vs continue
| Statement | Purpose |
|---|---|
break |
Completely terminates the loop |
continue |
Skips the current iteration and continues with the next iteration |
Loop Comparison
| Loop | When to Use | Condition Check |
|---|---|---|
for |
When the number of iterations is known | Before execution |
while |
When the number of iterations may not be known | Before execution |
do-while |
When the code must execute at least once | After execution |
for-each |
When iterating through arrays or collections | Automatically handled |
for loop is generally convenient when you know how many
times you want to execute a block of code. A while loop is
useful when execution depends mainly on a condition. A
do-while loop always executes its body at least once.
The for-each loop is convenient for processing elements
of arrays and collections.
if, if-else, and
switch are used for decision-making, while loops such as
for, while, do-while, and
for-each are used for repeated execution.
The break and continue statements provide
additional control over loops.
Array
Store and manage multiple values of the same data type in Java.
An array is a collection of elements of the same data type stored under a single variable name. Arrays are useful when you need to store multiple values and access them using an index.
In Java, arrays have a fixed size. Once an array is created, its size cannot normally be changed. The index of an array starts from 0.
Creating an Array
An array can be declared using the data type followed by square brackets
[].
int[] numbers = {10, 20, 30, 40, 50};
System.out.println(numbers[0]);
System.out.println(numbers[2]);
Output:
10
30
Here, numbers[0] accesses the first element and
numbers[2] accesses the third element.
Array Index
Java arrays use zero-based indexing. This means the first element is
stored at index 0, the second element at index
1, and so on.
| Index | Value |
|---|---|
0 |
10 |
1 |
20 |
2 |
30 |
3 |
40 |
4 |
50 |
Declaring an Array
You can declare an array first and create it later.
int[] numbers;
numbers = new int[5];
The above code creates an integer array that can store five values.
The indexes will be from 0 to 4.
Initializing an Array
Values can be assigned to an array using indexes.
int[] numbers = new int[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
System.out.println(numbers[2]);
Output:
30
Changing an Array Element
Array elements can be modified by assigning a new value to an existing index.
int[] numbers = {10, 20, 30};
numbers[1] = 100;
System.out.println(numbers[1]);
Output:
100
Array Length
Java provides the length property to find the number of
elements in an array.
int[] numbers = {10, 20, 30, 40, 50};
System.out.println(numbers.length);
Output:
5
length without parentheses.
For example, numbers.length.
Traversing an Array Using for Loop
A for loop can be used to access every element of an array.
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Output:
10
20
30
40
50
Traversing an Array Using for-each Loop
Java also provides the for-each loop, which is useful when
you want to access every element without using an index.
int[] numbers = {10, 20, 30, 40, 50};
for (int number : numbers) {
System.out.println(number);
}
Output:
10
20
30
40
50
String Array
Arrays can also store String values. For example, a String array can be used to store names of students.
String[] students = {
"Arun",
"Priya",
"Kumar",
"Meena"
};
System.out.println(students[0]);
Output:
Arun
Two-Dimensional Array
A two-dimensional array is an array that contains rows and columns. It can be used to represent tables, matrices, and other grid-like data.
int[][] numbers = {
{10, 20, 30},
{40, 50, 60},
{70, 80, 90}
};
System.out.println(numbers[0][1]);
Output:
20
The first index represents the row and the second index represents the column.
Traversing a Two-Dimensional Array
Nested for loops can be used to access all elements of a
two-dimensional array.
int[][] numbers = {
{10, 20, 30},
{40, 50, 60},
{70, 80, 90}
};
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers[i].length; j++) {
System.out.print(numbers[i][j] + " ");
}
System.out.println();
}
Output:
10 20 30
40 50 60
70 80 90
Common Array Operations
| Operation | Example | Purpose |
|---|---|---|
| Access | numbers[0] |
Access an element |
| Update | numbers[0] = 100 |
Change an element |
| Length | numbers.length |
Find the number of elements |
| Traverse | for loop |
Access all elements |
| Search | for loop |
Find a particular element |
Array Example
The following example calculates the sum of all elements in an array.
int[] numbers = {10, 20, 30, 40, 50};
int sum = 0;
for (int number : numbers) {
sum = sum + number;
}
System.out.println("Sum = " + sum);
Output:
Sum = 150
ArrayList.
0, and the last index is
length - 1. Arrays can be one-dimensional or
multi-dimensional and can be traversed using for or
for-each loops.
Strings
Learn how Java stores, creates, compares and manipulates text using Strings.
A String is a sequence of characters used to represent text in Java. Strings are commonly used for storing names, messages, addresses, passwords, email IDs and other textual information.
In Java, String is a class available in the
java.lang package. Strings are also
immutable, which means that once a String object is
created, its original value cannot be changed.
Creating a String
A String can be created by assigning text inside double quotation marks.
String name = "Arun";
System.out.println(name);
Output:
Arun
String Using new Keyword
A String can also be created using the new keyword.
String name = new String("Arun");
System.out.println(name);
Both approaches create String values, but String literals are commonly preferred for normal String usage.
String Concatenation
String concatenation means joining two or more Strings together.
Java uses the + operator to concatenate Strings.
String firstName = "Arun";
String lastName = "Kumar";
String fullName = firstName + " " + lastName;
System.out.println(fullName);
Output:
Arun Kumar
String with Numbers
Strings can also be combined with numbers using the
+ operator.
String name = "Arun";
int age = 22;
System.out.println("Name: " + name);
System.out.println("Age: " + age);
Output:
Name: Arun
Age: 22
String Length
The length() method is used to find the number of characters
in a String.
String name = "Arun";
System.out.println(name.length());
Output:
4
array.length.
For Strings, Java uses string.length().
Accessing String Characters
The charAt() method is used to access a character at a
particular index.
String name = "Arun";
System.out.println(name.charAt(0));
System.out.println(name.charAt(2));
Output:
A
u
String indexing starts from 0.
Converting String to Uppercase
The toUpperCase() method converts all characters in a
String to uppercase.
String name = "arun";
System.out.println(name.toUpperCase());
Output:
ARUN
Converting String to Lowercase
The toLowerCase() method converts all characters in a
String to lowercase.
String name = "ARUN";
System.out.println(name.toLowerCase());
Output:
arun
Comparing Strings
The equals() method is used to compare the actual contents
of two Strings.
String name1 = "Arun";
String name2 = "Arun";
System.out.println(name1.equals(name2));
Output:
true
equals() when you want to compare the contents of
Strings. Do not normally use == to compare String contents,
because == compares object references.
equalsIgnoreCase()
The equalsIgnoreCase() method compares two Strings while
ignoring differences in uppercase and lowercase letters.
String name1 = "Arun";
String name2 = "ARUN";
System.out.println(name1.equalsIgnoreCase(name2));
Output:
true
Comparing Strings Using compareTo()
The compareTo() method compares two Strings lexicographically.
It returns:
0if both Strings are equal.- A negative value if the first String comes before the second.
- A positive value if the first String comes after the second.
String first = "Apple";
String second = "Banana";
System.out.println(first.compareTo(second));
Checking Whether a String Contains Text
The contains() method checks whether a particular sequence
of characters exists inside a String.
String message = "Welcome to Java";
System.out.println(message.contains("Java"));
Output:
true
Checking Start and End of a String
Java provides startsWith() and endsWith()
methods to check the beginning and ending of a String.
String message = "Welcome to Java";
System.out.println(message.startsWith("Welcome"));
System.out.println(message.endsWith("Java"));
Output:
true
true
Removing Extra Spaces
The trim() method removes leading and trailing spaces
from a String.
String name = " Arun ";
System.out.println(name.trim());
Output:
Arun
Extracting Part of a String
The substring() method is used to extract a portion of
a String.
String text = "Welcome";
System.out.println(text.substring(0, 4));
Output:
Welc
The starting index is included, while the ending index is excluded.
Replacing Characters
The replace() method replaces characters or character
sequences with another value.
String message = "I like Python";
message = message.replace("Python", "Java");
System.out.println(message);
Output:
I like Java
Finding the Position of Text
The indexOf() method returns the index of the first
occurrence of a character or String.
String text = "Welcome to Java";
System.out.println(text.indexOf("Java"));
Output:
12
String Immutability
Strings in Java are immutable. This means that once a String object is created, its original value cannot be changed.
String name = "Arun";
name.concat(" Kumar");
System.out.println(name);
Output:
Arun
The concat() operation creates a new String. To store the
result, you need to assign it back to the variable.
String name = "Arun";
name = name.concat(" Kumar");
System.out.println(name);
Output:
Arun Kumar
Common String Methods
| Method | Purpose | Example |
|---|---|---|
length() |
Returns the number of characters | name.length() |
charAt() |
Returns a character at an index | name.charAt(0) |
toUpperCase() |
Converts text to uppercase | name.toUpperCase() |
toLowerCase() |
Converts text to lowercase | name.toLowerCase() |
equals() |
Compares String contents | a.equals(b) |
contains() |
Checks whether text exists | name.contains("Arun") |
substring() |
Extracts part of a String | name.substring(0, 3) |
trim() |
Removes leading and trailing spaces | name.trim() |
replace() |
Replaces characters or text | name.replace("A", "B") |
indexOf() |
Finds the position of text | name.indexOf("A") |
String Example
The following example demonstrates some commonly used String methods.
String name = " Arun Kumar ";
System.out.println("Original: " + name);
System.out.println("Length: " + name.length());
System.out.println("Uppercase: " + name.toUpperCase());
System.out.println("Lowercase: " + name.toLowerCase());
System.out.println("Trimmed: " + name.trim());
System.out.println("Contains Kumar: " + name.contains("Kumar"));
toUpperCase(), replace() and
concat() return a new String instead of modifying the
original String.
length(), charAt(),
equals(), substring(),
contains(), replace(),
trim(), toUpperCase() and
toLowerCase().
OOP Concepts in Java
Understand the fundamental concepts of Object-Oriented Programming in Java.
Object-Oriented Programming, commonly called OOP, is a programming approach where programs are designed using classes and objects. Java is an object-oriented programming language and provides several features to create reusable, maintainable and organized programs.
The main OOP concepts in Java are Class, Object, Encapsulation, Inheritance, Polymorphism and Abstraction.
1. Class
A class is a blueprint or template used to create objects. It defines the data and behaviors that objects can have.
A class can contain variables, constructors and methods.
2. Object
An object is an instance of a class. It represents a real-world entity and can access the variables and methods defined inside the class.
Objects are generally created using the new keyword.
3. Encapsulation
Encapsulation means wrapping data and methods together inside a class and controlling access to the data.
In Java, encapsulation is commonly implemented using
private variables along with public getter and setter
methods.
It helps protect data from direct and unwanted access.
4. Inheritance
Inheritance allows one class to acquire the properties and methods of another class.
The class that provides the properties and methods is called the parent or superclass, while the class that inherits them is called the child or subclass.
Java uses the extends keyword to implement class
inheritance.
5. Polymorphism
Polymorphism means "many forms". It allows the same method name or interface to behave differently depending on the situation.
Java mainly supports two types of polymorphism:
- Compile-time polymorphism – achieved through method overloading.
- Runtime polymorphism – achieved through method overriding.
6. Abstraction
Abstraction means hiding unnecessary implementation details and showing only the important features to the user.
In Java, abstraction can be achieved using abstract classes and interfaces.
Types of OOP Concepts
| Concept | Description |
|---|---|
| Class | A blueprint used to create objects. |
| Object | An instance of a class. |
| Encapsulation | Protects and controls access to data. |
| Inheritance | Allows a class to reuse properties and methods from another class. |
| Polymorphism | Allows the same method or interface to have different behaviors. |
| Abstraction | Hides implementation details and exposes essential functionality. |
One Example Combining OOP Concepts
The following example demonstrates a class, object, encapsulation, inheritance and method overriding.
class Animal {
private String name;
Animal(String name) {
this.name = name;
}
public void sound() {
System.out.println(name + " makes a sound");
}
public String getName() {
return name;
}
}
class Dog extends Animal {
Dog(String name) {
super(name);
}
@Override
public void sound() {
System.out.println(getName() + " barks");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog("Tom");
animal.sound();
}
}
Output:
Tom barks
Exception Handling in Java
Handle runtime errors and prevent programs from terminating unexpectedly.
Exception Handling is a mechanism in Java used to handle errors that occur during the execution of a program. An exception can interrupt the normal flow of a program if it is not handled properly.
Java provides keywords such as try, catch,
finally, throw and throws to
handle exceptions.
Why Is Exception Handling Required?
Errors can occur while a program is running. For example, a program may try to divide a number by zero, access an invalid array index or convert invalid text into a number.
Exception handling allows the program to respond to these situations instead of stopping suddenly.
- Prevents abnormal program termination.
- Handles runtime errors gracefully.
- Separates error-handling code from normal program logic.
- Improves application reliability.
- Helps provide meaningful error messages to users.
Basic try-catch
The try block contains code that may generate an exception.
The catch block is used to handle that exception.
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0;
System.out.println(result);
}
catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
}
}
Output:
Cannot divide by zero
Common Java Exceptions
Java provides many built-in exception classes. Some commonly encountered exceptions are shown below.
| Exception | Common Cause |
|---|---|
ArithmeticException |
Occurs during invalid arithmetic operations such as division by zero. |
ArrayIndexOutOfBoundsException |
Occurs when an invalid array index is accessed. |
NullPointerException |
Occurs when an operation is performed using a null reference. |
NumberFormatException |
Occurs when invalid text is converted into a number. |
StringIndexOutOfBoundsException |
Occurs when an invalid String index is accessed. |
finally Block
The finally block contains code that is intended to execute
after the try and catch processing, whether an
exception occurs or not.
It is commonly used for cleanup operations such as closing resources.
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 2;
System.out.println(result);
}
catch (ArithmeticException e) {
System.out.println("Arithmetic error");
}
finally {
System.out.println("Program completed");
}
}
}
Output:
5
Program completed
throw Keyword
The throw keyword is used to explicitly create and throw
an exception.
It is useful when a program needs to validate a condition and generate an exception when the condition is invalid.
public class Main {
public static void main(String[] args) {
int age = 15;
if (age < 18) {
throw new ArithmeticException("Age must be 18 or above");
}
System.out.println("Eligible to vote");
}
}
throws Keyword
The throws keyword is used in a method declaration to
indicate that the method may pass certain exceptions to its caller.
import java.io.IOException;
public class Main {
static void readFile() throws IOException {
System.out.println("Reading file");
}
public static void main(String[] args) {
try {
readFile();
}
catch (IOException e) {
System.out.println("File error occurred");
}
}
}
Checked and Unchecked Exceptions
Java exceptions are commonly divided into checked exceptions and unchecked exceptions.
| Type | Description | Examples |
|---|---|---|
| Checked Exception | Checked by the compiler. The program must handle or declare them. |
IOException,
SQLException
|
| Unchecked Exception | Occurs during runtime and generally represents programming or input-related errors. |
ArithmeticException,
NullPointerException
|
Exception Handling Keywords
| Keyword | Purpose |
|---|---|
try |
Contains code that may generate an exception. |
catch |
Handles an exception generated inside the try block. |
finally |
Contains cleanup or finalization code. |
throw |
Explicitly throws an exception. |
throws |
Declares exceptions that a method may pass to its caller. |
try for risky code, catch to handle
exceptions, finally for cleanup code,
throw to explicitly generate an exception and
throws to declare exceptions in a method.
try, catch, finally,
throw and throws.
Software Testing & Automation Testing
Understand software testing, automation testing and the basics of Selenium.
Software Testing is the process of checking an application to make sure that it works according to the expected requirements. Testing helps identify bugs, errors and unexpected behavior before an application is released to users.
Testing is an important part of software development because it helps improve the quality, reliability and performance of an application.
Why Is Software Testing Important?
Software testing helps developers and testers identify problems in an application before they affect users. It also helps ensure that new changes do not break existing functionality.
- Finds bugs and errors in the application.
- Verifies that requirements are working correctly.
- Improves application quality and reliability.
- Reduces the risk of failures after deployment.
- Helps ensure that existing features continue to work after changes.
Manual Testing
Manual Testing is a testing process where a tester manually performs test steps without using an automation tool.
For example, a tester can open a login page, enter a username and password, click the login button and verify whether the user is successfully logged in.
Example:
1. Open the login page
2. Enter username
3. Enter password
4. Click Login
5. Verify the result
Automation Testing
Automation Testing uses software tools and scripts to automatically execute test cases and verify application behavior.
Instead of manually repeating the same test steps, an automation script can perform those steps automatically.
Selenium is one of the most widely used tools for automating web browsers.
Manual Testing vs Automation Testing
| Manual Testing | Automation Testing |
|---|---|
| Test cases are executed manually. | Test cases are executed using scripts and tools. |
| Usually requires more manual effort for repetitive tests. | Useful for repetitive test execution. |
| Suitable for exploratory testing. | Suitable for repeated and regression testing. |
| Does not require automation code. | Requires automation scripts and tools. |
| Human verification is involved. | Many verification steps can be automated. |
What Is Selenium?
Selenium is an open-source automation framework used primarily for testing web applications.
Selenium allows automation scripts to interact with web browsers. A script can open a browser, navigate to a website, enter information into forms, click buttons and verify results.
Selenium supports popular browsers such as Chrome, Firefox, Edge and others through their corresponding browser drivers and automation interfaces.
Why Use Selenium?
- Automates web application testing.
- Supports multiple web browsers.
- Supports programming languages such as Java, Python and C#.
- Useful for regression testing.
- Can automate repetitive browser actions.
- Works with testing frameworks such as TestNG.
Selenium Components
Selenium provides several components for different testing and automation requirements.
| Component | Purpose |
|---|---|
| Selenium IDE | Used to record and play back browser interactions. |
| Selenium WebDriver | Used to programmatically control web browsers. |
| Selenium Grid | Used to run tests across multiple browsers and environments. |
Test Case
A test case is a set of steps used to verify a specific feature or behavior of an application.
For example, a login test case can verify whether a user can successfully log in using valid credentials.
| Step | Action | Expected Result |
|---|---|---|
| 1 | Open login page | Login page should be displayed. |
| 2 | Enter username | Username should be entered. |
| 3 | Enter password | Password should be entered. |
| 4 | Click Login | User should be logged in. |
| 5 | Verify dashboard | Dashboard should be displayed. |
Regression Testing
Regression Testing is performed after changes are made to an application to ensure that existing features still work correctly.
Automation is particularly useful for regression testing because the same set of test cases may need to be executed repeatedly after every application change.
Selenium with Java
Selenium WebDriver can be used with Java to create browser automation programs. The Java program communicates with the browser through Selenium WebDriver.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Test {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
System.out.println(driver.getTitle());
driver.quit();
}
}
In this example, Selenium starts a Chrome browser, opens Google, prints the page title and then closes the browser.
Basic Selenium Testing Flow
A typical Selenium automation test follows a sequence of steps:
Start
↓
Launch Browser
↓
Open Web Application
↓
Find Web Element
↓
Perform Action
↓
Verify Result
↓
Close Browser
↓
End
Common Testing Types
| Testing Type | Purpose |
|---|---|
| Functional Testing | Checks whether application features work according to requirements. |
| Regression Testing | Ensures existing functionality still works after changes. |
| Smoke Testing | Performs basic checks to determine whether a build is stable enough for further testing. |
| Integration Testing | Checks whether different components or modules work correctly together. |
| System Testing | Tests the complete application as an integrated system. |
Selenium IDE
Record, create and execute browser automation tests without writing extensive code.
Selenium IDE is a browser-based tool used to create and execute automated tests for web applications. It provides a graphical interface that allows testers to record their actions in a browser and replay them later.
Selenium IDE is especially useful for beginners because basic automation tests can be created without writing a complete programming language-based automation framework.
What Is Selenium IDE?
Selenium IDE stands for Selenium Integrated Development Environment. It is available as a browser extension and can be used to record interactions with web applications.
For example, Selenium IDE can record actions such as opening a website, clicking a button, entering text into a textbox and verifying information displayed on a page.
Why Use Selenium IDE?
- Easy to learn for beginners.
- Allows browser actions to be recorded.
- Tests can be replayed multiple times.
- Provides a graphical interface for creating tests.
- Useful for quickly creating simple automation tests.
- Can be used to understand Selenium automation concepts.
Installing Selenium IDE
Selenium IDE is installed as a browser extension. After installing the extension, it can be opened from the browser's extension or toolbar area.
The basic setup process is:
1. Open a supported web browser
2. Open the browser extension store
3. Search for Selenium IDE
4. Install the Selenium IDE extension
5. Open Selenium IDE
6. Create a new project
7. Start creating test cases
Creating a Selenium IDE Project
A Selenium IDE project is used to organize related test cases. After opening Selenium IDE, you can create a new project and provide a name for the project.
Project
↓
Test Suite
↓
Test Case
↓
Commands
↓
Execution
Recording a Test
Selenium IDE can record actions performed in the browser. When recording is enabled, actions such as clicking links, entering text and navigating between pages can be captured as test commands.
A basic recording process can be represented as:
Start Recording
↓
Open Website
↓
Enter Data
↓
Click Button
↓
Verify Result
↓
Stop Recording
Selenium IDE Commands
Selenium IDE represents browser actions using commands. These commands describe what the test should perform.
| Command | Purpose | Example |
|---|---|---|
open |
Opens or navigates to a web page. | open |
click |
Clicks a web element. | click |
type |
Enters text into an input field. | type |
select |
Works with selectable options. | select |
assert |
Checks whether an expected condition is true. | assert title |
verify |
Checks a condition while allowing the test to continue. | verify text |
waitForElementPresent |
Waits until an element is present. | waitForElementPresent |
Target
The Target identifies the web element on which a Selenium IDE command should operate.
For example, a target can identify a textbox, button, link or another element on a web page.
Command Target
--------------------------------
click id=loginButton
type id=username
click id=submit
Value
The Value contains the data that should be provided to a command when required.
For example, when using a type command, the value can contain the text that should be entered into an input field.
Command Target Value
------------------------------------------
type id=username Arun
type id=password password123
Example Login Test
A simple login test can contain commands that open a login page, enter credentials and click the login button.
Command Target Value
------------------------------------------------
open /login
type id=username Arun
type id=password password123
click id=loginButton
Selenium IDE executes these commands sequentially and performs the corresponding actions in the browser.
Assertions and Verification
Testing is not only about performing actions. We also need to check whether the application produces the expected result.
Selenium IDE provides assertion and verification commands for checking conditions on a web page.
Action:
Enter username
↓
Action:
Enter password
↓
Action:
Click Login
↓
Verification:
Dashboard should be displayed
Running a Test
After creating a test case, it can be executed using the run option in Selenium IDE. Selenium IDE performs the recorded commands in the browser and reports the result of the test.
Test Case
↓
Run Test
↓
Execute Commands
↓
Perform Browser Actions
↓
Verify Results
↓
Test Result
Test Suite
A Test Suite is a collection of related test cases. Instead of running individual test cases separately, related tests can be organized into a suite.
Test Suite
│
├── Login Test
├── Registration Test
├── Search Test
└── Logout Test
Advantages of Selenium IDE
- Simple graphical user interface.
- Easy for beginners to understand.
- Supports recording and playback.
- Useful for creating simple browser automation tests.
- Helps beginners understand Selenium commands and locators.
Limitations of Selenium IDE
- Not intended to replace full automation frameworks for complex projects.
- Complex test logic may require programming-based automation.
- Large test suites can become difficult to maintain.
- Advanced automation generally uses Selenium WebDriver with a programming language.
Selenium IDE vs Selenium WebDriver
| Selenium IDE | Selenium WebDriver |
|---|---|
| GUI-based automation tool. | Programming-based browser automation API. |
| Easy for beginners. | Requires programming knowledge. |
| Supports recording and playback. | Tests are written using programming languages. |
| Suitable for simple automation. | Suitable for larger and more complex automation projects. |
| Limited programming flexibility. | Provides greater flexibility and control. |
Basic Selenium IDE Workflow
Install Selenium IDE
↓
Create Project
↓
Create Test Suite
↓
Create Test Case
↓
Record Actions
↓
Add Commands
↓
Add Assertions
↓
Run Test
↓
Verify Result
open, click,
type, assert and verify.
Tests can be recorded, edited and executed directly through the IDE.
Selenium WebDriver
Automate web browsers and test web applications using Selenium WebDriver with Java.
Selenium WebDriver is a browser automation tool used to control web browsers programmatically. It allows testers to automate actions such as opening websites, clicking buttons, entering text, selecting options and verifying web page behavior.
Selenium WebDriver can be used with programming languages such as Java, Python and C#. In this course, we use Java with Selenium WebDriver.
Why Use Selenium WebDriver?
Selenium WebDriver is useful when browser-based tests need to be executed repeatedly and automatically.
- Automates web browser actions.
- Supports multiple browsers.
- Works with Java and other programming languages.
- Useful for functional and regression testing.
- Provides greater control than Selenium IDE.
- Can be integrated with testing frameworks such as TestNG.
Selenium WebDriver Architecture
WebDriver acts as an interface between the Java automation program and the browser. The Java program sends commands through Selenium WebDriver, which communicates with the appropriate browser automation component.
Java Program
↓
Selenium WebDriver
↓
Browser Driver
↓
Web Browser
↓
Web Application
Selenium WebDriver Setup
To use Selenium WebDriver with Java, you need a Java development
environment and Selenium libraries. In a Maven project, Selenium can be
added as a dependency in the pom.xml file.
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.x.x</version>
</dependency>
The exact Selenium version should be selected based on the version being used in your project.
Creating a WebDriver Object
The WebDriver interface provides methods for controlling a
browser. A browser-specific driver, such as ChromeDriver,
can be used to create the WebDriver object.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Main {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
}
}
Opening a Website
The get() method is used to open a URL in the browser.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Main {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
}
}
Getting the Page Title
The getTitle() method returns the title of the currently
opened web page.
String title = driver.getTitle();
System.out.println(title);
Getting the Current URL
The getCurrentUrl() method returns the URL of the current
web page.
String url = driver.getCurrentUrl();
System.out.println(url);
Finding Web Elements
A web page contains elements such as text boxes, buttons, links, checkboxes and dropdowns. Selenium uses locators to identify these elements.
The findElement() method is commonly used to locate a single
element on a web page.
WebElement username =
driver.findElement(By.id("username"));
Selenium Locators
Selenium provides different locator strategies for identifying elements on a web page.
| Locator | Purpose | Example |
|---|---|---|
id |
Finds an element using its ID. | By.id("username") |
name |
Finds an element using its name attribute. | By.name("email") |
className |
Finds an element using its class name. | By.className("btn") |
tagName |
Finds an element using its HTML tag. | By.tagName("input") |
linkText |
Finds a link using its visible text. | By.linkText("Login") |
cssSelector |
Finds an element using a CSS selector. | By.cssSelector("#username") |
xpath |
Finds an element using XPath. | By.xpath("//input[@id='username']") |
Entering Text
The sendKeys() method is used to enter text into a text box
or another input element.
WebElement username =
driver.findElement(By.id("username"));
username.sendKeys("Arun");
Clicking an Element
The click() method is used to click buttons, links,
checkboxes and other clickable elements.
WebElement loginButton =
driver.findElement(By.id("login"));
loginButton.click();
Getting Text from an Element
The getText() method returns the visible text of a web
element.
WebElement message =
driver.findElement(By.id("message"));
String text = message.getText();
System.out.println(text);
Browser Navigation
Selenium provides navigation methods for moving between web pages.
driver.navigate().to("https://www.google.com");
driver.navigate().back();
driver.navigate().forward();
driver.navigate().refresh();
Closing the Browser
Selenium provides two commonly used methods for closing browser windows.
-
close()closes the current browser window. -
quit()closes all browser windows opened by WebDriver and ends the WebDriver session.
driver.quit();
Complete Selenium WebDriver Example
The following example demonstrates creating a WebDriver object, opening a website, getting the title and closing the browser.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Main {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
System.out.println("Title: " + driver.getTitle());
driver.quit();
}
}
Basic WebDriver Workflow
Create WebDriver
↓
Launch Browser
↓
Open Website
↓
Find Web Element
↓
Perform Action
↓
Verify Result
↓
Close Browser
Common WebDriver Methods
| Method | Purpose |
|---|---|
get() |
Opens a specified URL. |
getTitle() |
Returns the current page title. |
getCurrentUrl() |
Returns the current page URL. |
findElement() |
Finds a web element. |
click() |
Clicks an element. |
sendKeys() |
Enters text into an element. |
getText() |
Returns visible text from an element. |
close() |
Closes the current browser window. |
quit() |
Closes the browser session and all associated windows. |
WebDriver provides the interface, while classes such as
ChromeDriver are used to control a specific browser.
Handling Events in Selenium
Perform and automate user interactions such as clicks, typing, keyboard actions and mouse movements.
In Selenium WebDriver, handling events means automating the actions that a user normally performs on a web page. These actions include clicking buttons, entering text, selecting elements, moving the mouse and using keyboard keys.
Selenium provides methods through WebElement and the
Actions class to perform different types of browser
interactions.
Click Event
The click() method is used to simulate a mouse click on a
web element such as a button, link or checkbox.
WebElement button =
driver.findElement(By.id("login"));
button.click();
Typing Text
The sendKeys() method is used to enter text into input
fields such as username, password and search boxes.
WebElement username =
driver.findElement(By.id("username"));
username.sendKeys("Arun");
Clearing Text
The clear() method removes the existing text from an input
field before new information is entered.
WebElement username =
driver.findElement(By.id("username"));
username.clear();
username.sendKeys("Arun");
Keyboard Events
Selenium provides keyboard keys through the Keys class.
These keys can be used with sendKeys() to simulate keyboard
actions.
import org.openqa.selenium.Keys;
WebElement search =
driver.findElement(By.name("q"));
search.sendKeys("Selenium");
search.sendKeys(Keys.ENTER);
Mouse Actions
The Actions class is used for advanced mouse and keyboard
interactions. It can perform actions such as mouse movement, double
clicking, right clicking and dragging elements.
import org.openqa.selenium.interactions.Actions;
Actions actions = new Actions(driver);
WebElement button =
driver.findElement(By.id("button"));
actions.moveToElement(button).click().perform();
Double Click
The doubleClick() method performs a double-click action on
a web element.
Actions actions = new Actions(driver);
WebElement element =
driver.findElement(By.id("item"));
actions.doubleClick(element).perform();
Right Click
The contextClick() method performs a right-click action on
a web element.
Actions actions = new Actions(driver);
WebElement element =
driver.findElement(By.id("item"));
actions.contextClick(element).perform();
Mouse Hover
Mouse hover is used when an element displays additional information or a menu when the mouse pointer is moved over it.
Actions actions = new Actions(driver);
WebElement menu =
driver.findElement(By.id("menu"));
actions.moveToElement(menu).perform();
Drag and Drop
The dragAndDrop() method can be used to move an element
from one location to another.
Actions actions = new Actions(driver);
WebElement source =
driver.findElement(By.id("source"));
WebElement target =
driver.findElement(By.id("target"));
actions.dragAndDrop(source, target).perform();
Keyboard Shortcut
Selenium can also perform keyboard combinations such as
CTRL + A and CTRL + C.
WebElement textbox =
driver.findElement(By.id("textbox"));
textbox.sendKeys("Selenium");
textbox.sendKeys(Keys.CONTROL, "a");
Form Submission
The submit() method can be used with form elements to
submit a form. In modern Selenium code, clicking the appropriate submit
button is also commonly used.
WebElement form =
driver.findElement(By.id("loginForm"));
form.submit();
Common Event Handling Methods
| Method | Purpose |
|---|---|
click() |
Clicks an element. |
sendKeys() |
Enters text or sends keyboard keys. |
clear() |
Clears text from an input field. |
moveToElement() |
Moves the mouse pointer to an element. |
doubleClick() |
Performs a double-click. |
contextClick() |
Performs a right-click. |
dragAndDrop() |
Drags an element and drops it onto another element. |
submit() |
Submits a form. |
Complete Event Handling Example
The following example demonstrates entering text, using a keyboard key and clicking a button.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.Keys;
import org.openqa.selenium.chrome.ChromeDriver;
public class EventExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
WebElement search =
driver.findElement(By.name("q"));
search.sendKeys("Selenium WebDriver");
search.sendKeys(Keys.ENTER);
driver.quit();
}
}
Event Handling Workflow
Open Browser
↓
Open Web Page
↓
Find Web Element
↓
Perform User Action
↓
Click / Type / Hover / Keyboard
↓
Verify Result
↓
Close Browser
WebElement methods. For advanced mouse and keyboard
interactions, Selenium provides the Actions class.
TestNG Framework
Organize, execute and manage Selenium automation tests using TestNG.
TestNG is a testing framework for Java that is commonly used with Selenium WebDriver to create, organize and execute automated test cases.
TestNG provides useful features such as annotations, test execution, grouping, prioritization, assertions, parameterization and test reports. It helps make Selenium automation projects easier to maintain and manage.
Why Use TestNG?
Selenium WebDriver is mainly responsible for browser automation, while TestNG provides the testing structure needed to organize and execute those automated tests.
- Organizes test cases.
- Provides test annotations.
- Supports test priorities.
- Supports grouping of test cases.
- Provides assertions for verification.
- Supports running multiple tests.
- Generates test execution reports.
- Works well with Selenium WebDriver.
TestNG with Selenium
Selenium WebDriver performs browser actions, while TestNG controls the test execution process.
TestNG
↓
Test Method
↓
Selenium WebDriver
↓
Browser
↓
Web Application
↓
Assertion
↓
Test Result
Installing TestNG
In a Java Maven project, TestNG can be added as a dependency in the
pom.xml file.
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.x.x</version>
<scope>test</scope>
</dependency>
After adding the dependency, Maven downloads the required TestNG library automatically.
First TestNG Test
A TestNG test method is created using the @Test annotation.
The method containing this annotation is executed as a test case.
import org.testng.annotations.Test;
public class FirstTest {
@Test
public void testMessage() {
System.out.println("Welcome to TestNG");
}
}
TestNG Annotations
Annotations tell TestNG when and how a particular method should be executed.
| Annotation | Purpose |
|---|---|
@Test |
Marks a method as a test case. |
@BeforeMethod |
Runs before each test method. |
@AfterMethod |
Runs after each test method. |
@BeforeClass |
Runs before the first test method in a class. |
@AfterClass |
Runs after all test methods in a class. |
@BeforeSuite |
Runs before the test suite. |
@AfterSuite |
Runs after the test suite. |
TestNG Test Lifecycle
TestNG annotations can be used to control the setup and cleanup process around test methods.
@BeforeSuite
↓
@BeforeClass
↓
@BeforeMethod
↓
@Test
↓
@AfterMethod
↓
@AfterClass
↓
@AfterSuite
Using TestNG with Selenium
TestNG can be combined with Selenium WebDriver to create automated browser tests. The browser can be started before the test and closed after the test using TestNG annotations.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class LoginTest {
WebDriver driver;
@BeforeMethod
public void setup() {
driver = new ChromeDriver();
driver.get("https://www.google.com");
}
@Test
public void verifyTitle() {
System.out.println(driver.getTitle());
}
@AfterMethod
public void tearDown() {
driver.quit();
}
}
Assertions
Assertions are used to compare the actual result with the expected result. They help determine whether a test case has passed or failed.
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestExample {
@Test
public void verifyTitle() {
String actualTitle = "Google";
String expectedTitle = "Google";
Assert.assertEquals(actualTitle, expectedTitle);
}
}
If the actual and expected values are equal, the assertion passes. Otherwise, the test case fails.
Common TestNG Assertions
| Assertion | Purpose |
|---|---|
assertEquals() |
Checks whether two values are equal. |
assertNotEquals() |
Checks whether two values are different. |
assertTrue() |
Checks whether a condition is true. |
assertFalse() |
Checks whether a condition is false. |
assertNull() |
Checks whether a value is null. |
assertNotNull() |
Checks whether a value is not null. |
Test Priority
The priority attribute can be used to control the execution
order of test methods.
@Test(priority = 1)
public void loginTest() {
System.out.println("Login Test");
}
@Test(priority = 2)
public void searchTest() {
System.out.println("Search Test");
}
@Test(priority = 3)
public void logoutTest() {
System.out.println("Logout Test");
}
Grouping Tests
TestNG allows related test cases to be placed into groups. This is useful when a project contains many test cases and only a specific category of tests needs to be executed.
@Test(groups = {"Login"})
public void validLogin() {
System.out.println("Valid Login");
}
@Test(groups = {"Login"})
public void invalidLogin() {
System.out.println("Invalid Login");
}
TestNG XML File
A TestNG XML file can be used to configure and organize test suites and test classes. It is commonly used when multiple test classes need to be executed together.
<?xml version="1.0" encoding="UTF-8"?>
<suite name="Automation Suite">
<test name="Login Tests">
<classes>
<class name="LoginTest"/>
</classes>
</test>
</suite>
Running TestNG Tests
TestNG tests can be executed from an IDE such as Visual Studio Code or other Java development environments depending on the configured Java and TestNG support. Maven can also be used to execute tests in a project.
mvn test
TestNG Test Flow
Start Test Suite
↓
Run Setup
↓
Launch Browser
↓
Execute @Test
↓
Perform Selenium Actions
↓
Verify Using Assertions
↓
Close Browser
↓
Generate Test Result
Advantages of TestNG
- Easy integration with Selenium WebDriver.
- Provides powerful annotations.
- Supports test prioritization.
- Supports test grouping.
- Provides assertions.
- Supports test suites.
- Can execute multiple test cases.
- Provides test execution reports.
Selenium WebDriver and TestNG
| Selenium WebDriver | TestNG |
|---|---|
| Automates the browser. | Manages test execution. |
| Finds and interacts with web elements. | Organizes test cases. |
| Performs browser actions. | Provides assertions and annotations. |
| Controls Chrome, Firefox and other browsers. | Controls how and when tests are executed. |
Jenkins
Automate software builds, testing and deployment using Jenkins.
Jenkins is an open-source automation server used to automate different stages of the software development process. It is widely used for Continuous Integration (CI) and Continuous Delivery (CD).
Jenkins can automatically build an application, execute test cases, generate reports and deploy the application whenever new changes are added to a source-code repository.
Why Use Jenkins?
In a software project, developers frequently make changes to the source code. Manually building and testing the application after every change can take time and may result in errors.
Jenkins automates these tasks so that the application can be built and tested automatically whenever changes are committed.
- Automates application builds.
- Runs automated test cases.
- Detects build and test failures.
- Integrates with Git and GitHub.
- Supports Continuous Integration and Continuous Delivery.
- Can automate application deployment.
- Provides build and test reports.
Continuous Integration
Continuous Integration, commonly called CI, is a development practice where developers frequently integrate their code changes into a shared repository.
Jenkins can automatically detect these changes, build the application and execute automated tests.
Developer
↓
Write Code
↓
Git / GitHub
↓
Jenkins
↓
Build Application
↓
Run Tests
↓
Test Result
Continuous Delivery
Continuous Delivery, commonly called CD, extends the CI process by preparing an application for release or deployment after successful builds and tests.
Code
↓
Build
↓
Test
↓
Package
↓
Deploy
↓
Application
Jenkins Installation
Jenkins requires Java because Jenkins runs on the Java platform. Before installing Jenkins, make sure a supported JDK is installed and available on your system.
After installing Java, Jenkins can be installed and configured on the development machine or on a dedicated server.
Jenkins Dashboard
After Jenkins is started, the Jenkins dashboard provides a central place to create and manage jobs, view build history, check test results and monitor the status of automation tasks.
Jenkins Dashboard
↓
Create Job
↓
Configure Source Code
↓
Configure Build
↓
Run Job
↓
View Build Result
Jenkins Job
A Jenkins job defines the tasks that Jenkins should perform. A job can contain source-code configuration, build commands, test commands and post-build actions.
For example, a Selenium project can use a Jenkins job to download the latest source code, build the project and execute TestNG test cases.
Creating a Jenkins Job
A basic Jenkins job can be created from the Jenkins dashboard. Select New Item, provide a name and choose the required project type.
Jenkins Dashboard
↓
New Item
↓
Enter Job Name
↓
Select Project Type
↓
Configure Job
↓
Save
↓
Build
Connecting Jenkins with Git
Jenkins can connect to Git repositories such as GitHub. The repository contains the source code that Jenkins needs to build and test.
GitHub Repository
↓
Jenkins
↓
Clone Source Code
↓
Build Project
↓
Run Tests
Build Commands
Jenkins can execute commands during a build. For a Java Maven project, commonly used commands include:
mvn clean
mvn test
mvn package
mvn clean removes previous build files,
mvn test executes the test cases, and
mvn package packages the application after a successful
build.
Jenkins with Selenium and TestNG
Jenkins can be integrated with Selenium WebDriver and TestNG to automate browser testing. Jenkins can trigger the automation suite and collect the test results.
Developer
↓
GitHub
↓
Jenkins
↓
Maven Build
↓
TestNG
↓
Selenium WebDriver
↓
Browser
↓
Test Result
↓
Jenkins Report
Jenkins Pipeline
A Jenkins Pipeline defines the complete automation workflow as a series of stages. It can include source-code checkout, building, testing and deployment.
Pipeline
↓
Checkout
↓
Build
↓
Test
↓
Package
↓
Deploy
Basic Jenkinsfile
A Jenkinsfile is a text file that defines a Jenkins
Pipeline. It can be stored together with the application source code.
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'mvn clean package'
}
}
stage('Test') {
steps {
sh 'mvn test'
}
}
}
}
On Windows-based Jenkins agents, build commands may use Windows command
syntax instead of the Unix-style sh step shown above.
Build Status
Jenkins displays the result of each build. A successful build means the configured build and test stages completed successfully, while a failed build indicates that one or more stages encountered a problem.
| Status | Meaning |
|---|---|
| Success | The build completed successfully. |
| Failure | A build step or test failed. |
| Unstable | The build completed but has test or quality problems. |
| Aborted | The build was stopped before completion. |
Jenkins Automation Workflow
Developer Pushes Code
↓
GitHub
↓
Jenkins
↓
Checkout Code
↓
Build Code
↓
Run TestNG Tests
↓
Selenium WebDriver Tests
↓
Generate Results
↓
Deploy Application
Advantages of Jenkins
- Open-source automation server.
- Supports Continuous Integration and Continuous Delivery.
- Integrates with Git and GitHub.
- Works with Maven and Java projects.
- Can execute Selenium and TestNG automation tests.
- Provides build history and test results.
- Supports pipeline-based automation.
- Can automate deployment processes.
Jenkins in Automation Testing
| Tool | Purpose |
|---|---|
| Git / GitHub | Stores and manages source code. |
| Maven | Builds the Java project and manages dependencies. |
| Selenium WebDriver | Automates web browsers. |
| TestNG | Organizes and executes test cases. |
| Jenkins | Automates the complete build and testing workflow. |