assertion statement in java

July 28, 2020 | No comments

Assert in Java Code

An assertion is a java statement. An assertion statement is used in the code to ensures the correctness of any assumptions on which the program depends.  When the java runtime executes the assert statement it will throw assertion exception. Assertion helps in maintaining the invariants in a program under check. We will explore how to use the assertion statement with an example.

Syntax for assertion

The following are the two different syntaxes for using assertion.
First way
If the expression is false the assert statement will throw java.lang.AssertionError
assert expression;
Second way
With two expressions where expression1 must be a boolean expression. and expression2 must return a value (must not return void). if exprerssion1 is false, the assert statement will throw java.lang.AssertError with expression2 as the message
assert expression1 : expression2;
By default assertion is disabled we can enable it by setting the jvm parameter ea or enableassertions.

Enabling assertion

By default, assertions are disabled in Java. If assertions are disabled, assertion statements do not have any effects. In order to enable them, we use the following command
java -ea JavaAssertionTest
(or)
java -enableassertions JavaAssertionTest

Example

In the following example, we have a Movie object containing movie name and minAge. From the main class we create a movie object and call the play method only if the minimum age requirement is met.
Movie.java
class Movie {
	private String title;
	private int minAge;

	public Movie(String title, int age) {
		this.title = title;
		this.minAge = age;
	}

	public void play() {
		System.out.print("Playing movie:  " + title);
	}

	public String getTitle() {
		return title;
	}

	public int getAgeRestriction() {
		return minAge;
	}
}
JavaAssertionTest
public class JavaAssertionTest {
	public static void main(String[] args) {
		Movie movieA = new Movie("movie 007 James bond", 11);
		Movie movieB = new Movie("movie Transformers", 18);

		//We want to play only movies suitable for age 11 or under
		assert (movieA.getAgeRestriction() <= 18);
		movieA.play();
		
		assert (movieB.getAgeRestriction() <= 11): "Underage for movie" + movieB.getTitle();
		movieB.play();
		
		System.out.println("played with all movies");
	}
}
Running the above example will result in the following output.
Console Output
Playing movie movie 007 James bond Exception in thread "main" java.lang.AssertionError: Underage for moviemovie Transformers at JavaAssertionTest.main(JavaAssertionTest.java:12)
Note in the above case the moment the assertion error is thrown, the program will exit.

Handling AssertionErrror

If an assertion error occurs the program will throw exception and exit. If we want to handle the assertion error, we can put the assert statement within a try-catch block. And in the catch block, we can have our logic if assert statement. The following example shows the same.
With Try Catch block
public static void main(String[] args) {
		Movie movieA = new Movie("movie 007 James bond", 11);
		Movie movieB = new Movie("movie Transformers", 18);
		
		System.out.println("Start playing movies");
		
		//We want to play only movies suitable for age 11 or under
		assert (movieA.getAgeRestriction() <= 18);
		movieA.play();
		
		try {
			assert (movieB.getAgeRestriction() <= 11): "Underage for movie with title:: " + movieB.getTitle();
			movieB.play();
		}catch (AssertionError e) {
			System.out.println("Oops this movie cannot be played because " + e.getMessage());
		}
		
		System.out.println("played with all movies");
	}
Console output
Start playing movies Playing movie: movie 007 James bond Oops this movie cannot be played because Underage for movie with title:: movie Transformers played with all movies
Summary
  • assertions are a great way to confirm program invariants hold true.
  • we have two different syntaxes for writing assertion in java.
  • by default assertions are turned off, we can turn on using JVM flag.
  • if an assert statement fails, the program will throw AssertionError and exit.
  • we can catch AssertionError, and still get hold control of the program.

No comments :

Post a Comment

Please leave your message queries or suggetions.