What's the output of the following code?
public class Main { public static void main(String args[]) { boolean myVal = false; if (myVal = true) for (int i = 0; i < 2; i++) System.out.println(i); else System.out.println("else"); } } a else b 0 1 2 c 0 1 d Compilation error
C
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.
Because the resulting value is a boolean value, the compiler doesn't complain about the assignment in the if construct.
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.
public class Main { public static void main(String args[]) { boolean myVal = false; if (myVal = true) for (int i = 0; i < 2; i++) System.out.println(i);/*from w w w.j a v a2 s. com*/ else System.out.println("else"); } }
The code above generates the following result.