AppDividend
Latest Code Tutorials

Assertion in Java Example | Java Assertion Tutorial

0

An assertion in Java Example | Java Assertion Tutorial is today’s topic. Suppose there is a condition that you, as a programmer or a developer, while testing your code, want to make sure exists, such as making sure that a particular method shall return only negative values; Java has a (relatively) new feature made available just for that. It is a feature called assertion, and wherein one can assert the existence of a particular condition. It is done with the help of the keyword assert. Assertions are generally used for testing and scarcely used in release code. Release code is usually run with assertions disabled.

#Why to use Assertions

  1. We can make sure that an unreachable looking code is unreachable.
  2. We can make sure that assumptions written in comments are right.
             if ((x & 1) == 1)  
             {  }
             else // x must be even 
             { assert (x % 2 == 0); }
  3. We can make sure the default switch case is not reached.
  4. We can check the object’s state.
  5. At the beginning of the method
  6. After the method invocation.

#Assertion Vs. Normal Exception Handling

Assertions are mainly used to check the logically impossible situations. i.e., they can be used to check the state the code expects before it starts running or state after it finishes the running. Unlike the normal exception/error handling, assertions are generally disabled at the run-time.

#Where to use Assertions

  1. Arguments to private methods. Private arguments are provided by the developer’s code only, and the developer may want to check his/her assumptions about the arguments.
  2. Conditional cases.
  3. Conditions at the beginning of any method.

#Where not to use Assertions

  1. Assertions should not be used to replace the error messages
  2. Assertions should not be used to check the arguments in the public methods as the user may provide them. Error handling should be used to handle the errors provided by the user.
  3. Assertions should not be used on the command line arguments.

Assertion in Java Example

The Java assert keyword was introduced in the Java 1.4, so it’s been around for quite a while. However, it remains the little-known keyword that can drastically reduce the boilerplate and make our code more readable.

For example, often in our code, we need to verify certain conditions that might prevent our application from working correctly.

With the use of an assert statement, if the condition holds at run time, then no action is taken; otherwise, an AssertionError is thrown.

The assert keyword has two forms. They are:

  1. assert condition;
  2. assert condition: expression;

#assert condition

In this form of the assert statement, a condition is mentioned, which is an expression which must evaluate to a Boolean result. If the condition does not hold at run time, an AssertionError will be thrown; otherwise, the program will continue uninterrupted.

See the following code example.

import java.util.*;

class NewClass{
	int checkOdd(int x){
		if(x%2!=0) return 1;

		return 0;
	}
}


class AssertEx1{
	public static void main(String [] args){
		NewClass obj = new NewClass();
		Scanner sc = new Scanner(System.in);

		System.out.print("Enter an odd integer: ");

		int a;
		a = sc.nextInt();

		int b;
		b = obj.checkOdd(a);

		assert b==1;
	}
}

Note: To check for assertions at runtime, assertions need to be enabled. To enable assertions, while running the above file, the following terminal command is used while running the file.

See the following output.

 

Assertion in Java Example

#assert condition: expression

In this form of the assert statement, a condition which must evaluate to a Boolean result is mentioned, and along with that, an expression which is to be printed with the error message is also included. If the condition does not hold at run time, an AssertionError will be thrown, which will also have the expression printed along with it; otherwise, the program will continue uninterrupted.

See the following code.

import java.util.*;

class NewClass {
	int checkOdd(int x) {
		if (x % 2 != 0)
			return 1;

		return 0;
	}
}

class AssertEx1 {
	public static void main(String[] args) {
		NewClass obj = new NewClass();
		Scanner sc = new Scanner(System.in);

		System.out.print("Enter an odd integer: ");

		int a;
		a = sc.nextInt();

		int b;
		b = obj.checkOdd(a);

		assert b == 1;
	}
}

See the following output.

 

assert condition in Java

#Enabling and Disabling Assertions

The assertions feature of Java is generally used while testing code, and therefore, assertions are enabled while testing, and they are disabled in release code.

To enable assertions for a package NewPack (and all of its sub packages), for example, use the following while running the file, and end with three periods:

-ea: NewPack…

To disable assertions for the same, use the following while running the file, and end with three periods:

-da: NewPack…

An individual class name NewClass, for example, can also be mentioned for enabling or disabling assertions as follows:

-ea: NewClass

#Handling an AssertionError

The class AssertionError extends an Error, which itself extends the Throwable. It means that AssertionError is the unchecked exception.

Therefore methods that use the assertions are not required to declare them, and further calling code should not try and catch them.

AssertionErrors are meant to indicate the unrecoverable conditions in an application, so never try to handle them or attempt recovery.

#Improper use of assertions

As assertions can be either enabled or disabled while running the code, one must not include necessary code inside of an assert statement. This is because if assertions are disabled, then the execution will be carried on in a logically inconsistent manner, and therefore, Java does not allow this. In such a scenario, the Java compiler will not allow the code to be compiled.

See the following example program.

import java.util.*;

class NewClass{
	int checkOdd(int x){
		if(x%2!=0) return 1;

		return 0;
	}
}


class AssertEx3{
	public static void main(String [] args){
		NewClass obj = new NewClass();
		Scanner sc = new Scanner(System.in);

		System.out.print("Enter an odd integer: ");

		int a;
		a = sc.nextInt();

		int b;
		assert(b = obj.checkOdd(a)) == 1;

		System.out.println(b);
	}
}

See the following output.

 

Improper use of assertions

#Best Practices

The most important thing to remember about the assertions is that they can be disabled, so never assume they’ll be executed.

Therefore keep the followings things in mind when using assertions:

  1. Always check for the null values and empty Optionals where appropriate.
  2. Avoid using assertions to check inputs into the public method and instead use a checked exception such as IllegalArgumentException or NullPointerException.
  3. Don’t call methods in the assertion conditions and instead assign the result of the method to a local variable and use that variable with an assert.
  4. Assertions are great for places in the code that will never be executed, such as the default case of the switch statement or after a loop that never finishes.

Finally, Assertion in Java Example | Java Assertion Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.