Java Programming - Assertions - Discussion

Discussion Forum : Assertions - Finding the output (Q.No. 3)
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 ");
bar done
foo done
Compilation fails
Answer: Option

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.

10 comments Page 1 of 1.

Adam Prog said:   6 years ago
After ":" can be any expression which has a value.

Ron said:   7 years ago
The formula after ":" should have no type, even void, it is supposed to be an expression like a sentence.

Vishesh said:   9 years ago
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.

Vishesh said:   9 years ago
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.

Tom Nguyen said:   9 years ago

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

Jagadeesh Urella said:   9 years ago
Can any one tell me what is assert? why we use it in java.

Vinay said:   10 years ago
If we comment the line 18 the output is strange? any explanation?

Dhirendra Kumar said:   1 decade ago
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.

Aditya valluru said:   1 decade ago
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 ?

Manuja George said:   1 decade ago
Assert can call method with which return type?

Post your comments here:

Your comments will be displayed after verification.