Since Java 1.4, assertions have been like detectives in the Java world, helping developers expose hidden issues in their code and fix them.

1. How to Use the Assert Detective

Using the assert statement is like asking a detective to check something:

How it works:

2. Turning On Assertions

By default, assertions are asleep. To wake them up, use -ea at the command line:

java -ea MyProgram

3. Detective Stories: Examples

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!");
    }
}