Interface in Java

HOME

In this tutorial, I’ll explain about Interfaces in Java.

What is Interface?

An interface is a group of related methods with empty bodies (abstract methods).

  1. All the methods in Interface are public and abstract. 
  2. A class can implement more than one interface.
  3. An interface can extends another interface or interfaces 
  4. A class that implements interface must implements all the methods in interface. To implement interface use implements keyword.
  5. The variables declared in an interface are public, static & final by default.
  6. Java does not support multiple inheritance in case of class, but by using interface it can achieve multiple inheritance .

Syntax of Interface

interface test {
//declare methods which are abstract by default
//declare variables which are public, static, final by default
}

Relationship between Class and Interfaces

Below is an example of implementation of Interface. I have declared a class as Interface which have two abstract methods.

public interface MyInterface {

	// Abstract methods
	public void method1();

	public void method2();
}

Interface Implementation

public class InterfaceTest implements MyInterface {

	public void method1() {
		System.out.println("Implementation of Method 1");
	}

	public void method2() {
		System.out.println("Implementation of Method 2");
	}

	public static void main(String[] args) {
		MyInterface interTest = new InterfaceTest();
		interTest.method1();
		interTest.method2();

	}
}

Output

Implementation of Method 1
Implementation of Method 2

Multiple Interface

In the below example, Interface 2 extends Interface 1 and class implements Interface 2.

Interface 1

public interface Infa1 {
	public void method1();

}

Interface 2

public interface Infa2 extends Infa1 {
	public void method2();

}

MultipleInterfaceTest Class

public class MultipleInterfaceTest implements Infa2 {

	public void method1() {
		System.out.println("Implementation of Method 1");
	}

	public void method2() {
		System.out.println("Implementation of Method 2");
	}

	public static void main(String[] args) {

		Infa2 obj = new MultipleInterfaceTest();
		obj.method1();
		obj.method2();
	}

}

Output

Implementation of Method 1
Implementation of Method 2

Multiple Inheritance

Interface supports multiple Inheritance. Here, there are two interfaces which are implemented in class MultipleInheritanceTest.

Interface 1

public interface Infa1 {
	public void method();

}

Interface 2

public interface Infa2 {
	public void method();

}

MultipleInheritanceTest Class

public class MultipleInheritanceTest implements Infa1, Infa2 {

	public void method() {
		System.out.println("Implementation of Method ");
	}


	public static void main(String[] args) {
		MultipleInheritanceTest test = new MultipleInheritanceTest();
		test.method();
	}

}

Output

Implementation of Method

Abstraction in Java

HOME

In this tutorial, I’ll explain about abstraction in Java.

What is Abstraction?

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

There are two ways to achieve abstraction in java

  1. Abstract class
  2. Interface

What is an Abstract Class?

A class which is declared as abstract is known as an abstract class.

  1. It can have abstract and non-abstract methods.
  2. It needs to be extended and its method is implemented.
  3. It cannot be instantiated.
  4. It can have constructors and static methods also.
  5. It can have final methods which will force the subclass not to change the body of the method.
  6. An abstract class is a class that contains at least one abstract method.
  7. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract.

Example of Abstract Class

abstract class Test
{
}

What is Abstract Method?

An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:

abstract int test(int a, int b);

Below is an example of abstraction.

Abstract Class

//Abstract Class
public abstract class Bank {

	// Abstract method
	abstract void getRateOfInterest();
}

SubClass1

//Subclass (inherit from Bank)
public class SBI extends Bank {

	// The body of getRateOfInterest is declared here
	public void getRateOfInterest() {

		System.out.println("Interest Rate of SBI Bank :" + 5.3);

	}
}

SubClass2

//Subclass (inherit from Bank)
public class BOI extends Bank {

	// The body of getRateOfInterest is declared here
	public void getRateOfInterest() {

		System.out.println("Interest Rate of BOI Bank :" + 4.1);

	}

}

Test Class

public class AbstractionTest {

	public static void main(String[] args) {

		Bank bank1 = new SBI();
		bank1.getRateOfInterest();

		Bank bank2 = new BOI();
		bank2.getRateOfInterest();

	}

}

Output

Interest Rate of SBI Bank :5.3
Interest Rate of BOI Bank :4.1

Abstract class can have a data member, constructor, abstract method, non abstract method and even main() method.

Below is an example where the abstract class has both abstract method as well as non abstract method.

public abstract class Bike { // abstract class

	int x = 25; // Instance Variable

	Bike() // Constructor
	{
		int y = 10;

		System.out.println("Value of y :" + y);
		System.out.println("Bike is created");

	}

	abstract void run(); // abstract method

	void change_gear() // non abstract method
	{
		System.out.println("Gear is changed");
	}

}

SubClass

public class Trek extends Bike {

	void run() {
		System.out.println("Bike is running");
	}

}

Test Class

public class AbstractionDemoTest {

	public static void main(String[] args) {

		Bike bike = new Trek();
		bike.run();
		bike.change_gear();

		System.out.println("Value of x :" + bike.x);

	}
}

Output

Value of y :10
Bike is created
Bike is running
Gear is changed
Value of x :25

Advantages of Abstraction

  1. It reduces the complexity of viewing the things.
  2. Avoids code duplication and increases reusability.
  3. Helps to increase security of an application or program as only important details are provided to the user.

Encapsulation in Java

HOME

Encapsulation in Java is a process of wrapping the data and code in a single unit. The whole idea behind encapsulation is to hide the implementation details from users. If a data member is private it means it can only be accessed within the same class. No outside class can access private data member (variable) of other class. It is one of the four important OOPs concept.

To achieve encapsulation in Java −

  • Declare the variables of a class as private.
  • Provide public setter and getter methods to modify and view the variables values.

The get method returns the variable value, and the set method sets the value.

Syntax of get method – method name starts with get followed by the variable name where first letter is capital.

Syntax of set method – method name starts with set followed by the variable name where first letter is capital.

Below is an example of encapsulation with two variables and their getter and setter method.

public class EncapsulationDemo {

	// private variables
	private String name;
	private int age;

	// getter method for age
	public int getAge() {
		return age;
	}

	// setter method for age
	public void setAge(int setAge) {
		this.age = setAge;

	}

	// getter method for name
	public String getName() {
		return name;
	}

	// setter method for name
	public void setName(String newName) {
		this.name = newName;
	}

}

The variables of the EncapsulationDemo class can be accessed using the following program −

public class EncapsulationTest {

	public static void main(String[] args) {

		//creating instance of the encapsulated class
		EncapsulationDemo encap = new EncapsulationDemo();

		//setting value in the age member 
		encap.setAge(25);
		
		//setting value in the name member 
		encap.setName("Terry");

		//getting value of the age and name member  
		System.out.print("Name : " + encap.getName() + " and Age :" + encap.getAge());

	}

}

Output

Name : Terry  and Age :25

The encapsulate class is easy to test. So, it is better for unit testing.

The standard IDE’s are providing the facility to generate the getters and setters. So, it is easy and fast to create an encapsulated class in Java.

Inheritance in Java

HOME

Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another class.

The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class).

Inheritance is applicable for public and protected members only. Private members can’t be inherited.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.

The keyword used for inheritance is extends

Syntax

class derived-class extends base class
{
//methods and variables
}

Below is an example of Inheritance. In the below example, ParentCalculation is the Base class (parent class) and has a method addition. ChildCaclculation is the derived class (child class) which has extends base class ParentCalculation. When an object of ChildCaclculation class is created, a copy of all methods and fields of the superclass acquire memory in this object. That is why by using the object of the subclass we can also access the members of a superclass. 

Base Class

public class ParentCalculation {

	int z;

	public void addition(int x, int y) {
		z = x + y;
		System.out.println("The sum of the given numbers:" + z);
	}

}

Derived Class

public class ChildCaclculation extends ParentCalculation {

	int c;

	public void multiplication(int a, int b) {
		c = a * b;
		System.out.println("The multiplication of the given numbers:" + c);
	}

	public static void main(String[] args) {
		ChildCaclculation cal = new ChildCaclculation();
		cal.addition(10, 14);
		cal.multiplication(5, 6);

	}

}

Output

The sum of the given numbers:24
The multiplication of the given numbers:30

Types of Inheritance in Java

Below are the different types of inheritance available in Java. 

1. Single Inheritance

In single inheritance, subclass (derived) inherit the features of superclass (base). In the image below, class A serves as a base class for the derived class B.

Base Class

public class Employee {

	String name = "Tom";
	int emp_no = 12001;

	public void displayEmployee() {
		System.out.println("Base Class");

		System.out.println("Name :" + name);
		System.out.println("Emp_No :" + emp_no);
	}
}

Derived Class

package JavaDemo.Inheritance;

public class Department extends Employee {

	String deptName = "IT Division";

	public void displayDept() {
		System.out.println("Derived Class");

		System.out.println("Department Name :" + deptName);
	}

	public static void main(String[] args) {

		Department dept = new Department();

		// Derived method
		dept.displayDept();

		// Base Method
		dept.displayEmployee();

	}

}

Output

Derived Class
Department Name :IT Division
Base Class
Name :Tom
Emp_No :12001

2. Multilevel Inheritance

In this, derived class extends an base class as well as the derived class act as a base class for another derived class. In the below example, Employee is Base class, Department is intermediate derived class and SubDivision is derived class.

Base Class

package JavaDemo.Inheritance;

public class Employee {

	String name = "Tom";
	int emp_no = 12001;

	public void displayEmployee() {
		System.out.println("Base Class");

		System.out.println("Name :" + name);
		System.out.println("Emp_No :" + emp_no);
	}
}

Intermediate Derived Class

package JavaDemo.Inheritance;

public class Department extends Employee {

	String deptName = "IT Division";

	public void displayDept() {
		System.out.println("Intermediate Derived Class");

		System.out.println("Department Name :" + deptName);
	}

	public static void main(String[] args) {

		Department dept = new Department();

		// Intermediate Derived method
		dept.displayDept();

		// Base Method
		dept.displayEmployee();

	}

}

Derived Class

package JavaDemo.Inheritance;

public class SubDivision extends Department {

	String sub_division = "Production Support";

	public void displaySubDivision() {
		System.out.println("Derived Class");

		System.out.println("SubDivision Name :" + sub_division);
	}

	public static void main(String[] args) {

		SubDivision div = new SubDivision();

		// Derived method
		div.displaySubDivision();

		// Intermediate Derived method
		div.displayDept();

		// Base Method
		div.displayEmployee();

	}

}

Output

Derived Class
SubDivision Name :Production Support
Intermediate Derived Class
Department Name :IT Division
Base Class
Name :Tom
Emp_No :12001

3.  Hierarchical Inheritance

In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclasses.

In the below example, Employee is the base class. Department and Salary are the derived classes.

Base Class

package JavaDemo.Inheritance;

public class Employee {

	String name = "Tom";
	int emp_no = 12001;

	public void displayEmployee() {
		System.out.println("Base Class");

		System.out.println("Name :" + name);
		System.out.println("Emp_No :" + emp_no);
	}
}

Derived Class1

public class Department extends Employee {

	String deptName = "IT Division";

	public void displayDept() {
		System.out.println("Derived Class 1");

		System.out.println("Department Name :" + deptName);
	}

	public static void main(String[] args) {

		Department dept = new Department();

		// Derived method
		dept.displayDept();

		// Base Method
		dept.displayEmployee();

	}

}

Derived Class2

package JavaDemo.Inheritance;

public class Salary extends Employee {

	float Salary = 65000;

	public void displaySalary() {
		System.out.println("Derived Class 2");
		System.out.println("Salary :" + Salary);
	}

	public static void main(String[] args) {

		Salary sal = new Salary();
		sal.displaySalary();
		sal.displayEmployee();

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

		Department dept = new Department();
		dept.displayDept();
		dept.displayEmployee();

	}

}

Output

Derived Class 2
Salary :65000.0
Base Class
Name :Tom
Emp_No :12001
=========================
Derived Class 1
Department Name :IT Division
Base Class
Name :Tom
Emp_No :12001

4. Multiple Inheritance

In Multiple inheritances, one class can have more than one superclass and inherit features from all parent classes. Java does not support multiple inheritances with classes. We can achieve multiple inheritances only through Interfaces.

5. Hybrid Inheritance

 It is a combination of single and multiple inheritance. As Java doesn’t support multiple inheritances with classes, hybrid inheritance is also not possible with classes. In java, we can achieve hybrid inheritance only through Interfaces.

Multiple Catch Exceptions

HOME

In the previous tutorial, I have explained about the control flow of try catch and finally blocks in Java. In this tutorial, I’ll explain multiple catch exceptions. Java supports multiple catch exceptions, that means a try block can have more than one catch handlers. All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception.

Scenario 1 In the below example, an array is defined of size 10 and we want to perform an invalid arithmetic operation on element 15 of the array. In this case, we have defined 3 different catch handlers to handle the exception – Arithmetic Exception, ArrayIndexOutOfBounds Exception and Parent Exception. The try block has thrown exception – Arithmetic as the Arithmetic operation is invalid (divide by 0).

public class MultipleCatchDemo1 {

	public static void main(String[] args) {
		try {
			int a[] = new int[10];
			a[15] = 30 / 0;
		
        } catch (ArithmeticException e) {
			System.out.println("Arithmetic Exception occurs");
		
        } catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBounds Exception occurs");
		
        } catch (Exception e) {
			System.out.println("Parent Exception occurs");
		
        }
		System.out.println("Rest of the program");
	}
}

Scenario 2 – In the below example, I’m throwing an exception which is not handled by first catch exception handler.

public class MultipleCatchDemo2 {

	public static void main(String[] args) {

		try {
			int a[] = new int[10];
			System.out.println(a[15]);

		} catch (ArithmeticException e) {
			System.out.println("Arithmetic Exception occurs");

		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBounds Exception occurs");

		} catch (Exception e) {
			System.out.println("Parent Exception occurs");

		}
		System.out.println("Rest of the program");
	}
}

Scenario 3 – In the below example, I’m throwing an exception which is not handled by any catch exception handler specified in the program. Then, parent exception handler will be invoked.

public class MultipleCatchDemo3 {

	public static void main(String[] args) {
		try {
			int a[] = new int[10];
			System.out.println(a[10]);

		} catch (ArithmeticException e) {
			System.out.println("Arithmetic Exception occurs");
		
		} catch (NullPointerException e) {
			System.out.println("NullPointer Exception occurs");
		
		} catch (Exception e) {
			System.out.println("Parent Exception occurs");
		
		}
		System.out.println("Rest of the program");
	}
}

Scenario 4 – In the below example, we do not maintain the order of preference in exceptions (child to parent), then compile time error occurs.

public class MultipleCatchDemo4 {

	public static void main(String[] args) {
		try {
			int a[] = new int[10];
			System.out.println(a[10]);

		} catch (Exception e) {
			System.out.println("Parent Exception occurs");

		} catch (ArithmeticException e) {
			System.out.println("Arithmetic Exception occurs");

		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBounds Exception occurs");

		}
		System.out.println("Rest of the program");
	}
}

Scenario 5 – In the below example, try block has 2 exceptions. It will call the first suitable catch block for the first try statement which has thrown the exception.

public class MultipleCatchDemo5 {

	public static void main(String[] args) {
		try {
			int a[] = new int[10];
			a[15] = 30 / 0;
			System.out.println(a[20]);

		} catch (ArithmeticException e) {
			System.out.println("Arithmetic Exception occurs");

		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBounds Exception occurs");

		} catch (Exception e) {
			System.out.println("Parent Exception occurs");

		}
		System.out.println("Rest of the program");
	}
}

Similarly, if I interchanged the try statements as shown below the response will also changes.

public class MultipleCatchDemo6 {

	public static void main(String[] args) {
		try {
			int a[] = new int[10];
			System.out.println(a[20]);
			a[15] = 30 / 0;

		} catch (ArithmeticException e) {
			System.out.println("Arithmetic Exception occurs");

		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBounds Exception occurs");

		} catch (Exception e) {
			System.out.println("Parent Exception occurs");

		}
		System.out.println("Rest of the program");
	}
}

Flow control in try catch finally in Java

HOME

In this tutorial, I’ll explain about the flow control of try catch and finally blocks in accordance to the exception.

What is try block in Java?

It is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can’t use try block alone.
If an exception occurs at the particular statement of try block, the rest of the block code will not execute. So, it is recommended not to keeping the code in try block that will not throw an exception.

What is catch block in Java?

It is used to handle the exception by declaring the type of exception within the parameter. It must be preceded by try block which means we can’t use catch block alone. It can be followed by finally block later.
You can use multiple catch block with a single try block.

What is finally block in Java?

It is used to execute important statements such as establishing connection, stream, etc. It is always executed whether exception is handled or not.

Syntax of try-catch block

try{
//throw an exception
}catch{ //handle exception }

Syntax of try-catch-finally block

try{
//throw an exception
}catch { //handle exception }
finally { //important code which will always be executed  }

1.Exception occurs in try block and handled in catch block

If a statement in try block throws an exception, then rest of the code of try block is not executed. The control transfers to corresponding catch block. After the execution of code in catch block, the control moves to the rest of the program code to be executed.

public class TryCatchDemo {

	public static void main(String[] args) {
		{
			try {
				String a = null; // null value
				System.out.println(a.length());

				// This will never execute as try block has exception just above this statement
				System.out.println("Inside try block");

				// Exception will be handled in catch block and will execute the statements in
				// catch block
			} catch (NullPointerException e) {
				System.out.println("NullPointer Exception - Exception caught in Catch block");

			}

			// Rest of the program will be executed
			System.out.println("Outside try-catch block");
		}
	}
}

Output
NullPointer Exception - Exception caught in Catch block
Outside try-catch block

2. Exception occurs in try block and handled in catch block and finally block is present

If a statement in try block throws an exception, then rest of the code of try block is not executed. The control transfers to corresponding catch block. After the execution of code in catch block, the control moves to finally block (if present) and then the rest of the program is executed.

public class TryCatchFinallyDemo {

	public static void main(String[] args) {
		{
			try {
				String a = null; // null value
				System.out.println(a.length());

				// This will never execute as try block has exception just above this statement
				System.out.println("Inside try block");

				// Exception will be handled in catch block and will execute the statements in
				// catch block
			} catch (NullPointerException e) {
				System.out.println("NullPointer Exception - Exception caught in Catch block");

				// Statement present in finally block will be executed irrespective whether
				// exception is handled or not
			} finally {
				System.out.println("finally block executed");
			}

			// Rest of the program will be executed
			System.out.println("Outside try-catch block");
		}
	}
}

Output
NullPointer Exception - Exception caught in Catch block
finally block executed
Outside try-catch block

3. Exception occurred in try-block is not handled in catch block without finally block

If a statement in try block throws an exception, then rest of the code of try block is not executed.

public class TryNoCatchDemo {

	public static void main(String[] args) {
		{
			try {
				String a = null; // null value
				System.out.println(a.length());

				// This will never execute as try block has exception just above this statement
				System.out.println("Inside try block");

				// Incorrect Exception
			} catch (IndexOutOfBoundException e) {
				System.out.println("IndexOutOfBound Exception - Exception caught in Catch block");

			}


			// Rest of the program will be executed
			System.out.println("Outside try-catch block");
		}
	}
}

Output
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	IndexOutOfBoundException cannot be resolved to a type

	at JavaDemo.Exception.TryNoCatchDemo.main(TryNoCatchDemo.java:15)

4. Exception occurred in try-block is not handled in catch block with finally block

public class TryNoCatchFinallyDemo {

	public static void main(String[] args) {
		{
			try {
				String a = null; // null value
				System.out.println(a.length());

				// This will never execute as try block has exception just above this statement
				System.out.println("Inside try block");

				// Incorrect Exception
			} catch (IndexOutOfBoundException e) {
				System.out.println("IndexOutOfBound Exception - Exception caught in Catch block");

			}

			finally {
				System.out.println("finally block executed");
			}

			// Rest of the program will be executed
			System.out.println("Outside try-catch block");
		}
	}
}

Output
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	IndexOutOfBoundException cannot be resolved to a type

	at JavaDemo.Exception.TryNoCatchDemo.main(TryNoCatchDemo.java:15)

5. Exception doesn’t occur in try-block

If a statement in try block does not throw an exception, then catch block will be never executed and then rest of the program will be executed.

public class NoTryCatchDemo {

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

			String str = "123";

			int num = Integer.parseInt(str);

			// this statement will execute
			// as no any exception is raised by above statement
			System.out.println("Inside try block");

		}

		catch (NumberFormatException ex) {

			System.out.println("catch block executed.");

		}

		System.out.println("Outside try-catch clause");
	}
}

Output
Inside try block
Outside try-catch clause

6. Exception doesn’t occur in try-block with finally block

If a statement in try block does not throw an exception, then catch block will never be executed. But the finally block will be executed and then rest of the program will be executed.

public class NoTryCatchFinallyDemo {

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

			String str = "123";

			int num = Integer.parseInt(str);

			// this statement will execute
			// as no any exception is raised by above statement
			System.out.println("Inside try block");

		}

		catch (NumberFormatException ex) {

			System.out.println("catch block executed");

		} finally {
			System.out.println("finally block executed");
		}

		System.out.println("Outside try-catch clause");
	}
}

Output
Inside try block
finally block executed
Outside try-catch clause

Java Exceptions Tutorial: Built-in and User-defined Exceptions

HOME

Table of Contents

  1. These are exceptions that are checked at compile-time.
  2. They must be either handled using a try-catch block or declared in the method signature using the `throws` keyword.
  3. Examples include IOException, SQLException, and FileNotFoundException.

It is thrown when an exception has occurred in an arithmetic operation. Below is an example of this exception.

public class ArithmeticExceptionDemo {

	public static void main(String[] args) {
		{
			try {
				int a = 30, b = 0;
				int c = a / b; // cannot divide by zero
				System.out.println("Result = " + c);
			} catch (ArithmeticException e) {
				System.out.println("Can't divide a number by 0");
			}
		}
	}
}

2. ArrayIndexOutOfBoundsException

It is thrown when an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

public class ArrayIndexOutOfBoundsExceptionDemo {

	public static void main(String[] args) {
		{
			try {
				// Create an array of size 5
				int a[] = new int[5];

				// Access 11th element from array of size 5
				a[10] = 9;
			} catch (ArrayIndexOutOfBoundsException e) {
				System.out.println("Array Index is Out Of Bounds");
			}
		}
	}
}

3. StringIndexOutOfBoundsException

It is thrown by String class methods to indicate that an index is either negative or greater than the size of the string.

public class StringOutOfBoundDemo {

	public static void main(String[] args) {
		{
			try {
				String a = "This is testing"; // length is 15
				System.out.println("Length of String :" + a.length());

				char b = a.charAt(20); // accessing 20th element
				System.out.println(b);
			} catch (StringIndexOutOfBoundsException e) {
				System.out.println("StringIndexOutOfBoundsException");
			}
		}
	}
}

4. NullPointerException

This exception is thrown when referring to the members of a null object.

public class NullPointerDemo {

	public static void main(String[] args) {
		{
			try {
				String a = null; // null value
				System.out.println(a.length());
			} catch (NullPointerException e) {
				System.out.println("NullPointerException");
			}
		}
	}
}

5. NumberFormatException

This exception is thrown when a method can not convert a string into a numeric format.

public class NumberFormatDemo {

	public static void main(String[] args) {
		try {
			// "java" is not a number
			int num = Integer.parseInt("java");

			System.out.println(num);
		} catch (NumberFormatException e) {
			System.out.println("Number format exception");
		}
	}
}

6. FileNotFoundException

This Exception is thrown when a file is not accessible or does not open.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class FileNotFoundDemo {

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

			// Following file does not exist
			File file = new File("C://demofile.txt");

			FileReader fr = new FileReader(file);
		} catch (FileNotFoundException e) {
			System.out.println("File does not exist");
		}
	}
}

7. ClassNotFoundException

This Exception is raised when we try to access a class whose definition is not found.

package JavaDemo;

public class ClassNotFoundExceptionDemo {

	public static void main(String[] args) {
		try {
			Class temp = Class.forName("gfg");
			// Calling the clas gfg which is not present in the
			// current class temp instance of calling class it
			// will throw ClassNotFoundException;
		} catch (ClassNotFoundException e) {
			// block executes when mention exception occur
			System.out.println("Class does not exist check the name of the class");
		}
	}
}

8. IOException

It is thrown when an input-output operation failed or interrupted.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class IOExceptionDemo {

	public static void main(String[] args) {

		String filepath = "C:\\Users\\Desktop\\IOTest1.txt";
		BufferedReader br1 = null;
		String curline;

		try {
			br1 = new BufferedReader(new FileReader(filepath));

			while ((curline = br1.readLine()) != null) {
				System.out.println(curline);
			}
		} catch (IOException e) {
			System.err.println("IOException found :" + e.getMessage());
		} finally {
			try {
				if (br1 != null)
					br1.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

9. NoSuchMethodException

It is thrown when accessing a method which is not found.

10. InterruptedException

It is thrown when a thread is waiting , sleeping , or doing some processing , and it is interrupted.

11. NoSuchFieldException

It is thrown when a class does not contain the field (or variable) specified.

12. RuntimeException

This represents any exception which occurs during runtime. They are ignored during compilation time. Such as logical bugs.

import java.util.Scanner;

public class RunTimeDemo {

	public static void main(String[] args) {
		// Reading user input
		Scanner input_dev = new Scanner(System.in);
		System.out.print("Enter your age in Numbers: ");
		int age1 = input_dev.nextInt();
		if (age1 > 20) {
			System.out.println("You can view the page");
		} else {
			System.out.println("You cannot view the page");
		}
	}
}

13. SQLException

This type of exception occurs while executing queries on a database related to the SQL syntax.

14. IllegalArgumentException

It is thrown when an inappropriate and incorrect argument is passed to the method. Suppose, a method does not allow null, but we are providing null as the parametr, then this exception is thrown.

Exception Handling in Java

HOME

What is Exception in Java?

An exception is an unwanted or unexpected event which occurs at the run time of the program, that leads to the disruption of the normal flow of execution of the program.

What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors happen in the program such as ClassNotFoundException, IOException, SQLException, RemoteException, etc, which disruptes the normal execution of the program.

Suppose there are 6 statements in your program and there occurs an exception at statement 3, the rest of the code will not be executed i.e. statement 4 to 6 will not be executed. If we perform exception handling, the rest of the statement will be executed. That is why we use exception handling in Java.

What is the difference between Error and Exception?

Error: An Error indicates serious problem that a reasonable application should not try to catch. Error are used by the Java run-time system(JVM) to indicate errors having to do with the run-time environment itself(JRE) or StackOverflowError or OutOfMemoryError

Exception: Exception indicates conditions that a reasonable application might try to catch. Example of exceptions are IOException, SQLException, etc.

Types of Exceptions

1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

Hierarchy of Java Exception classes

Keywords used in Exception Handling in Java

1. try keyword – It is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can’t use try block alone.

2. catch keyword – It is used to handle the exception. It must be preceded by try block which means we can’t use catch block alone. It can be followed by finally block later.

3. finally keyword – It is used to execute the important code of the program irrespective the exception is handled or not.

4. throw keyword – It is used to throw an exception explicitly in the program inside a function or inside a block of code.

5. throws keyword – It is used to declare exceptions. It doesn’t throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature.

Exception Handling Example in Java

Let’s see an example of exception handling where we can use try-catch block and will not use try-catch statements. Below example shows an exception without try-catch block.

package JavaDemo;

public class ExceptionHandlingDemo {

	static String a = null;

	public static void main(String[] args) {

		System.out.println(a.length());
	}

}

Output
Exception in thread "main" java.lang.NullPointerException
	at JavaDemo.ExceptionHandlingDemo.main(ExceptionHandlingDemo.java:9)

Below example shows an exception with try-catch block.

package JavaDemo;

public class ExceptionHandlingDemo {
	static String a = null;

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		try {
			System.out.println(a.length());
		} catch (NullPointerException e) {
			System.out.println(e);
		}
		System.out.println("Exception is handled");
	}

}

Output
java.lang.NullPointerException
Exception is handled

Page Object Model with Page Factory in Selenium

HOME

What Is Page Object Model (POM)?

Page Object model is an object design pattern in Selenium, where web pages are represented as classes, and the various elements on the page are defined as variables in the class and all possible user interactions can then be implemented as methods in the class.

The benefit is that if there is any change in the UI for the page, the tests themselves don’t need to change, only the code within the page object needs to change. Subsequently all changes to support that new UI are located in one place.

Advantages:

1. Readable There is a clean separation between test code and page specific code such as locators and methods.

2. Maintainability  – In this model, separate classes are created for different pages of a web application like login page, the home page, employee detail page, change password page, etc. So, if there is any change in any element of a website then we only need to make changes in one class, and not in all classes.

3. Reusable If multiple test scripts use the same web elements, then we need not write code to handle the web element in every test script. Placing it in a separate page class makes it reusable by making it accessible by any test script.

4. Easy project Structure – Its project structure is quite easy and understandable.

5. PageFactory – It can use PageFactory in the page object model in order to initialize the web element and store elements in the cache.

In case there are lots of web elements on a page, then the object repository class for a page can be separated from the class that includes methods for the corresponding page.

Example: If the New Customer page has many input fields. In that case, there can be 2 different classes. One class called NewCustomerObjects.java that forms the object repository for the UI elements on the register accounts page.

A separate class file NewCustomerMethods.java extending or inheriting NewCustomerObjects that includes all the methods performing different actions on the page could be created.

Consider the below script to login to an application and navigate to home page.

This is a small script. Therefore, script maintenance and readability looks very easy.

Imagine there are 50 different tests present in this script. In that case, the readability of the script decreases as well as maintenance become very difficult.

Scenario

  1. Launch the Firefox browser.
  2. The demo website opens in the browser.
  3. Verify the Login Page
  4. Enter username and Password and login to the demo site.
  5. Verify the home page.
  6. Close the browser.
package PageObjectModel;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class NonPOMExample {

     WebDriver driver;

     @BeforeTest
     public void setup() {

           ChromeOptions options = new ChromeOptions();
           driver = new ChromeDriver(options);
           driver.manage().window().maximize();
           driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
           driver.get("https://opensource-demo.orangehrmlive.com/");
     }

     @Test(priority = 0)
     public void Login() {
           String pageTitle = driver.findElement(By.id("logInPanelHeading")).getText();
           Assert.assertTrue(pageTitle.contains("LOGIN Panel"));
     }

     @Test(priority = 1)
     public void HomePage() {

           driver.findElement(By.name("txtUsername")).sendKeys("Admin");
           driver.findElement(By.name("txtPassword")).sendKeys("admin123");
           driver.findElement(By.id("btnLogin")).submit();
           String homePageText = driver.findElement(By.id("welcome")).getText();
           Assert.assertTrue(homePageText.contains("Welcome"));
     }

     @AfterTest
     public void close() {
           driver.close();
     } 
}

What Is Pagefactory?

PageFactory is a way of implementing the “Page Object Model”. Here, we follow the principle of separation of Page Object Repository and Test Methods. It is an inbuilt concept of Page Object Model which is very optimized.

1. The annotation @FindBy is used in Pagefactory to identify an element while POM without Pagefactory uses the driver.findElement() method to locate an element.

2. The second statement for Pagefactory after @FindBy is assigning an <element name> of type WebElement class that works exactly similar to the assignment of an element name of type WebElement class as a return type of the method driver.findElement() that is used in usual POM (userName in this example).

Non POM

driver.findElement(By.name("txtUsername"));

POM

@FindBy(name = "txtUsername")
WebElement userName;

3. Below is a code snippet of non PageFactory Mode to set Firefox driver path. A WebDriver instance is created with the name driver and the FirefoxDriver is assigned to the ‘driver’.  The same driver object is then used to launch the demo website, locate the webelements and to perform various operations

Basically, here the driver instance is created initially and every web element is freshly initialized each time when there is a call to that web element using driver.findElement() or driver.findElements().

ChromeOptions options = new ChromeOptions();
driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://opensource-demo.orangehrmlive.com/");

But with POM with PageFactory approach, all the elements are initialized with initElements() without explicitly initializing each web element.

The initElements is a static method of PageFactory class which is used to initialize all the web elements located by @FindBy annotation. Thus, instantiating the Page classes easily. It is used to initialize the WebElements declared, using driver instance from the main class. In other words, WebElements are created using the driver instance. Only after the WebElements are initialized, they can be used in the methods to perform actions.

public Login(WebDriver driver) {
           this.driver = driver;
           // This initElements method will create all WebElements
           PageFactory.initElements(driver, this);
     }

Implementation Steps

Step 1 – Create a Maven Project

Click here to know How to create a Maven project.

Step 2 – Add dependencies to the pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.example</groupId>
  <artifactId>PageObjectModel</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>PageObjectModel</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <selenium.version>4.21.0</selenium.version>
    <testng.version>7.10.2</testng.version>
    <maven.surefire.plugin.version>3.2.5</maven.surefire.plugin.version>
    <maven.compiler.plugin.version>3.13.0</maven.compiler.plugin.version>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>${selenium.version}</version>
    </dependency>

    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>${testng.version}</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>${maven.compiler.plugin.version}</version>
        <configuration>
          <source>${maven.compiler.source}</source>
          <target>${maven.compiler.target}</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>${maven.surefire.plugin.version}</version>
        <configuration>
          <suiteXmlFiles>
            <suiteXmlFile>testng.xml</suiteXmlFile>
          </suiteXmlFiles>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

Step 3 – Create a Java Class for each page

In this example, we will access 2 web pages, “Login” and “Home” pages.

Hence, we will create 2 Java classes in Page Layer  –  Login.java and HomePage.java

3.1. Define WebElements as variables using Annotation @FindBy:

We would be interacting with:

  • Message on Login Page, Username, Password, Login button field on the Login Page.
  • Successful message on the Home Page

For Example: If we are going to identify the Username using attribute name, then its variable declaration is

 @FindBy(name = "txtUsername")
 WebElement userName;

3.2 Create methods for actions performed on WebElements.

Below actions are performed on WebElements in Login Page:

  • Get Text on Login Page
  • Type action on the Username field.
  • Type action in the Password field.
  • Click action on the Login Button

Note: A constructor has to be created in each of the class in the Page Layer, in order to get the driver instance from the Main class in Test Layer and also to initialize WebElements(Page Objects) declared in the page class using PageFactory.InitElement().

package com.example.pages;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;

public class BasePage {
    public WebDriver driver;

    public BasePage(WebDriver driver) {
        this.driver = driver;
        PageFactory.initElements(driver,this);
    }

}

Login Page

package com.example.pages;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

public class LoginPage extends BasePage{

    public LoginPage(WebDriver driver) {
        super(driver);

    }

    @FindBy(name = "username")
    public WebElement userName;

    @FindBy(name = "password")
    public WebElement password;

    @FindBy(xpath = "//*[@class='oxd-form']/div[3]/button")
    public WebElement login;

    @FindBy(xpath = "//*[@id='app']/div[1]/div/div[1]/div/div[2]/div[2]/div/div[1]/div[1]/p")
    public  WebElement errorMessage;


    public void login(String strUserName, String strPassword) {

        userName.sendKeys(strUserName);
        password.sendKeys(strPassword);
        login.click();

    }

    public String getErrorMessage() {
        return errorMessage.getText();
    }


}

HomePage. java

package com.example.pages;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

public class HomePage extends BasePage {

    public HomePage(WebDriver driver) {
        super(driver);

    }

    @FindBy(xpath = "//*[@id='app']/div[1]/div[1]/header/div[1]/div[1]/span/h6")
    public  WebElement homePageUserName;

    public String getHomePageText() {
        return homePageUserName.getText();
    }

}

Step 4 –  Create test class for the tests of these pages

package com.example.tests;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;

import java.time.Duration;

public class BaseTests {

    public static WebDriver driver;
    public final static int TIMEOUT = 10;

    @BeforeMethod
    public void setup() {

        ChromeOptions options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");
        options.addArguments("--no-sandbox");
        options.addArguments("--disable-dev-shm-usage");
        options.addArguments("--headless");
        driver = new ChromeDriver(options);
        driver.manage().window().maximize();
        driver.get("https://opensource-demo.orangehrmlive.com/");
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(TIMEOUT));

    }

    @AfterMethod
    public void tearDown() {
        driver.quit();
    }

}

LoginPageTests.java

package com.example.tests;

import com.example.pages.HomePage;
import com.example.pages.LoginPage;
import org.testng.Assert;
import org.testng.annotations.Test;

public class LoginPageTests extends BaseTests{

    String actualResponse;

    @Test
    public void invalidCredentials()  {

        LoginPage objLoginPage = new LoginPage(driver);
        objLoginPage.login("admin", "admin");
        actualResponse = objLoginPage.getErrorMessage();
        Assert.assertEquals(actualResponse,"Invalid credentials");
    }

    @Test
    public void validCredentials() {

        LoginPage objLoginPage = new LoginPage(driver);
        objLoginPage.login("Admin", "admin123");
        HomePage objHomePage = new HomePage(driver);
        actualResponse = objHomePage.getHomePageText();
        Assert.assertEquals(actualResponse,"Dashboard");

    }

}

Step 5 – Execute the tests

To run the test, right click and select as Run As and then select TestNG Test (Eclipse).

Step 6 – Create TestNG.xml

You can add TestNG.xml and run the tests from there also.

<?xml version = "1.0"encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name = "PageObjectModel">
    <test name = "PageObjectModel Tests">
        <classes>
            <class name ="com.example.tests.LoginPageTests"/>
        </classes>
    </test>
</suite>

Step 7 – Run the tests from TestNG.xml

Right click on TestNG.xml and select Run As TestNG Suite.

The execution status looks like as shown below.

Step 8 -TestNG Report Generation

Once the execution is finished, refresh the project. It will create a test-output folder containing various reports generated by TestNG. Below is the screenshot of the report folder.

Index.html

emailable-report.html

mvn clean test

How to Download and Install Eclipse IDE

HOME

 Eclipse IDE is a software that allows you to write your programs and test scripts in multiple programming languages (with Java being the most popular one).

Download Eclipse IDE

 1. Open the below mentioned link. Latest version of Eclipse available is Eclipse IDE 2024-09 R Packages  Eclipse Download .

       
 2. Select – Eclipse IDE for Java Developers. Depending on type of Operating System, download either 32 bit or 64 bit. My system is 64 bit, so downloading 64 bit Eclipse .

3. Click on the Download button to start downloading process.

Install/Setup Eclipse

  1.  We do not need to install Eclipse, just unzip the Eclipse downloaded folder. Go to the path where Eclipse downloaded and unzip the folder .

2.    Eclipse folder have Eclipse Editor (Eclipse.exe), double click on it.

3.   Eclipse Workplace directory will get open. You can provide name to this directory. In Eclipse, all the projects saved in Eclipse Directory

4.  A folder with same Eclipse Directory name creates in same path as mentioned above.

Note: –  There are chances that you may face the issue while trying to access Eclipse IDE – Java was started but returned exit code =13. This is because there is configuration mistake in Eclipse.ini (Eclipse Configuration) file. The error will look like something below:-

To fix this issue, open the Eclipse Configuration file. It will be present in unzipped Eclipse Folder. 

Add the below mentioned line in Eclipse Configuration file:-

-vm
      C:\Program Files\Java\jre1.8.0_201\bin\java.exe

 More details can found from below link                                  

https://wiki.eclipse.org/Eclipse.ini#Specifying_the_JVM