Java Programming - Assertions - Discussion


What will be the output of the program?

public class Test 
    public static int y;
    public static void foo(int x) 
        System.out.print("foo ");
        y = x;
    public static int bar(int z) 
        System.out.print("bar ");
        return y = z;
    public static void main(String [] args ) 
        int t = 0;
        assert t > 0 : bar(7);
        assert t > 1 : foo(8); /* Line 18 */
        System.out.println("done ");

[A]. bar
[B]. bar done
[C]. foo done
[D]. Compilation fails

Answer: Option D


The foo() method returns void. It is a perfectly acceptable method, but because it returns void it cannot be used in an assert statement, so line 18 will not compile.

Manuja George said: (Oct 13, 2011)  
Assert can call method with which return type?

Aditya Valluru said: (Mar 2, 2012)  
Here why assert will't return assert error when t>0 is false.

Assert expects only true boolean value but it gets false. Am I correct ?

Dhirendra Kumar said: (Aug 26, 2012)  
The error is at line:
assert t > 1 : foo(8); /* Line 18 *
beacause foo()'s return type is void assert can not have void as return type.

Vinay said: (Nov 21, 2013)  
If we comment the line 18 the output is strange? any explanation?

Jagadeesh Urella said: (Dec 12, 2013)  
Can any one tell me what is assert? why we use it in java.

Tom Nguyen said: (Dec 30, 2013)  

Assert is used for troubleshooting, we want to make sure that the variables should be got right values at the specific locations.

Vishesh said: (Sep 24, 2014)  
Why colon (:) used here explain it. And if at place of : semicolon (;) used then output is bar foo done?

And both assert false after this no error thrown why? even when I made return type of method foo is int.

Vishesh said: (Sep 24, 2014)  
If you execute this program in IDE then it does not throw any exception. So compile it on cmd and for execution type

----> java -ea ClassName

Here ea used for to enable assertion.

Ron said: (Sep 1, 2016)  
The formula after ":" should have no type, even void, it is supposed to be an expression like a sentence.

Adam Prog said: (Nov 13, 2017)  
After ":" can be any expression which has a value.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.