Chapters
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
Shorter version
assert keyword has two forms. These are:
The first form will throw
This example demonstrates the first form of assert keyword.
Then, if
Next, This example demonstrates the second form of assert keyword.
Don't forget to omit
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 commandjava -enableassertions program-nameShorter version
java -ea program-name
assert keyword has two forms. These are:
assert expression1assert expression1 : expression2The 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 SampleClassThen, 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