top of page
Search

Assert :Understanding Assert in Java: A Quick Guide

The  ASSERT  keyword in java helps quickly verify some assumptions or program state/variable values.

Its a Keyword since Java 1.4


How to Use it:


public class AssertExample {

   public static void main(String[] args) {

       int age = 16;


       // Assert that age must be >= 20

       assert age >= 20 : "Age must be 20 or older";


       System.out.println("Age is: " + age);

   }

}



Output:


By default, IntelliJ does not enable assertions when you run a program. That means:

  • If you run normally (without -ea), the assert line is ignored by IntelliJ IDE or command line as well.

So normally it should print Age is: 16.(In IntelliJ ,just ad vm options as -ea in RunConfigurations, and it will be enabled).


So in command line , running it with enable-Assert Switch, it prints the required output.

java -ea AssertExample

Exception in thread "main" java.lang.AssertionError: Age must be 20 or older

       at AssertExample.main(AssertExample.java:6)



But in leetCode or online Java editor say :https://app.coderpad.io/

while Running this program gives this output:

Exception in thread "main" java.lang.AssertionError: Age must be 20 or older

   at Solution.main(Solution.java:24)


Where is ASSERT used in JAVA:

The assert keyword is used when debugging code. The assert keyword lets you test if a condition in your code returns True, if not, the program will raise an AssertionError. You can write a message to be written if the code returns False

Keep in Mind:

The assert keyword in Java is a keyword of the Java language itself, not a method defined within a specific class. It was introduced in JDK 1.4.

When an assert statement fails (meaning its boolean condition evaluates to false), it throws an AssertionError. The AssertionError class is part of the java.lang package, but to re-emphasize the assert keyword itself is a fundamental language construct and does not belong to a class.


 
 
 

Recent Posts

See All

Comments


bottom of page