Monday, September 10, 2007

boolean vs int in Java

Some of us might think C and Java might behave the same manner...
for example, the code below:

int x = 3;
if(x=4) {
System.out.println("X is assigned value 4");
}

if(x) {
System.out.println("Value of X is 4");
}

What is the output of the above programs in Java?
Ans: Compilation fails.
Reason: The 'if()' Condition in java expects a boolean argument. when we assign x=4, it returns an integer which is the value of 'x' i.e., 4.

0 comments: