Java Programming - Assertions - Discussion

Discussion Forum : Assertions - Finding the output (Q.No. 1)
1.
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" ; 
        System.out.println("finished");  
    } 
}
finished
Compiliation fails.
An AssertionError is thrown and finished is output.
An AssertionError is thrown with the message "assertion failed."
Answer: Option
Explanation:

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

Discussion:
8 comments Page 1 of 1.

Sri said:   1 decade ago
What's the assert statement?

Shrini said:   1 decade ago
How the assert statement really works. ?

Amit said:   1 decade ago
Please explain the answer.

Vishal said:   1 decade ago
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.
(1)

Jagdish Prasad Kumawat said:   8 years ago
Yes, it's prefect reason.

Ravali said:   8 years ago
Thanks for explaining it @Vishal.

Rohit said:   4 years ago
Excellent explanation, Thanks @Vishal.

Suman said:   2 years ago
Excellent explanation, Thanks @Vishal.

Post your comments here:

Your comments will be displayed after verification.