Consider the following snippet of code:
int i = 10; int j = 10; boolean b = (i > 5 && ((j = 20) > 15)); System.out.println("b = " + b); System.out.println("i = " + i); System.out.println("j = " + j);
What is the output?
b = true i = 10 j = 20
public class Main { public static void main(String[] args) { int i = 10; // ww w . j ava 2 s . c om int j = 10; boolean b = (i > 5 && ((j = 20) > 15)); System.out.println("b = " + b); System.out.println("i = " + i); System.out.println("j = " + j); } }
i > 5, evaluated to true, the right-hand of operand ((j = 20) > 15) was evaluated and the variable j was assigned a value 20.
What is the result of the following code?
int i = 10; int j = 10; boolean b = (i > 25 && ((j = 20) > 15)); System.out.println ("b = " + b); System.out.println ("i = " + i); System.out.println ("j = " + j); // Will print j = 10
b = false i = 10 j = 10
public class Main { public static void main(String[] args) { int i = 10; //ww w. j a v a 2 s .co m int j = 10; boolean b = (i > 25 && ((j = 20) > 15)); System.out.println ("b = " + b); System.out.println ("i = " + i); System.out.println ("j = " + j); // Will print j = 10 } }
If the left-hand operand evaluates to false, the right-hand operand would not be evaluated.
The value of j will remain 10.
((j = 20) > 5) is not evaluated because i > 25 returns false