Thursday, January 20, 2022

Java Tutorial: assert Keyword

Chapters

assert Keyword

This keyword is used for making assumptions during debugging. This keyword can be helpful when we're trying to fix or detect bugs in our program. By default, assert keyword is disabled at runtime. To enable it at runtime, we need to add additional command when we run our program.

On command prompt, we typically type java program-name to run a program. If we want to enable assert keyword, we type this command
java -enableassertions program-name
Shorter version
java -ea program-name

assert keyword has two forms. These are:
assert expression1
assert expression1 : expression2
The first form will throw java.lang.AssertionError if the expression1(boolean-expression) is false. The second form will throw java.lang.AssertionError with additional message(expression2).

This example demonstrates the first form of assert keyword.
import java.util.Random;

public class SampleClass{

  public static void main(String[] args){
    Random rand = new Random();
    
    int num = rand.nextInt(10);
    
    assert num > 5;
    
    System.out.println("num: " + num);
  }
}
We can run the example above like this:
java -ea SampleClass
Then, if num is less than 5, the assert keyword will throw java.lang.AssertionError once the execution executes the line where the assert keyword resides. Otherwise, the println() will be executed.

Next, This example demonstrates the second form of assert keyword.
import java.util.Random;

public class SampleClass{

  public static void main(String[] args){
    Random rand = new Random();
    
    int num = rand.nextInt(10);
    
    assert (num % 2) == 0 : num + " is odd!";
    
    System.out.println("num: " + num);
  }
}
If num is odd, the result would be like this:
Exception in thread "main" java.lang.AssertionError: 1 is odd!
at SampleClass.main(SampleClass.java:10)



Don't forget to omit -ea command and its long version once your program is ready for distribution. Only enable assertion during development.

No comments:

Post a Comment