Since Java 1.4, assertions have been like detectives in the Java world, helping developers expose hidden issues in their code and fix them.
Using the assert statement is like asking a detective to check something:
Short Version: assert expression1;
or
Full Version: assert expression1 : expression2;
expression1
is a simple check (true or false).expression2
is an optional additional message if something goes wrong.How it works:
expression1
) is false, the detective raises an alarm (AssertionError), optionally showing the extra message from expression2
.By default, assertions are asleep. To wake them up, use -ea
at the command line:
java -ea MyProgram
Let's see the detective in action with simple examples:
public class DetectiveExample {
public static void main(String[] args) {
int number = Integer.parseInt(args[0]);
assert number <= 10; // Stops if the number is greater than 10
System.out.println("All clear!");
}
}
If you run this with java -ea DetectiveExample 15
, it shouts:
Exception in thread "main" java.lang.AssertionError
at DetectiveExample.main(DetectiveExample.java:6)
But if you run it with java -ea DetectiveExample 8
, it says, "All clear!"
Here's another example with an optional message:
public class DetectiveMessage {
public static void main(String[] args) {
int argCount = args.length;
assert argCount == 5 : "There must be exactly 5 arguments";
System.out.println("Everything looks good!");
}
}