Java Programming - Assertions - Discussion

4. 

What will be the output of the program (when you run with the -ea option) ?

public class Test 
{  
    public static void main(String[] args) 
    {
        int x = 0;  
        assert (x > 0) : "assertion failed"; /* Line 6 */
        System.out.println("finished"); 
    } 
}

[A]. finished
[B]. Compilation fails.
[C]. An AssertionError is thrown.
[D]. An AssertionError is thrown and finished is output.

Answer: Option C

Explanation:

An assertion Error is thrown as normal giving the output "assertion failed". The word "finished" is not printed (ensure you run with the -ea option)

Assertion failures are generally labeled in the stack trace with the file and line number from which they were thrown, and also in this case with the error's detail message "assertion failed". The detail message is supplied by the assert statement in line 6.


Venkata said: (Jan 21, 2011)  
"finished" is output

Sundar said: (Feb 19, 2011)  
@All

The given answer is correct only. Don't forget to add -ea option while executing the java code.

I have got the following output:

D:\Java>javac Test.java

D:\Java>java -ea Test
Exception in thread "main" java.lang.AssertionError: assertion failed
at Test.main(Test.java:6)

D:\Java>java Test
finished


I hope the above output will clear your doubts. Have a nice day!

Pragya Sharma said: (Jun 1, 2011)  
Thanks.

Vivek Kumar said: (Jun 22, 2012)  
What is -ea option? & what does -ea do?. mean javac is for compilation & java is for interpretation.

Suyash said: (Oct 9, 2012)  
@Vivek.

If we want to execute assertion line then.

With the interpreter we should use -ea to execute assertion line of code.

Shwets said: (Jul 16, 2013)  
Could you please explain what is the use of assertion, why to use assertion?

Kds said: (Sep 2, 2013)  
I was running it from eclipse and got finished as answer.

Manpreet said: (Jun 23, 2014)  
I don't understand the use of assertion in java.

Dahaf said: (Aug 4, 2015)  
Assertions help a programmer to declare his assumptions.

Tarang Malvaniya said: (Dec 29, 2016)  
Output is A) finished.

Harsh said: (Feb 20, 2017)  
How to enable ea option in Net bean?

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.