Java Programming - Assertions - Discussion

Discussion Forum : Assertions - Pointing out the errors (Q.No. 1)
1.
public class Test2 
{
    public static int x;
    public static int foo(int y) 
    {
        return y * 2;
    }
    public static void main(String [] args) 
    {
        int z = 5;
        assert z > 0; /* Line 11 */
        assert z > 2: foo(z); /* Line 12 */
        if ( z < 7 )
            assert z > 4; /* Line 14 */

        switch (z) 
        {
            case 4: System.out.println("4 ");
            case 5: System.out.println("5 ");
            default: assert z < 10;
        }

        if ( z < 10 )
            assert z > 4: z++; /* Line 22 */
        System.out.println(z);
    }
}
which line is an example of an inappropriate use of assertions?
Line 11
Line 12
Line 14
Line 22
Answer: Option
Explanation:

Assert statements should not cause side effects. Line 22 changes the value of z if the assert statement is false.

Option A is fine; a second expression in an assert statement is not required.

Option B is fine because it is perfectly acceptable to call a method with the second expression of an assert statement.

Option C is fine because it is proper to call an assert statement conditionally.

Discussion:
3 comments Page 1 of 1.

VSPIDER said:   5 years ago
Assertion is majorly used to debug any java code. In option D it is changing the value of variable which effects the flow of code i.e. it changes the further working of code. Now in option B the value of z is not changed because of assertion but is changed because of function. And the value of 'z' is same even after the call. Where as in Option D assertion changes the value keep in mind that assertion is for debugging and not for modifying. That is why we use it on private variables whose scope is limited to class and change is detected there itself. We avoid using assertion on public variables.

Nikola said:   10 years ago
Why the answer is 22 and not 12? At line 12 also z is changed?

Starrer said:   1 decade ago
Why the answer is 22 and not 11?

Post your comments here:

Your comments will be displayed after verification.