• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Question from MindQ sun certified java programmer

 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Consider the two statements:

1. boolean passingScore = false && grade == 70;
2. boolean passingScore = false & grade == 70;
The expression

grade == 70

is evaluated:




a) in both 1 and 2
b) in neither 1 nor 2
c) in 1 but not 2
d) in 2 but not 1
e) invalid because false should be FALSE



correct answer is d..

can any one explain?
 
Ranch Hand
Posts: 167
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
&& and || operators are short circuit logical operators. It means in

if A is false, B is not evaluated. (Because there is no chance the result to be true if A is false)
In your example 1. passingScore is assigned to false and being evaluated, because it is false, grade==70 is not evaluated.
(In the second one & operator is not a schort circuit operator, rather bitweise and)

hope this helps
 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
&& - Short Circuit AND
|| - Short Circuit OR

for AND :

false && any boolean (true/false) is always false, so && does not evaluate the 2nd part when first part if false ..

Similarly incase of || , if first part is true, the second part is not evaluated..

Hope this helps
 
Rekha Gaikwad
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks alot..
 
reply
    Bookmark Topic Watch Topic
  • New Topic