Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

assertion
java

What are assertions in Java?

Educative Answers Team

An assertion is defined as a claim or assumption. In programming, there are cases when we, as programmers, know that a certain variable takes a specific value(s) at a particular line of code. We usually represent such a claim using comments in our code.

An assertion in Java is one single line of code which checks a certain boolean expression and throws a AssertionError if that expression is false. We say that an assertion has failed in this case.

Note: Assertions are disabled by default in Java. Include -ea command in your Java interpreter (or search specifically for your IDE on the web).

svg viewer
Program flow with an assert statement

Syntax

There are two ways to write an assertion using the assert keyword.

  1. assert expression;

We can pass our own message as any type of variable (other than void) which will be shown in the stack trace in case the expression was false.

  1. assert expression : "Invalid value";

When to use assertions?

  1. Using an assertion instead of a comment we put for our own convenience:
int x = 3;

if(x <= 2) {
	// ...
}
else {  // x > 2
	// ...
}
  1. Checking control-flow. If we know that our code is not meant to reach a certain line, we can place the assertion in that prohibited area;but, it should be written in such a way that it always returns false:
int i = 5;
while(i > 0){
  if(i == 2){ // Can be any condition which you think will be surely met.
    return;
  }

  i--;
}
  // My program should not reach this place.

RELATED TAGS

assertion
java
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring