Machine-translated by Google. Questions are authored in English.
Top

Discussion

public void test(int x) 
{ 
    int odd = 1; 
    if(odd) /* Line 4 */
    {
        System.out.println("odd"); 
    } 
    else 
    {
        System.out.println("even"); 
    } 
}

Which statement is true?

  • A.Compilation fails.
  • B."odd" will always be output.
  • C."even" will always be output.
  • D."odd" will be output for odd values of x, and "even" for even values.

Answer: A

Correct answer: Compilation fails.

Java requires the condition of an if to be a boolean, and odd is an int. There is no implicit conversion from a number to a boolean, so the C idiom of testing an integer for non-zero does not compile - it must be written if (odd != 0). The parameter x is never used at all, which is a hint that the fragment was never going to behave as its option about odd and even values suggests.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.