Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.4k points)

What are some real-life examples to understand the key role of assertions?

1 Answer

0 votes
by (46k points)

Assertions were added in Java 1.4. They are used to verify the accuracy of an invariant in the code. They shouldn't be triggered in production code, and are indicative of a bug or misuse of a code path. They can be initiated at run-time by way of the -ea option on the java command, but are not set on by default.

An example:

public Foo acquireFoo(int id) {

  Foo result = null;

  if (id > 50) {

    result = fooService.read(id);

  } else {

    result = new Foo(id);

  }

  assert result != null;

  return result;

}

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jul 16, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...