What does the Java assert keyword do, and when should it be used?

how to enable assertion in java
java assert not working
assert in java selenium
java assert best practices
java assert library
java assert keyword usefulness
assertion in java in hindi
assertion in java interview questions

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

Assertions (by way of the assert keyword) were added in Java 1.4. They are used to verify the correctness of an invariant in the code. They should never be triggered in production code, and are indicative of a bug or misuse of a code path. They can be activated at run-time by way of the -ea option on the java command, but are not turned 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;
}

When to use an assertion and when to use an exception, nothing. If the conditional expression evaluates to false, an error message is displayed and the program is terminated. Java assert keyword is used to create assertions in Java, which enables us to test the assumptions about our program. For example, an assertion may be to make sure that an employee’s age is positive number.

Let's assume that you are supposed to write a program to control a nuclear power-plant. It is pretty obvious that even the most minor mistake could have catastrophic results, therefore your code has to be bug-free (assuming that the JVM is bug-free for the sake of the argument).

Java is not a verifiable language, which means: you cannot calculate that the result of your operation will be perfect. The main reason for this are pointers: they can point anywhere or nowhere, therefore they cannot be calculated to be of this exact value, at least not within a reasonable span of code. Given this problem, there is no way to prove that your code is correct at a whole. But what you can do is to prove that you at least find every bug when it happens.

This idea is based on the Design-by-Contract (DbC) paradigm: you first define (with mathematical precision) what your method is supposed to do, and then verify this by testing it during actual execution. Example:

// Calculates the sum of a (int) + b (int) and returns the result (int).
int sum(int a, int b) {
  return a + b;
}

While this is pretty obvious to work fine, most programmers will not see the hidden bug inside this one (hint: the Ariane V crashed because of a similar bug). Now DbC defines that you must always check the input and output of a function to verify that it worked correctly. Java can do this through assertions:

// Calculates the sum of a (int) + b (int) and returns the result (int).
int sum(int a, int b) {
    assert (Integer.MAX_VALUE - a >= b) : "Value of " + a + " + " + b + " is too large to add.";
  final int result = a + b;
    assert (result - a == b) : "Sum of " + a + " + " + b + " returned wrong sum " + result;
  return result;
}

Should this function now ever fail, you will notice it. You will know that there is a problem in your code, you know where it is and you know what caused it (similar to Exceptions). And what is even more important: you stop executing right when it happens to prevent any further code to work with wrong values and potentially cause damage to whatever it controls.

Java Exceptions are a similar concept, but they fail to verify everything. If you want even more checks (at the cost of execution speed) you need to use assertions. Doing so will bloat your code, but you can in the end deliver a product at a surprisingly short development time (the earlier you fix a bug, the lower the cost). And in addition: if there is any bug inside your code, you will detect it. There is no way of a bug slipping-through and cause issues later.

This still is not a guarantee for bug-free code, but it is much closer to that, than usual programs.

What Are Assertions, It is mainly used for testing purposes during development. The assert statement is used with a Boolean expression and can be written in two different ways. to a derived class method in Java · Comparison of static keyword in C++ and Java. What does the Java assert keyword do, and when should it be used? The role of asserts is to stop the program if an input or value is not within a desired range. Some other examples would be making sure a users input is within bounds or does not contain any undesired characters.

Assertions are a development-phase tool to catch bugs in your code. They're designed to be easily removed, so they won't exist in production code. So assertions are not part of the "solution" that you deliver to the customer. They're internal checks to make sure that the assumptions you're making are correct. The most common example is to test for null. Many methods are written like this:

void doSomething(Widget widget) {
  if (widget != null) {
    widget.someMethod(); // ...
    ... // do more stuff with this widget
  }
}

Very often in a method like this, the widget should simply never be null. So if it's null, there's a bug in your code somewhere that you need to track down. But the code above will never tell you this. So in a well-intentioned effort to write "safe" code, you're also hiding a bug. It's much better to write code like this:

/**
 * @param Widget widget Should never be null
 */
void doSomething(Widget widget) {
  assert widget != null;
  widget.someMethod(); // ...
    ... // do more stuff with this widget
}

This way, you will be sure to catch this bug early. (It's also useful to specify in the contract that this parameter should never be null.) Be sure to turn assertions on when you test your code during development. (And persuading your colleagues to do this, too is often difficult, which I find very annoying.)

Now, some of your colleagues will object to this code, arguing that you should still put in the null check to prevent an exception in production. In that case, the assertion is still useful. You can write it like this:

void doSomething(Widget widget) {
  assert widget != null;
  if (widget != null) {
    widget.someMethod(); // ...
    ... // do more stuff with this widget
  }
}

This way, your colleagues will be happy that the null check is there for production code, but during development, you're no longer hiding the bug when widget is null.

Here's a real-world example: I once wrote a method that compared two arbitrary values for equality, where either value could be null:

/**
 * Compare two values using equals(), after checking for null.
 * @param thisValue (may be null)
 * @param otherValue (may be null)
 * @return True if they are both null or if equals() returns true
 */
public static boolean compare(final Object thisValue, final Object otherValue) {
  boolean result;
  if (thisValue == null) {
    result = otherValue == null;
  } else {
    result = thisValue.equals(otherValue);
  }
  return result;
}

This code delegates the work of the equals() method in the case where thisValue is not null. But it assumes the equals() method correctly fulfills the contract of equals() by properly handling a null parameter.

A colleague objected to my code, telling me that many of our classes have buggy equals() methods that don't test for null, so I should put that check into this method. It's debatable if this is wise, or if we should force the error, so we can spot it and fix it, but I deferred to my colleague and put in a null check, which I've marked with a comment:

public static boolean compare(final Object thisValue, final Object otherValue) {
  boolean result;
  if (thisValue == null) {
    result = otherValue == null;
  } else {
    result = otherValue != null && thisValue.equals(otherValue); // questionable null check
  }
  return result;
}

The additional check here, other != null, is only necessary if the equals() method fails to check for null as required by its contract.

Rather than engage in a fruitless debate with my colleague about the wisdom of letting the buggy code stay in our code base, I simply put two assertions in the code. These assertions will let me know, during the development phase, if one of our classes fails to implement equals() properly, so I can fix it:

public static boolean compare(final Object thisValue, final Object otherValue) {
  boolean result;
  if (thisValue == null) {
    result = otherValue == null;
    assert otherValue == null || otherValue.equals(null) == false;
  } else {
    result = otherValue != null && thisValue.equals(otherValue);
    assert thisValue.equals(null) == false;
  }
  return result;
}

The important points to keep in mind are these:

  1. Assertions are development-phase tools only.

  2. The point of an assertion is to let you know if there's a bug, not just in your code, but in your code base. (The assertions here will actually flag bugs in other classes.)

  3. Even if my colleague was confident that our classes were properly written, the assertions here would still be useful. New classes will be added that might fail to test for null, and this method can flag those bugs for us.

  4. In development, you should always turn assertions on, even if the code you've written doesn't use assertions. My IDE is set to always do this by default for any new executable.

  5. The assertions don't change the behavior of the code in production, so my colleague is happy that the null check is there, and that this method will execute properly even if the equals() method is buggy. I'm happy because I will catch any buggy equals() method in development.

Also, you should test your assertion policy by putting in a temporary assertion that will fail, so you can be certain that you are notified, either through the log file or a stack trace in the output stream.

7.12a, Learn how to work with assertions in Java using the assert keyword. They must be explicitly enabled using either the -enableassertions command a second syntax for assertions that takes a string, which will be used to  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.

A lot of good answers explaining what the assert keyword does, but few answering the real question, "when should the assert keyword be used in real life?"

The answer: almost never.

Assertions, as a concept, are wonderful. Good code has lots of if (...) throw ... statements (and their relatives like Objects.requireNonNull and Math.addExact). However, certain design decisions have greatly limited the utility of the assert keyword itself.

The driving idea behind the assert keyword is premature optimization, and the main feature is being able to easily turn off all checks. In fact, the assert checks are turned off by default.

However, it is critically important that invariant checks continue to be done in production. This is because perfect test coverage is impossible, and all production code will have bugs which assertions should help to diagnose and mitigate.

Therefore, the use of if (...) throw ... should be preferred, just as it is required for checking parameter values of public methods and for throwing IllegalArgumentException.

Occasionally, one might be tempted to write an invariant check that does take an undesirably long time to process (and is called often enough for it to matter). However, such checks will slow down testing which is also undesirable. Such time-consuming checks are usually written as unit tests. Nevertheless, it may sometimes make sense to use assert for this reason.

Do not use assert simply because it is cleaner and prettier than if (...) throw ... (and I say that with great pain, because I like clean and pretty). If you just cannot help yourself, and can control how your application is launched, then feel free to use assert but always enable assertions in production. Admittedly, this is what I tend to do. I am pushing for a lombok annotation that will cause assert to act more like if (...) throw .... Vote for it here.

(Rant: the JVM devs were a bunch of awful, prematurely optimizing coders. That is why you hear about so many security issues in the Java plugin and JVM. They refused to include basic checks and assertions in production code, and we are continuing to pay the price.)

Java code examples to use assert keyword. The assert keyword is used in assertion statement which is a feature of the Java Where: expression1 must be a booleanexpression. expression2 must return a value (must not return void). If assertion is enabled, then the assert statement will be evaluated. Java Programming/Keywords/assert assert is a Java keyword used to define an assert statement. An assert statement is used to declare an expected boolean condition in a program. If the program is running with assertions enabled, then the condition is checked at runtime.

Here's the most common use case. Suppose you're switching on an enum value:

switch (fruit) {
  case apple:
    // do something
    break;
  case pear:
    // do something
    break;
  case banana:
    // do something
    break;
}

As long as you handle every case, you're fine. But someday, somebody will add fig to your enum and forget to add it to your switch statement. This produces a bug that may get tricky to catch, because the effects won't be felt until after you've left the switch statement. But if you write your switch like this, you can catch it immediately:

switch (fruit) {
  case apple:
    // do something
    break;
  case pear:
    // do something
    break;
  case banana:
    // do something
    break;
  default:
    assert false : "Missing enum value: " + fruit;
}

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  Assertions (by way of the assert keyword) were added in Java 1.4. They are used to verify the correctness of an invariant in the code. They are used to verify the correctness of an invariant in the code.

This definition explains the Java assert keyword, which is part of a newly introduced The boolean condition of a Java assert statement can be as complicated as a Assertions should be used to test for situations, conditions and application  The benefit of using the Java assert statement is it can help identify when problems occur and provide a stack trace indicating the sequence of events and method calls that led to the fatal condition occurring.

expression2 is an expression that has a value and this value will be compared with expression1. The second form of the assertion statement should be used in  The assert keyword is used in assertion statement which is a feature of the Java programming language since Java 1.4. Assertion enables developers to test assumptions in their programs as a way to defect and fix bugs.

But did you know that Java has a built-in assert mechanism? However, they can be used anywhere in the code (with a few restrictions due to some good practices) and with Assertions use the reserved assert keyword. AssertionError: Amount should be between 0 and 1,000: -11.0 at com.example. assert is a keyword added in Java version 1.4. assert tests the programmer's assumption during development without writing exception handlers for an exception.

Comments
  • In real life you almost never see them. Conjecture: If you use assertions you have to think about three states: Assert passes, assert fails, assert is turned off, instead of just two. And assert is turned off by default so that is the most likely state, and it is hard to ensure that it is enabled for your code. What that adds up to is that asserts are a premature optimization that would be of limited use. As you see in @Bjorn's answer, it is even hard to come up with a use case where you would not want to fail an assert all the time.
  • @Yishai: "you have to think about ... assert is turned off" If you need to do that, you are doing it wrong. "asserts are a premature optimization of limited use" This is pretty much off the rails. Here is Sun's take on this: "Using Assertions in Java Technology" and this is also good to read: "The benefits of programming with assertions (a.k.a. assert statements)"
  • @DavidTonhofer, in real life you almost never see them. This is verifiable. Check as many open source projects as you like. I'm not saying you don't validate invariants. That isn't the same thing. Put another way. If asserts are so important, why are they off by default?
  • A reference, FWIW: The relationship between software assertions and code quality: "We also compare the efficacy of assertions against that of popular bug finding techniques like source code static analysis tools. We observe from our case study that with an increase in the assertion density in a file there is a statistically significant decrease in fault density."
  • @DavidTonhofer David, i think your love for assertion is for a very specific type of programming that you guys are doing, in my field which works with web applications exiting out of the program for ANY reason is the biggest NO NO - i have personally never used assert other than unit/integ testing
  • In fact, Oracle tells you not to use assert to check public method parameters (docs.oracle.com/javase/1.4.2/docs/guide/lang/assert.html). That should throw an Exception instead of killing the program.
  • But you still don't explain why they exist. Why can't you do an if() check and throw an exception?
  • @ElMac - assertions are for the dev/debug/test parts of the cycle - they are not for production. An if block runs in prod. Simple assertions won't break the bank, but expensive assertions that do complex data validation might bring down your production environment, which is why they are turned off there.
  • @hoodaticus you mean solely the fact that I can turn on/off all assertions for prod code is the reason? Because I can do complex data validation anyways and then handle it with exceptions. If I have production code, I could turn off the complex (and maybe expensive) assertions, because it should work and was tested already? In theory they shouldnt bring down the program because then you would have a problem anyways.
  • This convention is unaffected by the addition of the assert construct. Do not use assertions to check the parameters of a public method. An assert is inappropriate because the method guarantees that it will always enforce the argument checks. It must check its arguments whether or not assertions are enabled. Further, the assert construct does not throw an exception of the specified type. It can throw only an AssertionError. docs.oracle.com/javase/8/docs/technotes/guides/language/…
  • I chose this example because it presents hidden bugs in seemingly bug-free code very well . If this is similar to what someone else presented, then they maybe had the same idea in mind. ;)
  • You choose assert because it fails when the assertion is false. An if can have any behaviour. Hitting fringe cases is the job of Unit Testing. Using Design by Contract specified the contract rather well but as with real life contracts, you need a control to be sure they are respected. With assertions a watchdog is inserted that will then you when the contract is disrespected. Think of it as a nagging lawyer screaming "WRONG" every time you do something that is outside or against a contract you signed and then send you home so you can't continue to work and breach the contract further!