Win a copy of Spring Boot in Practice this week in the Spring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

what's the output

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ?

 
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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);
reply
    Bookmark Topic Watch Topic
  • New Topic