⬅ Previous Topic
Java abstract KeywordNext Topic ⮕
Java boolean Keyword⬅ Previous Topic
Java abstract KeywordNext Topic ⮕
Java boolean Keywordassert
Keyword in JavaThe assert
keyword in Java is used to perform sanity checks during development. Assertions are like internal self-checks in your code. They're especially useful for catching bugs early by making sure certain conditions are always true at runtime.
assert
?Think of assertions as a form of internal documentation that actively runs and alerts you when something unexpected happens. If an assertion fails, the program throws an AssertionError
and stops execution at that point. Assertions are typically used during development and testing, not in production environments.
assert
assert condition;
Or with a custom error message:
assert condition : "Error Message";
By default, assertions are disabled in the JVM. You must explicitly enable them using the -ea
flag while running the program:
java -ea YourClassName
public class AssertDemo {
public static void main(String[] args) {
int age = 20;
assert age > 18;
System.out.println("Age is valid");
}
}
Age is valid
Here, since age > 18
is true, the assertion passes and execution continues normally.
public class AssertFailDemo {
public static void main(String[] args) {
int age = 16;
assert age > 18;
System.out.println("This line won't be printed");
}
}
Exception in thread "main" java.lang.AssertionError
The program stops with an AssertionError
because the condition age > 18
is false.
public class AssertMessageDemo {
public static void main(String[] args) {
int number = -5;
assert number >= 0 : "Number must be non-negative";
System.out.println("Number is " + number);
}
}
Exception in thread "main" java.lang.AssertionError: Number must be non-negative
The error message provides context, which is extremely helpful during debugging.
However, avoid using assertions to validate user input or parameters in public methods. These should be handled with proper exception handling instead.
-ea
public class Calculator {
public static int divide(int a, int b) {
assert b != 0 : "Divider cannot be zero";
return a / b;
}
public static void main(String[] args) {
int result = divide(10, 2);
System.out.println("Result: " + result);
// This will cause an AssertionError
divide(10, 0);
}
}
Result: 5
Exception in thread "main" java.lang.AssertionError: Divider cannot be zero
assert
keyword helps you catch bugs during development.-ea
to see assertion effects.assert
Never rely on assertions for input validation, file I/O checks, or network operations. These are part of the contract with external systems or users and should be managed using proper error handling mechanisms.
⬅ Previous Topic
Java abstract KeywordNext Topic ⮕
Java boolean KeywordYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.