Java Programming - Flow Control - Discussion

Discussion Forum : Flow Control - General Questions (Q.No. 3)
3.
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?
Compilation fails.
"odd" will always be output.
"even" will always be output.
"odd" will be output for odd values of x, and "even" for even values.
Answer: Option
Explanation:

The compiler will complain because of incompatible types (line 4), the if expects a boolean but it gets an integer.

Discussion:
15 comments Page 2 of 2.

Shantanu said:   1 decade ago
What when we use while (1)?

That time it gives exact output in c++. It is not allowed in java.

Shrek said:   9 years ago
As far as I have learned, any number other than 0 in the if condition results in a true result. 0 returns false and hence in this case if should actually return true and print ODD.

Although, I am not sure if this is invalid incase of java.
(1)

Surendra said:   9 years ago
With in if condition boolean expression is given.
(1)

Sajib said:   8 years ago
How it becomes compilation error? 0 if false otherwise true.
(2)

Vikash rai said:   6 years ago
Integer can not behave like boolean. And there is not a complete condition statement in if condition.

So it will throw compilation error.

Thanks.


Post your comments here:

Your comments will be displayed after verification.