What's the output of the following code?
public class Main4 { public static void main(String args[]) { boolean myVal = false; if (myVal=true) for (int i = 0; i < 2; i++) System.out.println(i); else /*from w w w. j a va 2 s . com*/ System.out.println("else"); } }
a else /* w w w .j ava2 s. c om*/ b 0 1 2 c 0 1 d Compilation error
c
First of all, the expression used in the if construct isn't comparing the value of the variable myVal
with the literal value true-it's assigning the literal value true to it.
The assignment operator (=) assigns the literal value.
The comparison operator (==) is used to compare values.
Because the resulting value is a boolean value, the compiler doesn't complain about the assignment in the if construct.
The code is deliberately poorly indented because you may encounter similarly poor indentation in the OCA Java SE 8 Programmer I exam.
The for loop is part of the if construct, which prints 0 and 1.
The else part doesn't execute because the if condition evaluates to true.
The code has no compilation errors.