Java Programming - Assertions - Discussion

Discussion Forum : Assertions - Finding the output (Q.No. 2)
2.
public class Test 
{ 
    public void foo() 
    {
        assert false; /* Line 5 */
        assert false; /* Line 6 */
    } 
    public void bar()
    {
        while(true)
        {
            assert false; /* Line 12 */
        } 
        assert false;  /* Line 14 */
    } 
}
What causes compilation to fail?
Line 5
Line 6
Line 12
Line 14
Answer: Option
Explanation:

Option D is correct. Compilation fails because of an unreachable statement at line 14. It is a compile-time error if a statement cannot be executed because it is unreachable. The question is now, why is line 20 unreachable? If it is because of the assert then surely line 6 would also be unreachable. The answer must be something other than assert.

Examine the following:

A while statement can complete normally if and only if at least one of the following is true:

- The while statement is reachable and the condition expression is not a constant expression with value true.

-There is a reachable break statement that exits the while statement.

The while statement at line 11 is infinite and there is no break statement therefore line 14 is unreachable. You can test this with the following code:

public class Test80 
{ 
    public void foo() 
    {
        assert false; 
        assert false; 
    } 
    public void bar()
    {
        while(true)
        {
            assert false; 
            break; 
        } 
        assert false;  
    } 
}

Discussion:
12 comments Page 2 of 2.

T V MADHU SUDHANA REDDY said:   1 decade ago
If we declare boolean assert=true/false in starting and if we are trying to compile from 1.5 version onwards then we will get compile time error.

Complietime error:assert is an keyword from 1.5 version so dont use assert as an identifier.

Das said:   1 decade ago
Now if we declare boolean assert in starting, where will be the error. ? In which line. ?


Post your comments here:

Your comments will be displayed after verification.