• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

what's the output

 
Samrat Pujara
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class ShortCkt {
public static void main(String args[]) {
int i = 0;
boolean t = true;
boolean f = false, b;
b = (t | | ((i++) == 0));
b = (f | | ((i+=2) > 0));
System.out.println(i);
}
}

a] 0
b] 1
c] 2
d] 3

Answer is probably c) but i feel it should have been d)
Any suggestions ?

 
Sam Wong
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Answer is c. Here's why.
| | is a short circuited operation meaning that it will only do as much work as necessary to determine the answer.
Hence, in the line of code: b = (t| |((i++) == 0)), t is true and thus determine the output of the | | operator regardless of the output of ((i++) == 0). In such a case, the second operand being ((i++) == 0) will not be executed and thus i will not be incremented.
The answer would have been d if the operands were reversed like b = (((i++) == 0) | | t);
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic