- 1Java Exceptions
- 2Java Keywords
- 3Java abstract Keyword
- 4Java assert Keyword
- 5Java boolean Keyword
- 6Java break Keyword
- 7Java byte Keyword
- 8Java case Keyword
- 9Java catch Keyword
- 10Java char Keyword
- 11Java class Keyword
- 12Java const Keyword
- 13Java continue Keyword
- 14Java default Keyword
- 15Java do Keyword
- 16Java double Keyword
- 17Java else Keyword
- 18Java enum Keyword
- 19Java extends Keyword
- 20Java final Keyword
- 21Java finally Keyword
- 22Java float Keyword
- 23Java for Keyword
- 24Java goto Keyword
- 25Java if Keyword
- 26Java implements Keyword
- 27Java import Keyword
- 28Java instanceof Keyword
- 29Java int Keyword
- 30Java interface Keyword
- 31Java long Keyword
- 32Java native Keyword
- 33Java new Keyword
- 34Java null Keyword
- 35Java package Keyword
- 36Java private Keyword
- 37Java protected Keyword
- 38Java public Keyword
- 39Java return Keyword
- 40Java short Keyword
- 41Java static Keyword
- 42Java strictfp Keyword
- 43Java super Keyword
- 44Java switch Keyword
- 45Java synchronized Keyword
- 46Java this Keyword
- 47Java transient Keyword
- 48Java try Keyword
- 49Java void Keyword
- 50Java volatile Keyword
- 51Java while Keyword
- 52Java String Methods - Syntax and Description
- 53Java String
charAt()
method - 54Java String
codePointAt()
method - 55Java String
codePointBefore()
method - 56Java String
codePointCount()
method - 57Java String
compareTo()
method - 58Java String
compareToIgnoreCase()
method - 59Java String
concat()
method - 60Java String
contains()
method - 61Java String
contentEquals()
method - 62Java String
copyValueOf()
method - 63Java String
endsWith()
method - 64Java String
equals()
method - 65Java String
equalsIgnoreCase()
method - 66Java String
format()
method - 67Java String
getBytes()
method - 68Java String
getChars()
method - 69Java String
hashCode()
method - 70Java String
indexOf()
method - 71Java String
intern()
method - 72Java String
isEmpty()
method - 73Java String
join()
method - 74Java String
lastIndexOf()
method - 75Java String
length()
method - 76Java String
matches()
method - 77Java String
offsetByCodePoints()
method - 78Java String
regionMatches()
method - 79Java String
replace()
method - 80Java String
replaceAll()
method - 81Java String
replaceFirst()
method - 82Java String
split()
method - 83Java String
startsWith()
method - 84Java String
subSequence()
method - 85Java String
substring()
method - 86Java String
toCharArray()
method - 87Java String
toLowerCase()
method - 88Java String
toString()
method - 89Java String
toUpperCase()
method - 90Java String
trim()
method - 91Java String
valueOf()
method - 92Java ArrayList Methods - Complete Reference with Syntax and Description
- 93Java LinkedList Methods - Complete Reference with Syntax and Description
- 94Java HashMap Methods - Syntax and Descriptions
Java assert Keyword
Usage and Examples
assert
Keyword in Java
The 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.
What Is the Purpose of Using 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.
Basic Syntax of assert
assert condition;
Or with a custom error message:
assert condition : "Error Message";
How to Enable Assertions in Java
By default, assertions are disabled in the JVM. You must explicitly enable them using the -ea
flag while running the program:
java -ea YourClassName
Simple Example Without Error Message
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.
Example With Assertion Failure
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.
Using Assertions With Custom Error Messages
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.
Where Should You Use Assertions?
- Validating internal logic during development
- Ensuring preconditions/postconditions in methods
- Verifying state transitions in algorithms
However, avoid using assertions to validate user input or parameters in public methods. These should be handled with proper exception handling instead.
Common Pitfalls and Misuse
- Forgetting to enable assertions at runtime using
-ea
- Using assertions for production-critical checks
- Using assertions to change program state (e.g., modifying variables inside assertions)
Practical Use Case Example
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
Summary
- The
assert
keyword helps you catch bugs during development. - Assertions should not replace proper validation in production code.
- Always run your Java program with
-ea
to see assertion effects. - Use custom messages to make debugging easier.
When Not to Use 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.