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.*;
  1. Simple Assertion

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 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 with 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 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 same, but has different reference. 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!!

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!!

Difference between == and equals() method in Java

HOME

What is == operator ?

To compare primitives and objects we use “==” equality operator in java which is a binary operator given in the java programming language

What is equals() method in java?

The Java String class equals() method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true.

Difference between == and equals method in java

1. == is an operator whereas equals() is a method of Object class.

2. == operator compares reference or memory location of objects in the heap, whether they point to the same location or not. Whenever we create an object using the operator new it will create a new memory location for that object. So we use the == operator to check memory location or address of two objects are the same or not.
equals() method  is used to compare the state of two objects or the contents of the objects.

3. Equals method can be overridden but you can’t override behavior of “==” operator.

Below is an example which shows the use of == and equals.

public class EqualsDemo1 {

	public static void main(String[] args) {
		String str1 = new String("JAVATUTORIAL");
		String str2 = new String("JAVATUTORIAL");

		// Reference comparison
		System.out.println("Check str1 == str2 : " + (str1 == str2));

		// Content comparison
		System.out.println("Check str1.equals(str2) : " + str1.equals(str2));

		// integer-type
		System.out.println("Check Integer Type :" + (10 == 10));

		// char-type
		System.out.println("Check Char Type :" + ('a' == 'a'));
	}
}

Output
Check str1 == str2 : false
Check str1.equals(str2) : true
Check Integer Type :true
Check Char Type :true

Let us take an example where both strings have same characters and same length but in lower case.

public class EqualsDemo2 {

	public static void main(String[] args) {
		String str1 = new String("JAVATUTORIAL");
		String str2 = new String("jAVATUTORIAL");

		// Reference comparison
		System.out.println("Check str1 == str2 : " + (str1 == str2));

		// Content comparison
		System.out.println("Check str1.equals(str2) : " + str1.equals(str2));
	}
}

Output
Check str1 == str2 : false
Check str1.equals(str2) : false

Let us take an example where both Integer refer to the same object.

public class EqualsDemo3 {

	public static void main(String[] args) {

		Integer i = new Integer(10);
		Integer j = i;

		System.out.println("Check i == j : " + (i == j));
}

Output
Check i == j : true

Let us take an example where both Integer1 and Integer2 refer to the different objects.

public class EqualsDemo4 {

	public static void main(String[] args) {

		Integer i = new Integer(10);
		Integer j = new Integer(10);

		System.out.println("Check i == j : " + (i == j));
	}
}

Output
Check i == j : false

That’s it for today. Have a wonderful learning.

Multiple questions on Exception Handling in Java

HOME

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

Example1

public class Example1 {

	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..");
	}
}

Output
Arithmetic Exception occurs
Continue the program..

Here, we have multiple catch blocks with a 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, now the program runs in normal flow.

Example2

public class Example2 {

	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..");
	}
}

Output
ArrayIndexOutOfBounds Exception occurs
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, now the program runs in normal flow.

Example3

public class Example3 {

	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, now the program runs in normal flow.

Example4

public class Example4 {

	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..");
	}
}

Output
Arithmetic Exception occurs
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 ArithmeticException. So, the catch block for ArithmeticException is executed. Once the corresponding catch block is executed, now the program runs in normal flow.

Example5

public class Example5 {

	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..");
	}
}
		

Output
Parent Exception occurs
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 Example6 {

	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..");
	}
}

Output
Unresolved compilation problems: 
Unreachable catch block for ArithmeticException. It is already handled by the catch block for Exception
Unreachable catch block for ArrayIndexOutOfBoundsException. It is already handled by the catch block for Exception

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

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

Output
Exception in thread "main" java.lang.ArithmeticException: / by zero

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 Example8 {

	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");
		}
	}
}

Output
Unresolved compilation problem: 
Unreachable catch block for ArrayIndexOutOfBoundsException. It is already handled by the catch block for Exception

Here, ArrayIndexOutOfBoundsException has been already caught by 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);
		}
	}
}

Output
a[1]=2
a[2]=3
a[3]=4
ArrayIndexOutOfBounds Exception occured

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

Example10

public class Example10 {

	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..");
	}
}

Output
going to divide by 0
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
No more inner try catch block
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 Example11 {

	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 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");
		}
	}
}

Output
java.lang.ArithmeticException: / by zero
Outer 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 Example12 {

	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");
		}
	}
}

Output
Arithmetic exception
inner try block 1

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 Example13 {

	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 catch block is not executed. finally block is always executed irrespective the catch block is executed or not.

Example14

public class Example14 {

	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 ..");
	}
}

Output
Inside the try block
finally block is always executed
Exception in thread "main" java.lang.ArithmeticException: / by zero

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 Example15 {

	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 ..");
	}
}

Output
Inside try block
Exception is handled
java.lang.ArithmeticException: / by zero
finally block is always executed
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 Example16 {

	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");
		}
	}
}

Output
a = 0
Divide by zero error
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 Example17 {

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

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

}

Output
Exception in thread "main" java.lang.ArithmeticException: / by zero

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

Example 18

public class Example18 {

	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 catch block only to handle the exceptions.

Example 19

public class Example19 {

	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 ..");
	}
}

Output
Exception in thread "main" Welcome to the Admission process!!
java.lang.ArithmeticException: Student is not eligible for admission

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

Example 20

public class Example20 {

	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");
	}
}

Output
try - first statement
start - myMethod
An Exception
finally
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 Example21 {

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

Output
Unresolved compilation problems: 
No exception of type int can be thrown; an exception type must be a subclass of Throwable

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 Example22 {

	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 ");
		}
	}
}

Output
Unresolved compilation problems: 
No exception of type Test can be thrown; an exception type must be a subclass of Throwable

Example 23

class Base extends Exception {
}

class Derived extends Base {
}

public class Example23 {

	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");
		}
	}
}

Output
Unresolved compilation problem: 
Unreachable catch block for Derived. It is already handled by the catch block for Base

Example 24

public class Example24 {

	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) {
		Example24 object = new Example24();
		object.A();
		object.display();
	}

}

Output
abdec

‘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 Example25 {

	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[]) {
		Example25 obj = new Example25();
		obj.p();
		System.out.println("Continue the program..");
	}
}

Output
Exception Handled
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 Example26 {

	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[]) {
		Example26 obj = new Example26();
		obj.p();
		System.out.println("Continue the program..");
	}
}

Output
Unresolved compilation problem: 
Unhandled exception type IOException

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 supposed to be handled, but as it is checked Exception which can not be handled by Exception.

Example 27

public class Example27 {

	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[]) {
		Example27 obj = new Example27();
		obj.p();
		System.out.println("Continue the program..");
	}
}

Output
Exception handled
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 Example28 {

	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);
	}
}

Output
Unresolved compilation problem: 
sum cannot be resolved to a variable

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

Example 29

public class Example29 {

	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!!");
		}
	}
}

Output
13
StringIndexOutOfBoundsException!!

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

Example 30

public class Example30 {

	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");
			}
		}
	}
}

Output
Number format exception occurred

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

Throws in Java

HOME

The throws keyword in Java is used in the signature of method to indicate that this method might throw one of the listed type of exceptions. The caller to these methods has to handle the exception using a try-catch block.

Syntax of throws

return_type method_name() throws ExceptionType1, ExceptionType2 …{  
//method code  
} 

As you can see from the above syntax, we can use throws to declare multiple exceptions.

Below is an example of throws exception. Here, as you can see IOException is listed as an exception. This exception is handled by a try catch block when findFile() method is called.

public class ThrowsExample {

	public static void findFile() throws IOException {

		File file= new File("C:\\test.txt");
		FileInputStream stream = new FileInputStream(file);

	}

	public static void main(String[] args) {
		try {
			findFile();
		} catch (IOException e) {
			System.out.println(e);
		}
	}
}

Output
java.io.FileNotFoundException: C:\test.txt (The system cannot find the file specified)

When we run this program, if the file test.txt does not exist, FileInputStream throws a FileNotFoundException which extends the IOException class.

If a method does not handle exceptions, the type of exceptions that may occur within it must be specified in the throws clause so that methods further up in the call stack can handle them or specify them using throws keyword themselves.

The findFile() method specifies that an IOException can be thrown. The main() method calls this method and handles the exception if it is thrown.

In a program, if there is a chance of raising an exception then compiler always warn us about it and compulsorily we should handle that checked exception, Otherwise we will get compile time error saying unreported exception XXX must be caught or declared to be thrown. To prevent this compile time error we can handle the exception in two ways: 

  1. We have caught the exception i.e. we have handled the exception using try/catch block.
  2. We have declared the exception i.e. specified throws keyword with the method.

Case 1 : Handle Exception Using try-catch block

In case we handle the exception, the code will be executed fine whether exception occurs during the program or not.

class Demo {
	void method() throws IOException {
		throw new IOException("IOException Occurred");
	}
}

public class TestThrowsExample2 {

	public static void main(String[] args) {
		try {
			Demo demo = new Demo();
			demo.method();
		} catch (Exception e) {
			System.out.println("Exception handled");
		}

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

Output
Exception handled
Continue the program...

Case 2: We declare the exception, if exception does not occur, the code will be executed fine.

class Test {
	void method() throws IOException {
		System.out.println("No Exception");
	}
}

public class TestThrowsExample3 {

	public static void main(String[] args) {
		try {
			Test test = new Test();
			test.method();
		} catch (Exception e) {
			System.out.println("Exception handled");
		}

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

Output
No Exception
Continue the program...

Case 3 :  We declare the exception and the exception occurs, it will be thrown at runtime because throws does not handle the exception.

class TestDemo {
	void method() throws IOException {
		throw new IOException("IOException Occurred");
	}
}

public class TestThrowsExample4 {

	public static void main(String[] args) throws IOException {
		TestDemo test = new TestDemo();
		test.method();
		System.out.println("Continue the program...");

	}

}

Output
Exception in thread "main" java.io.IOException: IOException Occurred

Access Modifiers in Java

HOME

There are two types of access modifiers in Java – access modifiers and non access modifiers.

The access modifier of Java specifies the scope of variable, method, constructor or class. We can change the access level of variables, methods, constructors, class by applying access modifiers to them.

There are 4 types of access modifiers.

  1. Private: The code is only accessible within the declared class. It cannot be accessed from outside the class.
  2. Default: The code is only accessible in the same package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.
  3. Protected: The code is accessible in the same package and subclasses. If you do not make the child class, it cannot be accessed from outside the package.
  4. Public: The class is accessible by any other class. It can be accessed from within the class, outside the class, within the package and outside the package.

Java Access Modifiers

Private

The private access modifier is accessible only within the class.

In this example, I have created one class – Demo_1 in package Parent_A. It contains private variable and private method. We can access private variables and methods within the class.

package Parent_A;

public class Demo_1 {

	private int x = 10; // private variable

	private void display() { // private method
		System.out.println("Display private method");
	}

	public static void main(String[] args) {

		Demo_1 obj1 = new Demo_1();

		System.out.println("Value of X :" + obj1.x);
		obj1.display();
	}

}

In the below example, we have 2 classes – Demo_1 and Demo_2. Class Demo_1 contains private data member and private method. We are accessing these private members from outside the class, another class Demo_2 so there is a compile-time error.

package Parent_A;

public class Demo_1 {

	private int x = 10; // private variable

	private void display() { // private method
		System.out.println("Display private method");
	}

}

package Parent_A;

public class Demo_2 {

	public static void main(String[] args) {

		Demo_1 obj1 = new Demo_1();
		System.out.println("Value of X :" + obj1.x);
		obj1.display();
	}

}

Private Constructor

In the below example, private constructor is accessible within the class.

package Parent_A;

public class Demo_1 {

	private int x = 10; // private variable

	private Demo_1() {

		System.out.println("Private Constructor");
	}

	private void display() { // private method
		System.out.println("Display private method");
	}

	public static void main(String[] args) {

		Demo_1 obj1 = new Demo_1();

	}
}

Output
Private Constructor

If you make any class constructor private, you cannot create the instance of that class from outside the class.

package Parent_A;

public class Demo_1 {

	private int x = 10; // private variable

	private Demo_1() {

		System.out.println("Private Constructor");
	}

	private void display() { // private method
		System.out.println("Display private method");
	}

}

package Parent_A;

public class Demo_2 {

	public static void main(String[] args) {

		Demo_1 obj1 = new Demo_1();
	}

}

Output
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The constructor Demo_1() is not visible

Default

If we don’t use any modifier, it is treated as default access modifier. The default modifier is accessible only within package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is more restrictive than protected, and public.

In this example, we have created two classes – Demo_1 and Demo_2 in package – Parent_A. We are accessing the class Demo_2 from within its package, since it is default, so it can be accessed from within the package.

package Parent_A;

public class Demo_1 {

	int x = 10; // default variable

	Demo_1() { // default constructor

		System.out.println("Default Constructor");
	}

	void display() { // default method
		System.out.println("Display default method");
	}

}



package Parent_A;

public class Demo_2 {

	public static void main(String[] args) {

		Demo_1 obj1 = new Demo_1();
		System.out.println("Value of X :" + obj1.x);
		obj1.display();
	}

}

Output
Default Constructor
Value of X :10
Display default method

Protected

The protected access modifier is accessible within package and outside the package but through inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It can’t be applied on the class.

In the below example, I have created the two packages Parent_A and Parent_B. The class Demo_1 of Parent_A package is public, so can be accessed from outside the package. But variable, constructor and method of this package is declared as protected, so it can be accessed from outside the class only through inheritance.

package Parent_A;

public class Demo_1 {

	protected int x = 10; // protected variable

	protected Demo_1() { // protected constructor

		System.out.println("Protected Constructor");
	}

	protected void display() { // protected method
		System.out.println("Display protected method");
	}

}


package Parent_B;

import Parent_A.Demo_1;

public class Demo_3 extends Demo_1 {

	public static void main(String[] args) {

		Demo_3 obj1 = new Demo_3();

		System.out.println("Value of X :" + obj1.x);
		obj1.display();

	}

}

Output
Protected Constructor
Value of X :10
Display protected method

Public

The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.

In the below example, I have created the two packages Parent_A and Parent_B. The variable, constructor and method of this package is declared as public, so it can be accessed from outside the class or outside the package also.

package Parent_A;

public class Demo_1 {

	public int x = 10; // public variable

	public Demo_1() { // public constructor

		System.out.println("Public Constructor");
	}

	public void display() { // public method
		System.out.println("Display public method");
	}

}

package Parent_B;

import Parent_A.Demo_1;

public class Demo_3 {

	public static void main(String[] args) {

		Demo_1 obj1 = new Demo_1();

		System.out.println("Value of X :" + obj1.x);
		obj1.display();

	}

}

Output
Public Constructor
Value of X :10
Display public method

Iterators in Java

HOME

‘Iterator’ is an interface which belongs to collection framework. It allows us to traverse the collection, access the data element and remove the data elements of the collection.

java.util package has public interface Iterator and contains three methods:

  1. boolean hasNext(): It returns true if Iterator has more element to iterate.
  2. Object next(): It returns the next element in the collection until the hasNext()method return true. This method throws ‘NoSuchElementException’ if there is no next element.
  3. void remove(): It removes from the underlying collection the last element returned by this iterator (optional operation). This method can be called only once per call to next(). The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.
  4. forEachRemaining – Performs the given action for each remaining element until all elements have been processed or the action throws an exception. Actions are performed in the order of iteration, if that order is specified. Exceptions thrown by the action are relayed to the caller.

Below is an example of use of Iterator. The iterator() method is used to get an iterator for any collection:

public class IteratorDemo {

   public static void main(String[] args) {

		ArrayList<String> cars = new ArrayList<String>();
		cars.add("Audi");
		cars.add("BMW");
		cars.add("Ford");
		cars.add("Duster");

		// Get the iterator
		Iterator<String> it = cars.iterator();

		// Print the first item
		System.out.println("First element from list :"+it.next());

	}
}

Output
First element from list :Audi

Looping through Collection

In the below example, we are looping through the collection using hasNext() and next() methods of Iterator.

public class IteratorDemo {

	 public static void main(String[] args) {

		ArrayList<String> cars = new ArrayList<String>();
		cars.add("Audi");
		cars.add("BMW");
		cars.add("Ford");
		cars.add("Duster");

		// Get the iterator
		Iterator<String> iterator = cars.iterator();

		System.out.println("List elements : ");

		while (iterator.hasNext())
			System.out.print(iterator.next() + " ");

		System.out.println();
	}
}

Output
List elements : 
Audi BMW Ford Duster 

Removing elements from Collection

Iterators are designed to easily change the collections that they loop through. The remove() method can remove items from a collection while looping. In the below example, I’m deleting the items whose reminder are not 0.

public class IteratorDemo {

	 public static void main(String[] args) {

		ArrayList<Integer> numbers = new ArrayList<Integer>();
		numbers.add(20);
		numbers.add(8);
		numbers.add(10);
		numbers.add(50);

        // Get the iterator
		Iterator<Integer> it = numbers.iterator();

		System.out.println("List of Numbers : ");
		while (it.hasNext()) {

			Integer i = it.next();

			if (i / 10 == 0) {
				it.remove();
			}
		}
		System.out.println(numbers);
	}

}

Output
List of Numbers : 
[20, 10, 50]

I hope you are cleared about Iterators now. Enjoy learning. Cheers!!

HashMap in Java

HOME

A HashMap store items in “key/value” pairs, and you can access them by an index of another type (e.g. a String).

One object is used as a key (index) to another object (value). It can store different types: String keys and Integer values, or the same type, like: String keys and String values. We need to import java.util.HashMap or its super class in order to use the HashMap class and methods.

It is not an ordered collection which means it does not return the keys and values in the same order in which they have been inserted into the HashMap.

Create a HashMap object as shown below from:-

import java.util.HashMap;

Syntax of HashMap

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

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

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

Add Items

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

public class HashMapDemo {

	public static void main(String[] args) {

		/* This is how to declare HashMap of key and Value as String  */
		HashMap<String, String> employeeDetail = new HashMap<String, String>();

		// Add keys and values (Name, Designation)
		employeeDetail.put("Tim", "DBA");
		employeeDetail.put("Dong", "SDET");
		employeeDetail.put("Nisha", "BA");
		employeeDetail.put("Ulana", "Dev");

		System.out.println("Detail of Employees");
		System.out.println(employeeDetail);
	}
}

Output
Detail of Employees
{Dong=SDET, Tim=DBA, Nisha=BA, Ulana=Dev}

Below is an example where we are adding items to HashMap by using put() method. Here, key is String and Value as Integer.

public class HashMapDemo {

	public static void main(String[] args) {

		// Combination of String(key) and Integer(value)
		HashMap<String, Integer> employeeAge = new HashMap<String, Integer>();

		// Add keys and values (Name, Age)
		employeeAge.put("Tim", 25);
		employeeAge.put("Dong", 26);
		employeeAge.put("Nisha", 29);
		employeeAge.put("Ulana", 34);

		System.out.println("Age of Employees");
		System.out.println(employeeAge);
    }
}

Output
Age of Employees
{Dong=26, Tim=25, Nisha=29, Ulana=34}

Access an Item

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

public class HashMapDemo {

	public static void main(String[] args) {

		// Combination of String(key) and Integer(value)
		HashMap<String, Integer> employeeAge = new HashMap<String, Integer>();

		// Add keys and values (Name, Age)
		employeeAge.put("Tim", 25);
		employeeAge.put("Dong", 26);
		employeeAge.put("Nisha", 29);
		employeeAge.put("Ulana", 34);

		System.out.println("Age of Employees");
		System.out.println(employeeAge);

		// Access a value
		System.out.println("Access Value of Key Nisha");
		System.out.println(employeeAge.get("Nisha"));
   }
}

Output
Access Value of Key Nisha
29

Remove an Item

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

public class HashMapDemo {

	public static void main(String[] args) {

		// Combination of String(key) and Integer(value)
		HashMap<String, Integer> employeeAge = new HashMap<String, Integer>();

		// Add keys and values (Name, Age)
		employeeAge.put("Tim", 25);
		employeeAge.put("Dong", 26);
		employeeAge.put("Nisha", 29);
		employeeAge.put("Ulana", 34);

		System.out.println("Age of Employees");
		System.out.println(employeeAge);

		// To remove an item, use the remove() method and refer to the key
		employeeAge.remove("Ulana");
		System.out.println("List of Employee after removing Ulana :" + employeeAge);
   }
}

Output
Age of Employees
{Dong=26, Tim=25, Nisha=29, Ulana=34}
List of Employee after removing Ulana :{Dong=26, Tim=25, Nisha=29}

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

public class HashMapDemo {

	public static void main(String[] args) {

		// Combination of String(key) and Integer(value)
		HashMap<String, Integer> employeeAge = new HashMap<String, Integer>();

		// Add keys and values (Name, Age)
		employeeAge.put("Tim", 25);
		employeeAge.put("Dong", 26);
		employeeAge.put("Nisha", 29);
		employeeAge.put("Ulana", 34);

		System.out.println("Age of Employees");
		System.out.println(employeeAge);

		// To remove all items, use the clear() method:
		employeeAge.clear();
		System.out.println("List of Employes after clear:" + employeeAge);
   }
}

Output
Age of Employees
{Dong=26, Tim=25, Nisha=29, Ulana=34}
List of Employes after clear:{}

Checking whether HashMap is empty or not

We are using isEmpty() method of HashMap class to perform this check.

public class HashMapDemo1 {

	public static void main(String[] args) {

		/* This is how to declare HashMap */
		HashMap<String, String> employeeDetail = new HashMap<String, String>();

		// Add keys and values (Name, Designation)
		employeeDetail.put("Tim", "DBA");
		employeeDetail.put("Dong", "SDET");
		employeeDetail.put("Nisha", "BA");
		employeeDetail.put("Ulana", "Dev");

		System.out.println("Detail of Employees");
		System.out.println(employeeDetail);

		// Checking whether HashMap is empty or not
		System.out.println("Is HashMap Empty? " + employeeDetail.isEmpty());

		// Delete all items from HasMap
		employeeDetail.clear();

		System.out.println("Is HashMap Empty now? " + employeeDetail.isEmpty());
    }
}

Output
Detail of Employees
{Dong=SDET, Tim=DBA, Nisha=BA, Ulana=Dev}
Is HashMap Empty? false
Is HashMap Empty now? true

Check if a particular key exists in HashMap

We will be using containsKey() method of HashMap class to perform this check.  This method returns a boolean value.

public class HashMapDemo1 {

	public static void main(String[] args) {

		/* This is how to declare HashMap */
		HashMap<String, String> employeeDetail = new HashMap<String, String>();

		// Add keys and values (Name, Designation)
		employeeDetail.put("Tim", "DBA");
		employeeDetail.put("Dong", "SDET");
		employeeDetail.put("Nisha", "BA");
		employeeDetail.put("Ulana", "Dev");

		System.out.println("Detail of Employees");
		System.out.println(employeeDetail);

		// Check if a particular key exists in HashMap
		boolean flag = employeeDetail.containsKey("Nisha");
		System.out.println("Key Nisha exists in HashMap? : " + flag);

		boolean flag1 = employeeDetail.containsKey("Shawn");
		System.out.println("Key Shawn exists in HashMap? : " + flag1);
    }
}

Output
Detail of Employees
{Dong=SDET, Tim=DBA, Nisha=BA, Ulana=Dev}
Key Nisha exists in HashMap? : true
Key Shawn exists in HashMap? : false

Check if a particular value exists in HashMap

We will be using containsValue() method of HashMap class to perform this check.

public class HashMapDemo1 {

	public static void main(String[] args) {

		/* This is how to declare HashMap */
		HashMap<String, String> employeeDetail = new HashMap<String, String>();

		// Add keys and values (Name, Designation)
		employeeDetail.put("Tim", "DBA");
		employeeDetail.put("Dong", "SDET");
		employeeDetail.put("Nisha", "BA");
		employeeDetail.put("Ulana", "Dev");

		System.out.println("Detail of Employees");
		System.out.println(employeeDetail);

		// Check if a particular value exists in HashMap
		boolean valueExists = employeeDetail.containsValue("Dev");
		System.out.println("String Dev exists in HashMap? : " + valueExists);

		boolean valueNotExists = employeeDetail.containsValue("Test");
		System.out.println("String Test exists in HashMap? : " + valueNotExists)
    }
}

Output
Detail of Employees
{Dong=SDET, Tim=DBA, Nisha=BA, Ulana=Dev}
String Dev exists in HashMap? : true
String Test exists in HashMap? : false

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

How to set style in Excel in Java using Apache POI

HOME

In the previous tutorial, I have explained about How to add Formulas in Excel in Java. In this tutorial, I will explain How to customize the style of cells in Excel in Java using Apache POI.

I’m using Apache POI to write data to the excel file. To download and install Apache POI, refer here.

If you are using maven, then you need to add below dependency 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>

To know more about various interfaces and classes for managing Excel, please refer to this tutorial.

In the below example, I have an existing excel with the name of “EmployeeDetails.xlsx”.

Steps to Customize the style in Excel

Step 1 – Create a blank work and then a sheet with name Write_TestData.

XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Write_TestData");

Step 2- XSSFWorkbook and XSSFSheet are imported from the below consecutive packages.

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

Step 3 – Write data to the sheet. To know more about this part, refer this link.

Step 4 – Set the auto Size for column 0.

sheet.autoSizeColumn(0);

Step 5 – To create a cell style, we only need a reference to the excel workbook:

	CellStyle style = workbook.createCellStyle();

Step 6 – CellStyle is imported from package mentioned below.

import org.apache.poi.ss.usermodel.CellStyle;

Step 7 – To create font style and add attributes to this font

XSSFFont font = workbook.createFont();

Step 8 – XSSFFont is imported from below package

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

Step 9 – To set the Background Colour of the cell.

style.setFillForegroundColor(IndexedColors.BLUE_GREY.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

Step 10 – BackgroundColor and FillPattern are imported from the below consecutive packages.

import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.FillPatternType;

Step 11 – Write data to an OutputStream. Use the below code to write output stream.

FileOutputStream out = new FileOutputStream(new File("Styled_EmployeeDetails.xlsx"));
workbook.write(out);

Below is the complete program to show various cell setyles for Row 0 (Header Row).

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;

import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelStyleExample {

	public static void main(String[] args) {

		try {
			// create blank workbook
			XSSFWorkbook workbook = new XSSFWorkbook();

			// Create a blank sheet
			XSSFSheet sheet = workbook.createSheet("Write_TestData");

			ArrayList<Object[]> data = new ArrayList<Object[]>();
			data.add(new String[] { "Name", "Id", "Salary" });
			data.add(new Object[] { "Jim Lawrence", "001A", 10000 });
			data.add(new Object[] { "Jack", "1001B", 40000 });
			data.add(new Object[] { "Tim", "2001C", 20000 });
			data.add(new Object[] { "Gina", "1004S", 30000 });

			// Iterate over data and write to sheet
			int rownum = 0;
			for (Object[] employeeDetails : data) {

				// Create Row
				XSSFRow row = sheet.createRow(rownum++);

				int cellnum = 0;
				for (Object obj : employeeDetails) {

					// Create cell
					XSSFCell cell = row.createCell(cellnum++);

					// Set value to cell
					if (obj instanceof String)
						cell.setCellValue((String) obj);
					else if (obj instanceof Double)
						cell.setCellValue((Double) obj);
					else if (obj instanceof Integer)
						cell.setCellValue((Integer) obj);

					// Set Column width to the maximum for Column 0
					sheet.autoSizeColumn(0);

					if (rownum == 1) {

						CellStyle style = null;

						// Creating a font
						XSSFFont font = workbook.createFont();

						font.setFontHeightInPoints((short) 10);
						font.setFontName("Verdana");
						font.setColor(IndexedColors.BLACK.getIndex());
						font.setBold(true);
						font.setItalic(false);

						// Creating cell Style
						style = workbook.createCellStyle();

						// Setting Foreground Colour
						style.setFillForegroundColor(IndexedColors.BLUE_GREY.getIndex());
						style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

						// Setting Alignment of font
						style.setAlignment(HorizontalAlignment.CENTER);

						// Setting font to style
						style.setFont(font);

						// Setting cell style
						cell.setCellStyle(style);

					}
				}
			}

			// Write the workbook in file system
			FileOutputStream out = new FileOutputStream(new File("Styled_EmployeeDetails.xlsx"));
			workbook.write(out);

			System.out.println("Style of Excel is updated successfully");

			out.close();

			// Close workbook
			workbook.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

How to add Formulas in Excel in Java

HOME

In the previous tutorial, I have explained How to update data in existing excel in Java. In this Java Excel tutorial, I will explain how to create an Excel with formula in a Java program. Excel is very excellent in calculating formulas. The Apache POI library provides excellent support for working with formulas in Excel.

I’m using Apache POI to write data to the excel file. To download and install Apache POI, refer here.

If you are using maven, then you need to add below dependency 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>

To know about various Interfaces and Classes in Excel, please refer this link.

Below are the steps which explain how to add Formulas in Excel.

Step 1 – Create a blank workbook.

XSSFWorkbook workbook = new XSSFWorkbook();

Step 2 – Import XSSFWorkbook from package.

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

Step 3 – Create a sheet and pass name of the sheet.

XSSFSheet sheet = workbook.createSheet("Calculate Salary");

Step 4 – Import XSSFSheet from package.

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

Step 5 – Create a Row. A spreadsheet consists of rows and cells. It has a grid layout. I have created object called Header of XSSFRow.

	XSSFRow header = sheet.createRow(0);

Step 6 – Below syntax create new cells within the row at index 0 and set a string value for the cell.

header.createCell(0).setCellValue("Employee_Name");

Step 7 – Below syntax creates a cell at index 4 and sets formula for cell.

dataRow.createCell(4).setCellFormula("B2+C2+D2");

Step 8 – The following line of code sets formula for the cell at the row #1 and column #5 (remember index is 0-based):

In case the column (Cell) does not exist (but the row does), use the following code.

XSSFRow dataRow = sheet.createRow(1);
dataRow.createCell(5).setCellFormula("SUM(B2:C2)");

In the above line, note that you should make sure that the cell at position (1, 5) does exist, otherwise you get a NullPointerException.

Let us see a program where I have created a cell which contains the formula.

public class FormulaExample {

	public static void main(String[] args) {

		// Create object of XSSFWorkbook class
		XSSFWorkbook workbook = new XSSFWorkbook();

		// Create object of XSSFSheet class
		XSSFSheet sheet = workbook.createSheet("Calculate Salary");

		// Create Header row using XSSFRow class
		XSSFRow header = sheet.createRow(0);
		header.createCell(0).setCellValue("Employee_Name");
		header.createCell(1).setCellValue("Base_Salary");
		header.createCell(2).setCellValue("Variable_Pay");
		header.createCell(3).setCellValue("Other_Benefits");
		header.createCell(4).setCellValue("Total Salary");
		header.createCell(5).setCellValue("Base_Variable Salary");

		XSSFRow dataRow = sheet.createRow(1);
		dataRow.createCell(0).setCellValue("George");
		dataRow.createCell(1).setCellValue(5000);
		dataRow.createCell(2).setCellValue(650);
		dataRow.createCell(3).setCellValue(1200);

		// Set formula
		dataRow.createCell(4).setCellFormula("B2+C2+D2");
		dataRow.createCell(5).setCellFormula("SUM(B2:C2)");

		try {

			// Write the workbook in file system
			FileOutputStream out = new FileOutputStream(new File("Salary_Slip.xlsx"));
			workbook.write(out);
			out.close();
			System.out.println("Excel written successfully.");

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

		}
	}
}

That’s it! Well Done! Cheers!!

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