Difference between Static Method and Non-Static Method

HOME

package com.example.definitions;

public class staticMyClass {

    static void MyStatic_Method() { // Static Method
        System.out.println("Static method can be accessed without creating object");
    }

    public void MyPublic_Method() { // Public Method
        System.out.println("Public  method can be accessed only by creating object");
    }

    public static void main(String[] args) {
        MyStatic_Method(); // Calling Static Method

    }
}


public class nonStaticClass {

    static void MyStatic_Method() { // Static Method
        System.out.println("Static method can be accessed without creating object");
    }

    public void MyPublic_Method() { // Public Method
        System.out.println("Public method can be accessed only by creating object");
    }

    public static void main(String[] args) {

        nonStaticClass stat = new nonStaticClass();
        stat.MyPublic_Method();   // Calling Non Static Method


    }
}

Class and Object in Java

HOME

Let us consider the Phone as the object. The state of the Phone is coloured grey, and black, and types like IPhone, Samsung, and behaviour is calling, sending messages, and internet browsing.

public class Student {
          String Name;
}

How to create an Object?

To create an object, specify a class name like Student, an object name like stud, and use a new keyword. 

Student stud = new Student();

Let us create a class and an object of its class and print the value of the variable name.

public class Student {

    String Name = "Tom";
    public static void main(String[] args)

    {
        Student stud = new Student();
        System.out.println("Name of Student :"+stud.Name);
    }
}

Multiple Objects of a Class

We can create multiple objects of a class. In the below example, we have created 2 objects of class Student.

public class Student {

    String Name = "Tom";
    public static void main(String[] args)
    {
        Student stud1 = new Student();
        Student stud2 = new Student();
        System.out.println("Name of Student :"+stud1.Name);
        System.out.println("Name of Student :"+stud2.Name);
    }
}

Multiple Classes

We can create a class and then create an object of that class in another class. Like, here, we have created a class called Student.java and another class is Student_Demo.java where we will create the object of class Student. This is a better approach than the previous one.

public class Student {
          String Name = "Tom";         
}


public class Student_Test{
    public static void main(String[] args)
    {
        Student stud = new Student();
        System.out.println("Name of Student :"+stud.Name);
    }
}

There are multiple ways to initialize the classes and objects.

1) Initialize through reference

Here, initializing an object means storing data in the object. Let’s see a simple example where we are going to initialize the object through a reference variable.

public class Student {
          String Name ;
          int Age;
}

public class Student_Test {
    public static void main(String[] args)
    {
        Student stud = new Student();
        stud.Name ="Tom";
        stud.Age=35;
        System.out.println("Name of Student :"+stud.Name);
        System.out.println("Age of Student :"+stud.Age);
    }
}

2) Initializing through method

We are creating the two objects of the Student class and initializing the value to these objects by invoking the InsertData() method. Here, we are displaying the state (data) of the objects by invoking the DisplayData() method.

public class Student {
	String Name;
	int Age;

	void InsertData(String n, int a) {
		Name = n;
		Age = a;
	}

	void DisplayData() {
		System.out.println("Name of Student :" + Name);
		System.out.println("Age of Student :" + Age);
	}
}


public class Student_Test {
    
    public static void main(String[] args) {
        Student stud = new Student();
        stud.InsertData("Tom", 34);
        stud.DisplayData();
    }
}

We can create multiple objects

public class Student {
          String Name ;
          int Age;

          void InsertData(String n, int a)
          {
                   Name =n;
                   Age = a;
          }

          void DisplayData()
          {
                   System.out.println("Name of Student :"+Name);
                   System.out.println("Age of Student :"+Age);
          }
    }  


public class Student_Test {
    
    public static void main(String[] args) {

            Student stud1 = new Student();
            Student stud2 = new Student();
            stud1.InsertData("Matt",43);
            stud1.DisplayData();
            stud2.InsertData("Terry",36);
            stud2.DisplayData();
    }
 }

Method Overloading in Java

HOME

public class MethodOverloading_Demo {

    public void Calculation(int a, float b) {
        System.out.println("Sum of 2 numbers :" + (a + b));
    }

    //Different type of parameters
    public void Calculation(float x, float y) {
        System.out.println("Sum of 2 numbers :" + (x + y));
    }

    //Different number of parameters
    public void Calculation(int i, int j, int k) {
        System.out.println("Sum of 3 numbers :" + (i + j + k));
    }

    //Different sequence of parameters
    public void Calculation(float p, int r) {
        System.out.println("Sum of 3 numbers :" + (p + r));
    }

    public static void main(String[] args) {

        MethodOverloading_Demo add = new MethodOverloading_Demo();

        //Call overloaded methods
        add.Calculation(5, 12f);
        add.Calculation(13f, 12.0f);
        add.Calculation(22, 33, 50);
        add.Calculation(11f, 10);
    }

}

What is Type Promotion?

When a data type of smaller type, promote to bigger type, it called type promotion.  Suppose a method has double data type and object provides float, then the program works fine. Float will be promote to double.

Let us explain this with an example. In the below example, object has provided float data type, but method has double data type, so there is type promotion.

public class Addition {

    public void Calculation(int a, int b)  {
        System.out.println("Sum of 2 numbers :"+(a+b));
    }

    public void Calculation(int x, double y)   {
        System.out.println("Sum of 2 numbers :"+(x+y));
    }

    public static void main(String[] args) {
        Addition add = new Addition();
        //Type Promotion method
        add.Calculation(5,12);
        add.Calculation(13,12f);
    }
}

Multiple questions on Exception Handling in Java

HOME

In this tutorial, you will see the various questions related to Exception Handling.

Example1

public class ExceptionHandlingDemo {

	public static void main(String[] args) {

		try {
			int a[] = new int[5];
			a[5] = 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("Continue the program..");
	}
}

Here, we have multiple catch blocks with different types of exceptions. 30 is divided by 0 which throws ArithmeticException. So, the catch block for ArithmeticException is executed. Once the try-catch block is executed, the program runs in normal flow.


Example2

public class ExceptionHandlingDemo {

	public static void main(String[] args) {

		try {
			int a[] = new int[5];
			a[5] = 30 / 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("Continue the program..");
	}
}

Here, we are trying to access a[5] where index 5 is out of range, which throws ArrayIndexOutOfBoundsException. So, the catch block for ArrayIndexOutOfBoundsException is executed. Once the try-catch block is executed, the program runs in normal flow.


Example3

public class ExceptionHandlingDemo {

	public static void main(String[] args) {
		try {
			int a[] = new int[5];

			System.out.println(a[7]);
		} 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("Continue the program..");
	}
}

Output
ArrayIndexOutOfBounds Exception occurs
Continue the program..

Here, we are trying to access a[7] where index 7 is out of range, which throws ArrayIndexOutOfBoundsException. So, the catch block for ArrayIndexOutOfBoundsException is executed. Once the try-catch block is executed, the program runs in normal flow.


Example4

public class ExceptionHandlingDemo {

	public static void main(String[] args) {
		try {
			int a[] = new int[5];
			a[5] = 30 / 0;
			System.out.println(a[10]);
		} 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("Continue the program..");
	}
}

Here, the try block contains two exceptions. But at a time only one exception occurs and its corresponding catch block is executed. So, the first exception is 30 divided by 0 which throws an ArithmeticException. So, the catch block for ArithmeticException is executed. Once the corresponding catch block is executed, the program runs in normal flow.


Example5

public class ExceptionHandlingDemo {

    public static void main(String[] args) {
        try {
            String name = null;
            System.out.println(name.length());
        } 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("Continue the program..");
    }
}

Here, the try block contains NullPointerException. But, there is no NullPointerException present in any of the catch blocks. In such a case, the catch block containing the parent exception class Exception will be invoked.


Example6

public class ExceptionHandlingDemo {

	public static void main(String[] args) {
		try {
			int a[] = new int[5];
			a[5] = 30 / 0;
		} catch (Exception e) {
			System.out.println("common task completed");
		} catch (ArithmeticException e) {
			System.out.println("Arithmetic Exception occurs");
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBounds Exception occurs");
		}
		System.out.println("Continue the program..");
	}
}

Here, the order of exceptions is not maintained like most specific to general exceptions. The exception is the parent exception, so should be mentioned as the last exception. As a result, there is a compile-time error.


Example7

public class ExceptionHandlingDemo {

    public static void main(String args[]) {
        int x = 0;
        int y = 10;
        int z = y/x;
    }
}

Here, ArithmeticException is an unchecked exception that is not checked at a compiled time. So the program compiles fine but throws ArithmeticException.


Example8

public class ExceptionHandlingDemo {

    public static void main(String[] args) {
        try {
            int a[] = { 1, 2, 3, 4 };
            for (int i = 1; i <= 4; i++) {
                System.out.println("a[" + i + "]=" + a[i]);
            }
        }

        catch (Exception e) {
            System.out.println("error = " + e);
        }

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

Here, ArrayIndexOutOfBoundsException has been already caught by the base class Exception. When a subclass exception is mentioned after the base class exception, then an error occurs.


Example9

public class Example9 {

	public static void main(String[] args) {
		try {
			int a[] = { 1, 2, 3, 4 };
			for (int i = 1; i <= 4; i++) {
				System.out.println("a[" + i + "]=" + a[i]);
			}
		}

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

		catch (Exception e) {
			System.out.println("error = " + e);
		}
	}
}

Here, the try block prints a[1] to a[3] and then throws ArrayIndexOutOfBoundsException which is handled by the corresponding catch block.


Example10

public class ExceptionHandlingDemo {

	public static void main(String[] args) {

		// outer try block
		try {

			// inner try and catch block 1
			try {
				System.out.println("going to divide by 0");
				int b = 40 / 0;
			}
			catch (ArithmeticException e) {
				System.out.println(e);
			}

			// inner try and catch block 2
			try {
				int a[] = new int[5];

				// assigning the value out of array bounds
				a[5] = 4;
			}
			catch (ArrayIndexOutOfBoundsException e) {
				System.out.println(e);
			}

			System.out.println("No more inner try catch block");
		}

		// catch block of outer try block
		catch (Exception e) {
			System.out.println("Handled the exception of outer try");
		}

		System.out.println("Continue the program..");
	}
}

Here, the first inner try-catch block is executed. Then second inner try-catch block is executed and at last outer try-catch block is executed. Post all these, the program runs in normal flow.


Example11

public class ExceptionHandlingDemo {

	public static void main(String[] args) {

        // outer try block
        try {

            // inner try block 1
            try {

                // inner try block 2
                try {
                    int x = 25 / 0;
                    System.out.println("Value of x :" + x);
                }

                // to handles ArrayIndexOutOfBoundsException
                catch (ArrayIndexOutOfBoundsException e) {
                    System.out.println("Arithmetic exception");
                    System.out.println(" inner try block 2");
                }
            }

            // to handle ArrayIndexOutOfBoundsException
            catch (ArrayIndexOutOfBoundsException e) {
                System.out.println("Arithmetic exception");
                System.out.println("inner try block 1");
            }
        }

        // to handle ArithmeticException
        catch (ArithmeticException e) {
            System.out.println(e);
            System.out.println("Outer try block");
        } catch (Exception e) {
            System.out.print("Exception");
            System.out.println("Handled in main try block");
        }
    }
}

Here, the try block within the nested try block (inner try block 2) does not handle the exception. The control is then transferred to its parent try block (inner try block 1) and it also does not handle the exception, then the control is transferred to the main try block (outer try block) where the appropriate catch block handles the exception. 


Example12

public class ExceptionHandlingDemo {

	public static void main(String[] args) {

		// outer try block
		try {

			// inner try block 1
			try {

				// inner try block 2
				try {
					int x = 25 / 0;
					System.out.println(x);
				}

				// to handles ArrayIndexOutOfBoundsException
				catch (ArrayIndexOutOfBoundsException e) {
					System.out.println("Arithmetic exception");
					System.out.println(" inner try block 2");
				}
			}

			// to handle ArithmeticException 
			catch (ArithmeticException e) {
				System.out.println("Arithmetic exception");
				System.out.println("inner try block 1");
			}
		}

		// to handle ArithmeticException
		catch (ArithmeticException e) {
			System.out.print(e);
			System.out.println("Outer try block");

		} catch (Exception e) {
			System.out.print("Exception");
			System.out.println("Handled in main try block");
		}
	}
}

Here, the try block within the nested try block (inner try block 2) does not handle the exception. The control is then transferred to its parent try block (inner try block 1) and it does handle the exception, so the catch block of inner try block 1 handles the exception.


Example13

public class ExceptionHandlingDemo {

	public static void main(String[] args) {
		try {
			// below code do not throw any exception
			int data = 25 / 5;
			System.out.println(data);
		}

		// catch won't be executed
		catch (NullPointerException e) {
			System.out.println(e);
		}

		// This is executed whether exception occurs or not
		finally {
			System.out.println("finally block is always executed");
		}

		System.out.println("Continue the Program ..");
	}
}

Output
5
finally block is always executed
Continue the Program ..

Here, no exception is thrown, so the catch block is not executed. finally block is always executed irrespective the catch block is executed or not.


Example14

public class ExceptionHandlingDemo {

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

			System.out.println("Inside the try block");

			// below code throws divide by zero exception
			int data = 25 / 0;
			System.out.println(data);
		}

		catch (NullPointerException e) {
			System.out.println("Exception handled");
			System.out.println(e);
		}

		// executes regardless of exception occurred or not
		finally {
			System.out.println("finally block is always executed");
		}

		System.out.println("Continue the Program ..");
	}
}

Here, the code throws an exception, however, the catch block cannot handle it. Despite this, the finally block is executed after the try block and then the program terminates abnormally.


Example15

public class ExceptionHandlingDemo {

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

			System.out.println("Inside try block");

			// below code throws divide by zero exception
			int data = 25 / 0;
			System.out.println(data);
		}

		// handles the Arithmetic Exception 
		catch (ArithmeticException e) {
			System.out.println("Exception is handled");
			System.out.println(e);
		}

		// executes regardless of exception occured or not
		finally {
			System.out.println("finally block is always executed");
		}

		System.out.println("Continue the Program ..");
	}
}

Here, the code throws an exception and the catch block handles the exception. Later the finally block is executed after the try-catch block. Further, the rest of the code is also executed normally.


Example16

public class ExceptionHandlingDemo {

	public static void main(String[] args) {
		try {
			int a = 0;
			System.out.println("a = " + a);
			int b = 20 / a;
			System.out.println("b = " + b);
		}

		catch (ArithmeticException e) {
			System.out.println("Divide by zero error");
		}

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

Here, a is printed. Then, 20 is divided by 0, which throws ArithmeticException and control goes inside the catch block. Also, the finally block is always executed whether an exception occurs or not.


Example 17

public class ExceptionHandlingDemo {

	public static void main(String[] args) {
		int data = 50 / 0; // may throw exception

		System.out.println("rest of the code");
	}

}

Here, there is no try-catch block. So, the error is thrown.


Example 18

public class ExceptionHandlingDemo  {

	public static void main(String[] args) {
		try {
			int data1 = 50 / 0; 

		}
		catch (Exception e) {
			// generating the exception in catch block
			String name = null;
			System.out.println(name.length());
			
		}
		System.out.println("Continue the Program ..");
	}

}

Output
Exception in thread "main" java.lang.NullPointerException

Here, the catch block didn’t contain the exception code. So, enclose the exception code within a try block and use a catch block only to handle the exceptions.


Example 19

public class ExceptionHandlingDemo {

	static void checkEligibilty(int age, int marks) {
		if (age < 18 && marks < 90) {
			throw new ArithmeticException("Student is not eligible for admission");
		} else {
			System.out.println("Student Entry is Valid!!");
		}
	}

	public static void main(String[] args) {
		System.out.println("Welcome to the Admission process!!");
		checkEligibilty(17, 80);
		System.out.println("Continue the Program ..");
	}
}

Here, an unchecked exception was thrown and it is not handled, so the program halts.


Example 20

public class ExceptionHandlingDemo {

	public static void myMethod(int testnum) throws Exception {
		System.out.println("start - myMethod");
		if (testnum < 100)
			throw new Exception();
		System.out.println("end - myMethod");
		return;
	}

	public static void main(String args[]) {
		int testnum = 90;
		try {
			System.out.println("try - first statement");
			myMethod(testnum);
			System.out.println("try - last statement");
		} catch (Exception ex) {
			System.out.println("An Exception");
		} finally {
			System.out.println("finally");
		}
		System.out.println("Out of try/catch/finally - statement");
	}
}

Here, an exception is thrown in the try block, which is handled by the catch block. A finally block is executed, and then the program continues as usual.


Example 21

public class ExceptionHandlingDemo {

   public static void main(String args[]) {
      try {
         throw 10;
      }
      catch(int e) {
         System.out.println("Got the  Exception " + e);
      }
  }
}

In Java, only throwable objects (Throwable objects are instances of any subclass of the Throwable class) can be thrown as exceptions. So basic data types can not be thrown at all.


Example 22

public class ExceptionHandlingDemo {

	public static void main(String[] args) {
		
      try {
			throw new Test();
		} catch (Test t) {
			System.out.println("Got the Test Exception");
		} finally {
			System.out.println("Inside finally block ");
		}
	}
}

The output of the above program is


Example 23

class Base extends Exception {
}

class Derived extends Base {
}

 class ExceptionHandlingDemo  {

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

            throw new Derived();
        } catch (Base b) {
            System.out.println("Caught base class exception");
        } catch (Derived d) {
            System.out.println("Caught derived class exception");
        }
    }
}


Example 24

public class ExceptionHandlingDemo {

	String str = "a";

    void A() {
        try {
            str += "b";
            B();
        } catch (Exception e) {
            str += "c";
        }
    }

    void B() throws Exception {
        try {
            str += "d";
            C();
        } catch (Exception e) {
            throw new Exception();
        } finally {
            str += "e";
        }

        str += "f";

    }

    void C() throws Exception {
        throw new Exception();
    }

    void display() {
        System.out.println(str);
    }

    public static void main(String[] args) {
        ExceptionHandlingDemo object = new ExceptionHandlingDemo();
        object.A();
        object.display();
    }

}

}

‘throw’ keyword is used to explicitly throw an exception.
Call to method C() throws an exception. Thus, control goes to the catch block of method B() which again throws an exception. Then finally block is always executed even when an exception occurs. Now, control goes to the catch block of method A().


Example 25

public class ExceptionHandlingDemo {

	 void m() {
        int data = 50 / 0;
    }

    void n() {
        m();
    }

    void p() {
        try {
            n();
        } catch (Exception e) {
            System.out.println("Exception Handled");
        }
    }

    public static void main(String args[]) {
        ExceptionHandlingDemo obj = new ExceptionHandlingDemo();
        obj.p();
        System.out.println("Continue the program..");
    }
}

Here, the exception occurs in the m() method where it is not handled, so it is propagated to the previous n() method where it is not handled, again it is propagated to the p() method where the exception is handled.


Example 26

public class ExceptionHandlingDemo {

	void m() {
        throw new IOException("device error");// checked exception
    }

    void n() {
        m();
    }

    void p() {
        try {
            n();
        } catch (Exception e) {
            System.out.println("Exception Handled");
        }
    }

    public static void main(String args[]) {
        ExceptionHandlingDemo obj = new ExceptionHandlingDemo();
        obj.p();
        System.out.println("Continue the program..");
    }
}

Here, the exception occurs in the m() method where it is not handled, so it is propagated to the previous n() method where it is not handled, it is propagated to the p() method where the exception is supposed to be handled, but as it is checked Exception which can not be handled by Exception.


Example 27

public class ExceptionHandlingDemo {

    void m() {
        throw new ArithmeticException("Arithmetic Exception occured ");
    }

    void n() {
        m();
    }

    void p() {
        try {
            n();
        } catch (Exception e) {
            System.out.println("Exception handled");
        }
    }

    public static void main(String args[]) {
        ExceptionHandlingDemo obj = new ExceptionHandlingDemo();
        obj.p();
        System.out.println("Continue the program..");
    }
}

Here, the exception occurs in the m() method – ArithmeticException where it is not handled, so it is propagated to the previous n() method where it is not handled, again it is propagated to the p() method where the exception is handled.


Example 28

public class ExceptionHandlingDemo {

	public static void main(String args[]) {
		try {
			int i, sum;
			sum = 10;
			for (i = -1; i < 3; ++i)
				sum = (sum / i);
		} catch (ArithmeticException e) {
			System.out.print("0");
		}
		System.out.print(sum);
	}
}

Here, the value of the variable sum is printed outside of the try block, the sum is declared only in the try block, and outside try block it is undefined.


Example 29

public class ExceptionHandlingDemo {

	public static void main(String args[]) {
		try {
			String str = "beginnersbook";
			System.out.println(str.length());
			char c = str.charAt(0);
			c = str.charAt(40);
			System.out.println(c);
		} catch (StringIndexOutOfBoundsException e) {
			System.out.println("StringIndexOutOfBoundsException!!");
		}
	}
}

Here, an exception occurred because the referenced index was not present in the String.


Example 30

public class ExceptionHandlingDemo {

    public static void main(String[] args) {

            try {
                int num = Integer.parseInt("XYZ");
                System.out.println(num);
            } catch (StringIndexOutOfBoundsException e) {
                System.out.println("String IndexOutOfBounds Exception occurred!!");
            } catch (NumberFormatException e) {
                System.out.println("Number format exception occurred");
            } catch (Exception e) {
                System.out.println("Exception occurred");
            }
        }
    }

Here, an exception is not of type StringIndexOutOfBounds, so moved to the next catch where the exception is handled.

How to download and install Apache POI

HOME

This tutorial describes how to download and install Apache POI.

Selenium does not have an inbuilt method to read data from an Excel File. However, there are various libraries in JAVA that help in reading/writing data from Excel files. Apache POI is one of the most used libraries, which provides various classes and methods to read/write data from various formats of Excel files(xls, xlsx etc).

What is Apache POI?

Apache POI, where POI stands for (Poor Obfuscation Implementation)  is the Java API for Microsoft Documents that offers a collection of Java libraries that helps us to read, write, and manipulate different Microsoft files such as Excel sheets, PowerPoint, and Word files.

Download Apache POI

Step 1To download Apache POI, go to its official site, here. Click on the Download as shown in the image. This link will navigate to the page showing the latest release of Apache POI.  The latest Apache POI version is 5.2.3. You can follow the same steps for any version of POI.

Step 2 This page shows the latest Apache POI Release Artifacts. Here, you can see POI 5.0.0 is the latest one. Download any one of the Binary Distribution options. One option is .ztar.gz and another option is .zip. I have selected .zip option.

Step 3 After clicking on the link, it navigates to another page as shown below. I have used the highlighted link to download the POI library files.

Step 4 Once POI.zip is downloaded and extracted, this is how the folder looks like

How to add POI libraries in Eclipse?

Step 1 Below is the Java project present in Eclipse.

Step 2 To add POI libraries to this project, Right-click on the project, hover over the Build path, select Configure Build Path.

Step 3  It will open the “Properties” of the project. After that, select the Libraries tab. Finally, click on the Add External JARs as highlighted below.

Step 4 Select the JARs in the parent folder of the unzipped POI files. Subsequently, click on the Open button to include them in the Eclipse project.

Step 5 – Next, select the JARs under the ooxml-lib folder in the unzipped POI folder as highlighted below:

Step 6 – Select the JARs under the lib folder in the unzipped POI folder as highlighted below.

Step 7 – After that, once all the POI JARs add, click on the Apply and Close button as highlighted below.

Step 8 – Once all the POI libraries successfully install in the Eclipse project, they will reflect under the Referenced Libraries folder in the left pane of the Eclipse project structure, as shown below:

How to add POI libraries to Maven Java Project

You can add the poi and poi-ooxml jar files to the Maven project by mentioning the dependencies in pom.xml.

 <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.0.0</version>
</dependency>


<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.0.0</version>
</dependency>

You need to make sure that these two dependencies should be of the same version.

That’s it! We have downloaded and installed Apache POI.

Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!

How to connect to SQL Server using Java

HOME

jdbc:<driver protocol>:<driver connection details>
MS MySql Server - jdbc:odbc:DemoDSN
MySQL - jdbc:mysql://localhost:3306/demodb
Oracle - jdbc:orac;e:thin@myserver:1521:demodb

String dbUrl = "jdbc:mysql://localhost:3306/demo";
String username = "student";
String password = "student";

Connection conn = DriverManager.getConnection(dbUrl,username,password)
Statement stmt = conn.createStatement();

ResultSet result = stmt.executeQuery("select * from employee");

 java.sql and javax.sql
<dependency>
      <groupId>com.mysql</groupId>
      <artifactId>mysql-connector-j</artifactId>
      <version>8.2.0</version>
</dependency>

import java.sql.*;

public class JdbcTest {

    public static void main(String[] args) throws SQLException {

        Connection conn;
        Statement stmt = null;
        ResultSet result = null;

        String dbUrl = "jdbc:mysql://localhost:3306/demo";
        String username = "student";
        String password = "student1$";

        try {
            //Get a connection to database
            conn = DriverManager.getConnection(dbUrl, username, password);

            System.out.println("Database connection is successful\n");

            //Create a statement
            stmt = conn.createStatement();

            //Execute the SQL Query
            result = stmt.executeQuery("Select * from employees");

            //Process the result set
            while (result.next()) {
                System.out.println("First_Name :" + result.getString("first_name") + " , " + ("Last_Name :" + result.getString("last_name")));

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

create database if not exists demo;

use demo;

drop table if exists employees;

CREATE TABLE `employees` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `last_name` varchar(64) DEFAULT NULL,
  `first_name` varchar(64) DEFAULT NULL,
  `email` varchar(64) DEFAULT NULL,
  `department` varchar(64) DEFAULT NULL,
  `salary` DECIMAL(10,2) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

INSERT INTO `employees` (`id`,`last_name`,`first_name`,`email`, `department`, `salary`) VALUES (1,'Doe','John','john.doe@foo.com', 'HR', 55000.00);
INSERT INTO `employees` (`id`,`last_name`,`first_name`,`email`, `department`, `salary`) VALUES (2,'Public','Mary','mary.public@foo.com', 'Engineering', 75000.00);
INSERT INTO `employees` (`id`,`last_name`,`first_name`,`email`, `department`, `salary`) VALUES (3,'Queue','Susan','susan.queue@foo.com', 'Legal', 130000.00);

INSERT INTO `employees` (`id`,`last_name`,`first_name`,`email`, `department`, `salary`) VALUES (4,'Williams','David','david.williams@foo.com', 'HR', 120000.00);
INSERT INTO `employees` (`id`,`last_name`,`first_name`,`email`, `department`, `salary`) VALUES (5,'Johnson','Lisa','lisa.johnson@foo.com', 'Engineering', 50000.00);
INSERT INTO `employees` (`id`,`last_name`,`first_name`,`email`, `department`, `salary`) VALUES (6,'Smith','Paul','paul.smith@foo.com', 'Legal', 100000.00);

INSERT INTO `employees` (`id`,`last_name`,`first_name`,`email`, `department`, `salary`) VALUES (7,'Adams','Carl','carl.adams@foo.com', 'HR', 50000.00);
INSERT INTO `employees` (`id`,`last_name`,`first_name`,`email`, `department`, `salary`) VALUES (8,'Brown','Bill','bill.brown@foo.com', 'Engineering', 50000.00);
INSERT INTO `employees` (`id`,`last_name`,`first_name`,`email`, `department`, `salary`) VALUES (9,'Thomas','Susan','susan.thomas@foo.com', 'Legal', 80000.00);

INSERT INTO `employees` (`id`,`last_name`,`first_name`,`email`, `department`, `salary`) VALUES (10,'Davis','John','john.davis@foo.com', 'HR', 45000.00);
INSERT INTO `employees` (`id`,`last_name`,`first_name`,`email`, `department`, `salary`) VALUES (11,'Fowler','Mary','mary.fowler@foo.com', 'Engineering', 65000.00);
INSERT INTO `employees` (`id`,`last_name`,`first_name`,`email`, `department`, `salary`) VALUES (12,'Waters','David','david.waters@foo.com', 'Legal', 90000.00);

select * from demo.employees;

AssertJ – Fluent Assertions in Java

HOME

This tutorial describes the usage of the AssertJ – Fluent Assertions framework for writing tests in Java.

Introduction to AssertJ

The AssertJ project provides fluent assertion statements for test code written in Java. These assert statements are typically used with Java JUnit tests. 

AssertJ is composed of several modules:

A core module to provide assertions for JDK types (String, Iterable, Stream, Path, File, Map…​)
1. A Guava module to provide assertions for Guava types (Multimap, Optional…​)
2. A Joda Time module to provide assertions for Joda Time types (DateTime, LocalDateTime)
3. A Neo4J module to provide assertions for Neo4J types (Path, Node, Relationship…​)
4. A DB module to provide assertions for relational database types (Table, Row, Column…​)
5. A Swing module provides a simple and intuitive API for functional testing of Swing user interfaces

What is AssertJ Core?

AssertJ is a Java library that provides a rich set of assertions and truly helpful error messages, improves test code readability, and is designed to be super easy to use within any IDE.

AssertJ Core major versions depend on different Java versions:

  • AssertJ Core 3.x requires Java 8 or higher
  • AssertJ Core 2.x requires Java 7 or higher

AssertJ Core 3.x includes all AssertJ Core 2.x features and adds Java 8 specific ones (like exception assertions with lambdas).

Maven

<dependency>
    <groupId>org.assertj</groupId>
    <artifactId>assertj-core</artifactId>
    <version>3.22.0</version>
    <scope>test</scope>
</dependency>

Gradle

testImplementation 'org.assertj:assertj-core:3.22.0'

The Assertions class is the only class you need to start using AssertJ, it provides all the methods you need.

import static org.assertj.core.api.Assertions.*;

Verify that age is greater or equal to 50. This assertion will fail

int age = 20;
assertThat(age).isGreaterThanOrEqualTo(30);

There is another way to perform the same test. Don’t import the static package.

import org.assertj.core.api.Assertions;
int age = 20;

// Verify that age is greater or equal to 50
Assertions.assertThat(age).isGreaterThanOrEqualTo(30);

This assertion will pass.

int age = 50;

// Verify that age is greater or equal to 50
Assertions.assertThat(age).isGreaterThanOrEqualTo(30);

2. Array Assertions

For an Iterable or an Array there are multiple ways of asserting that their content exist. One of the most common assertions would be to check if an Iterable or Array contains a given element:

int age = 30;
List<Integer> ages = Arrays.asList(20, 25, 33, 45);

// Verify that ages list contains age(30) or not
Assertions.assertThat(ages).contains(age);

Verify if a list is empty or not

	List<String> names = Arrays.asList("Here", "Keep", "Ugly", "door", "time");

   @Test
	public void assertJAssertionsExample8() {
		Assertions.assertThat(names).isEmpty();

	}

Verify if a List starts with a given character. For example “Ugly”:

	List<String> names = Arrays.asList("Here", "Keep", "Ugly", "door", "time");

	@Test
	public void assertJAssertionsExample8() {

		// Verify that ages list contains age(30) or not
		Assertions.assertThat(names).startsWith("Ugly");

	}

Assert the size of the list

List<Integer> ages = Arrays.asList(20, 25, 33, 45);

// Verify that list ages contains 5 elements
Assertions.assertThat(ages).hasSize(5);

Chaining of assertions

AssertJ allows you to be concise by chaining multiple assertions.

int age = 30;
List<Integer> ages = Arrays.asList(20, 25, 33, 45);

// Verify that the list of age contains 20, and size of list is 4 and match the
// values of all elements
Assertions.assertThat(ages).contains(20).hasSize(4).allMatch(a -> a >= 10 && a <= 30);

3. Assertion description

It is often valuable to describe the assertion performed, especially for boolean assertions, where the default error message just complains that it got false instead of true (or vice versa).

You can set such a description as (String description, Object…​ args) but remember to do it before calling the assertion otherwise it is simply ignored as a failing assertion breaks the chained calls.

Example of a failing assertion with a description:

String name = "Happy Days are here";
Assertions.assertThat(name).as("check name").startsWith("Life");

The error message starts with the given description in [check name]

4. Assertions for Date

AssertJ provides special assertions for the Java date class.

LocalDateTime date1 = LocalDate.of(1992, 2, 14).atStartOfDay();
LocalDateTime date2 = LocalDate.of(1998, 1, 1).atStartOfDay();
Assertions.assertThat(date1).isEqualTo(date2);

LocalDateTime isAfter

LocalDateTime date1 = LocalDate.of(1992, 2, 14).atStartOfDay();
LocalDateTime date2 = LocalDate.of(1998, 1, 1).atStartOfDay();
Assertions.assertThat(date1).isAfter(date2);

LocalDateTime isBefore

LocalDateTime date1 = LocalDate.of(2025, 2, 14).atStartOfDay();
Assertions.assertThat(date1).isBefore(LocalDateTime.now());

5. Soft Assertions

Soft assertions AssertJ collects all assertion errors instead of stopping at the first one. Since soft assertions don’t fail at the first error, you need to tell AssertJ when to report the captured assertion errors, we are using assertAll().

SoftAssertions softly = new SoftAssertions();

softly.assertThat("George Martin").as("great authors").isEqualTo("JK Rowling");
softly.assertThat(42).as("comparison").isGreaterThan(120);
softly.assertThat("50").isEqualTo("23");

// Don't forget to call assertAll() otherwise no assertion errors are reported!
softly.assertAll();

6. Object Assertions

Objects can be compared in various ways, either to determine the equality of two objects or to examine the fields of an object.

public class AssertJEmployee {

	String name;
	int age;
	float salary;

	public AssertJEmployee(String name, int age, float salary) {
		super();
		this.name = name;
		this.age = age;
		this.salary = salary;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public float getSalary() {
		return salary;
	}

	public void setSalary(float salary) {
		this.salary = salary;
	}

}
@Test
public void test() {

	AssertJEmployee emp1 = new AssertJEmployee("Tim", 24, 24000);
	AssertJEmployee emp2 = new AssertJEmployee("Tim", 20, 24000);

	Assertions.assertThat(emp1).usingRecursiveComparison().isEqualTo(emp2);
}

In the below example, we have used isEqualTo() method that compares object references. We can see that both objects are the same but have different references. So, the assertion fails here.

@Test
public void test() {

	AssertJEmployee emp1 = new AssertJEmployee("Tim", 24, 24000);
	AssertJEmployee emp2 = new AssertJEmployee("Tim", 24, 24000);

	Assertions.assertThat(emp1).isEqualTo(emp2);
}

Congratulation! We are able to understand the use of AssertJ. Happy Learning!!

Reading Excel Data with Apache POI in Java

HOME

This tutorial describes how to read data from an Excel file in Java.

I’m using Apache POI to read the Excel file. To download and install Apache POI, refer here.

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.3.0</version>
</dependency>

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.3.0</version>
</dependency>

  • HSSFWorkbook  These class methods are used to read/write data to Microsoft Excel file in .xls format. It is compatible with MS-Office versions 97–2003.
  • XSSFWorkbook  These class methods are used to read-write data to Microsoft Excel in .xls or .xlsx format. It is compatible with MS-Office versions 2007 or later.

How to read Excel (.xlsx) from specific cell value?

Step 1 To locate the location of file.

File file = new File("C:\\Selenium_ReadTestData.xlsx");

Import File from package

import java.io.File;

Step 2 – Instantiate FileInputStream to read from the file specified.

 FileInputStream fis = new FileInputStream(file);

Step 3 Create object of XSSFWorkbook class

XSSFWorkbook wb = new XSSFWorkbook(fis);

Step 4  Import XSSFWorkbook from package

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

Step 5To read excel sheet by sheet name

XSSFSheet sheet1 = wb.getSheet("Read_TestData");

Step 6 Import XSSFSheetfrom package

import org.apache.poi.xssf.usermodel.XSSFSheet;

Step 7  To access data from the XLSX file, use of  the following methods:

getRow(int rownum)
getCell(int cellnum)
getStringCellValue()
getNumericCellValue()

Step 8  To get the cell value from column A and Row 1

 System.out.println(sheet1.getRow(0).getCell(0).getStringCellValue());

Here getRow(0) will look into the first row, and getCell(0) will look into the first column, i.e. A1.

To retrieve the String value we are making use of getStringCellValue in the end.

Below is the Excel which I’m using to read the data as mentioned below:-

We want to get the value of Row 1, Cell B

We want to get the value of Row 3, Cell A

import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadSpecificData {

	public static void main(String[] args) {
		
     String path = "C:\\Selenium_ReadTestData.xlsx";	

		try {
			
			//Create an object of FileInputStream class to read excel file
			FileInputStream fis = new FileInputStream(path);
			
			//Create object of XSSFWorkbook class
			XSSFWorkbook wb = new XSSFWorkbook(fis);
			
			//Read excel sheet by sheet name 
			XSSFSheet sheet1 = wb.getSheet("Read_TestData");
			
			//Get data from specified cell
			System.out.println(sheet1.getRow(1).getCell(1).getStringCellValue());
			System.out.println(sheet1.getRow(3).getCell(0).getStringCellValue());
			
		} catch (IOException e) {
			e.printStackTrace();
		}	

	}

}

How to read the entire Excel sheet?

To read the complete data from Excel, you can iterate over each cell of the row, present in the sheet. 

To get the last and first-row numbers, there are two methods in the sheet  class:

  • getLastRowNum() 
  • getFirstRowNum()
   int rowCount=sheet.getLastRowNum()-sheet.getFirstRowNum();	  

Once you get the row, you can iterate over the cells present in the row by using the total number of cells, which we can calculate using getLastCellNum() method:

int cellcount=sheet.getRow(1).getLastCellNum();

Below is the entire program to read complete Excel.

import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadExcelFile {
	public static  void main(String args[]) throws IOException {
		
		String path = "C:\\Selenium_ReadTestData.xlsx";
		
		//Create an object of FileInputStream class to read excel file
		FileInputStream fis = new FileInputStream(path);
		
		//Create object of XSSFWorkbook class
		Workbook workbook = new XSSFWorkbook(fis);
		
		//Read excel sheet by sheet name 
		Sheet sheet = workbook.getSheet("Read_TestData");
		
		
		//Find number of rows in excel file
	    int rowCount=sheet.getLastRowNum()-sheet.getFirstRowNum();	    
	    System.out.println("row count:"+rowCount);
		
		 //iterate over all the row to print the data present in each cell.
	    for(int i=0;i<=rowCount;i++){
	        
	        //get cell count in a row
	        int cellcount=sheet.getRow(i).getLastCellNum();	        
	   
	        //iterate over each cell to print its value       
	        for(int j=0;j<cellcount;j++){
	            System.out.print(sheet.getRow(i).getCell(j).getStringCellValue().toString() +"||");
	        }
	        System.out.println();
		}
	}
}

That’s it! We are done.

Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!

How to download and install Apache POI
Exception Handling in Java
Multiple Catch Exceptions
AssertJ – Fluent Assertions in Java
Polymorphism in Java

LinkedHashMap in Java

HOME

The LinkedHashMap Class is just like HashMap with an additional feature of maintaining an order of elements inserted into it. However, the linked hash map is based on both a hash table and a linked list to enhance the functionality of the hash map.

Create a LinkedHashMap object as shown below from:-

import java.util.LinkedHashMap;

Syntax of LinkedHashMap

LinkedHashMap<String, String> employeeDetail = new LinkedHashMap<String, String>();

LinkedHashMap<String, String> employeeDetail = new LinkedHashMap<>();

LinkedHashMap<String, Integer> employeeDetail = new LinkedHashMap<String, Integer>();

Adding the Elements

Below is an example where we are adding items to HashMap by using put() method.

import java.util.LinkedHashMap;

public class LinkedHashMap_Demo {
    public static void main(String a[]) {

        // Creating an empty LinkedHashMap
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>();

        // Adding entries in Map using put() method
        linkedHashMap.put("Tim", "DBA");
        linkedHashMap.put("Cillian", "SDET");
        linkedHashMap.put("Patrick", "BA");
        linkedHashMap.put("Brendan", "Dev");

        // Printing all entries inside Map
        System.out.println("Linked HashMap :" + linkedHashMap);

    }
}

Accessing an Element

To access a value in the LinkedHashMap, use the get() method and refer to its key:-

import java.util.LinkedHashMap;

public class LinkedHashMap_Demo {
    public static void main(String a[]) {

        // Creating an empty LinkedHashMap
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>();

        // Adding entries in Map using put() method
        linkedHashMap.put("Tim", "DBA");
        linkedHashMap.put("Cillian", "SDET");
        linkedHashMap.put("Patrick", "BA");
        linkedHashMap.put("Brendan", "Dev");

        // Printing all entries inside Map
        System.out.println("Linked HashMap :" + linkedHashMap);

        // Access a value
        System.out.println("Access Value of Key Patrick :" + linkedHashMap.get("Patrick"));

    }
}

Removing an Element

To remove an item, use the remove() method and refer to the key:

import java.util.LinkedHashMap;

public class LinkedHashMap_Demo {
    public static void main(String a[]) {

        // Creating an empty LinkedHashMap
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>();

        // Adding entries in Map using put() method
        linkedHashMap.put("Tim", "DBA");
        linkedHashMap.put("Cillian", "SDET");
        linkedHashMap.put("Patrick", "BA");
        linkedHashMap.put("Brendan", "Dev");

        // Printing all entries inside Map
        System.out.println("Linked HashMap :" + linkedHashMap);

        // Removing the mapping with Key Brendan
        linkedHashMap.remove("Brendan");

        // Printing the updated map
        System.out.println("Updated Map :" + linkedHashMap);

    }
}

To remove all items, use the clear() method:-

import java.util.LinkedHashMap;

public class LinkedHashMap_Demo {
    public static void main(String a[]) {

        // Creating an empty LinkedHashMap
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>();

        // Adding entries in Map using put() method
        linkedHashMap.put("Tim", "DBA");
        linkedHashMap.put("Cillian", "SDET");
        linkedHashMap.put("Patrick", "BA");
        linkedHashMap.put("Brendan", "Dev");

        // Printing all entries inside Map
        System.out.println("Linked HashMap :" + linkedHashMap);

        // Removing the mapping with Key Brendan
        linkedHashMap.clear();

        // Printing the updated map
        System.out.println("Updated Map :" + linkedHashMap);

    }
}

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMap_Demo {
    public static void main(String a[]) {

        // Creating an empty LinkedHashMap
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>();

        // Adding entries in Map using put() method
        linkedHashMap.put("Tim", "DBA");
        linkedHashMap.put("Cillian", "SDET");
        linkedHashMap.put("Patrick", "BA");
        linkedHashMap.put("Brendan", "Dev");

        // For-each loop for traversal over Map
        for (Map.Entry<String, String> mapElement : linkedHashMap.entrySet()) {

            String key = mapElement.getKey();

            // Finding the value
            // using getValue() method
            String value = mapElement.getValue();

            // Printing the key-value pairs
            System.out.println(key + " : " + value);
        }
    }
}

Methods in LinkedHashMap

import java.util.LinkedHashMap;

public class LinkedHashMap_Demo {
    public static void main(String a[]) {

        // Creating an empty LinkedHashMap
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>();

        // Adding entries in Map using put() method
        linkedHashMap.put("Tim", "DBA");
        linkedHashMap.put("Cillian", "SDET");
        linkedHashMap.put("Patrick", "BA");
        linkedHashMap.put("Brendan", "Dev");

        // Getting and printing value for a specific key
        System.out.println("Getting value for key 'Patrick' :" + linkedHashMap.get("Patrick"));

        // Getting size of Map using size() method
        System.out.println("Size of the map :" + linkedHashMap.size());

        // Checking whether Map is empty or not
        System.out.println("Is map empty? :" + linkedHashMap.isEmpty());

        // Using containsKey() method to check for a value
        System.out.println("Contains value 'SDET' "  + linkedHashMap.containsValue("SDET"));

        // Using containsKey() method to check for a key
        System.out.println("Contains key 'Brendan'? :" + linkedHashMap.containsKey("Brendan"));

        // Removing entry using remove() method
        System.out.println("Delete element 'Brendan' :" + linkedHashMap.remove("Brendan"));

        // Printing mappings to the console
        System.out.println("Mappings of LinkedHashMap :" + linkedHashMap);
        }
}

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Throw in Java

HOME

In Java we have already defined exception classes such as ArithmeticException, NullPointerException, ArrayIndexOutOfBounds exception etc. These exceptions are set to trigger on different conditions. For example when we divide a number by zero, this triggers ArithmeticException, when we try to access the array element out of its bounds then we get ArrayIndexOutOfBoundsException.


The Java throw keyword is used to throw an exception explicitly. We specify the exception object which is to be thrown. The Exception has some message with it that provides the error description. These exceptions may be related to user inputs, server, etc.

We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used to throw a custom exception.

throw Instance
Example:
throw new ArithmeticException("/ by zero");

Instance must be of type Throwable or a subclass of Throwable. For example Exception is a sub-class of Throwable and user defined exceptions typically extend Exception class.Data types such as int, char, floats or non-throwable classes cannot be used as exceptions.

The flow of execution of the program stops immediately after the throw statement is executed and the nearest enclosing try block is checked to see if it has a catch statement that matches the type of exception. If it finds a match, controlled is transferred to that statement otherwise next enclosing try block is checked and so on. If no matching catch is found then the default exception handler will halt the program.

public class Example1 {

	public static void test() {
		try {
			throw new ArithmeticException(" Hello ");
		} catch (ArithmeticException e) {
			System.out.println("Caught throw exception in method.");
			throw e; // rethrowing the exception
		}
	}

	public static void main(String args[]) {
		try {
			test();
		} catch (ArithmeticException e) {
			System.out.println("Caught exception in main.");
		}
	}
}

Output
Caught throw exception in method.
Caught exception in main.

Let us take another example where we have created the validate method that takes integer value as a parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message “Person is eligible to drive!!” .

public class Example1 {

	public static void validate(int age) {
		if (age < 18) {

			// throw Arithmetic exception if not eligible to drive
			throw new ArithmeticException("Person is not eligible to drive");
		} else {
			System.out.println("Person is eligible to drive!!");
		}
	}

	public static void main(String args[]) {
		validate(13);

	}
}

Exception in thread "main" java.lang.ArithmeticException: Person is not eligible to drive
	at ExceptionsExamples.Example1.validate(Example1.java:9)
	at ExceptionsExamples.Example1.main(Example1.java:16)

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!