Java Programming - Assertions - Discussion


What will be the output of the program?

public class Test 
    public static void main(String[] args) 
        int x = 0;  
        assert (x > 0) ? "assertion failed" : "assertion passed" ; 

[A]. finished
[B]. Compiliation fails.
[C]. An AssertionError is thrown and finished is output.
[D]. An AssertionError is thrown with the message "assertion failed."

Answer: Option B


Compilation Fails. You can't use the Assert statement in a similar way to the ternary operator. Don't confuse.

Sri said: (Nov 9, 2010)  
What's the assert statement?

Shrini said: (Aug 23, 2011)  
How the assert statement really works. ?

Amit said: (Feb 24, 2012)  
Please explain the answer.

Vishal said: (Mar 22, 2012)  
assert tests the programmer's assumption during development without writing exception handlers for an exception. Suppose you assumed that a number passed into a method will always be positive. While testing and debugging, you want to validate your assumption. Without the assert keyword, you will write a method like:

private void method(int a) {

if (a >= 0) {
// do something that depends on a not being negative
} else {
// tell the user that a is negative

This is simple exception handling; consider the case of big one. Assertion will come into the picture when you don't want to take the time to write the exception handling code.

Consider the above program with assertion:

private void method(int a) {
assert (a>=0); //throws an assertion error if a is negative.
// do stuff, knowing that a is not negative

In this program, assert (a>0) will pass when 'a' is only positive. Isn't this much cleaner than the previous example? If the value of 'a' is negative, then an AssertionError will be thrown.

Jagdish Prasad Kumawat said: (Sep 22, 2016)  
Yes, it's prefect reason.

Ravali said: (Jan 3, 2017)  
Thanks for explaining it @Vishal.

Rohit said: (Jun 5, 2020)  
Excellent explanation, Thanks @Vishal.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.