• 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

Query about Short-Circuit

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Following code is from K&B's book(pg-180):-
class Logical{
public static void main(String[] args){
boolean b = true && false;
System.out.println("boolean b= "+ b);
}
}
Output is: boolean b= false
Output of this code confused me. I think,
b = true,because && takes first operand(true) Or if b is true then it print default value of boolean b= false.
Could somebody explain me.Why it print false?
Thanks
 
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,
The output print false because "&&" means both operators are true and it return true. As op1 is true, evaluates op2, op1 is false, don't evaluate op2.
boolean b = true & false; //return false.
As op1 and op2 are both true, always evaluates op1 and op2.
 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi Parmar
boolean b= false&&true;
boolean b= true &&false;
both has to return the same results right.
make sure u understand the 'AND' operator.
shortcircuit means it will not evaluate the second operand if that is not gonna chage the result.
AND
op1 op2 result
1 0 0
0 1 0
1 1 1
0 0 0
OR
op1 op2 result
1 1 1
1 0 1
0 1 1
0 0 0
Hope u got the point
Thomas
 
reply
    Bookmark Topic Watch Topic
  • New Topic