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 1 of 2.

AKASH said:   1 decade ago
I am confused about it. At 4th Line if expects any value if it's equal to 0 than compilation will go in if condition otherwise else condition.

Jaladi said:   1 decade ago
Using the integer 1 in the while statement, or any other looping or conditional construct for that matter, will result in a compiler error. This is old C Program syntax, not valid Java.

Chandra bhushan said:   1 decade ago
If condition take two value 1 and 0 ant 1=true 0=false.
Now I is int value which contain value 1 so it should be true.

Prashant said:   1 decade ago
Here if (odd) expects value of odd variable.

As declared earlier value of odd is 1 then condition holds true. Odd should be printed. Didn't understand why it is compiler error.

Manoj said:   1 decade ago
Here if (odd) expects value of odd variable.

As declared earlier value of odd is 1 then condition holds true. Odd should be printed. Didn't understand why it is compiler error.

Surajit said:   1 decade ago
In C programming language while(1){} is a infinite loop. But in java while(1){} is a compilation error because in condition it expects either true of false(both keyword). So, the same c program equivalent code in java is while(true){} which represents infinite loop.
(1)

Bharathraj said:   1 decade ago
How it is a compile error?
(1)

Bandana said:   1 decade ago
In line 4. There is no Boolean condition. It just an integer. That's why it is compile error.

Nashath Nasar said:   1 decade ago
Hi guys,

Option A is the correct answer, because there should be a Boolean expression within the brackets followed by "if". Here is an integer number (Odd) within the brackets. That's why it's compile error.
(1)

Anjan Chandra Das said:   1 decade ago
In java the condition parameters are "true" and "false" i.e. in Boolean format.

But in C or C++ the positive integers are taken as true like.

If (500) // is taken as true in C language. So, Don't be confuse the feature of java and C.
(1)


Post your comments here:

Your comments will be displayed after verification.