posted 15 years ago
1.1.public static ShortCkt {
2.public static void main(String args[]) {
3.int i = 0;
4.boolean t = true;
5.boolean f = false, b;
6.b = (t && ((i++) == 0));
7.b = (f && ((i+=2) > 0));
8.System.out.println(i);
}
}
answer is 1.
2.1.public static ShortCkt {
2.public static void main(String args[]) {
3.int i = 0;
4.boolean t = true;
5.boolean f = false, b;
6.b = (t & ((i++) == 0));
7.b = (f & ((i+=2) > 0));
8.System.out.println(i);
}
}
Code 1 uses short circuit operator "&&". This evaluates the second part of the expression only if the first part is true. If the first part is false, the second part of the expression is ignored.
In line 6, in the first part, t is true. Hence, the second part is evaluated and i is incremented to 1.In line 7, first part, f is false so, the second half of the expression is ignored. Hence, i = 1.
Code 2 uses logical "&" operator. Hence both expressions are evaluated and i = 3.
Hope you are clear with the answer.