Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt in || and &&

 
Vaibhav Chauhan
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
//code:

c class TestBoolean {

static boolean a,b,c,d,e,f;
public static void main(String[] args)
{

boolean ans =(a=true)&&(b=true)||(c=true)&&
(d=true)&&(e=true)||(f=true);


System.out.println(" a: "+a+
"\n b: "+b+
"\n c: "+c+
"\n d: "+d+
"\n e: "+e+
"\n f: "+f+
"\n ans: "+ans
);
}

output:
a: true
b: true
c: false
d: false
e: false
f: false
ans: true

but i was expecting

a: true
b: true
c: true
d: true
e: true
f: false
ans: true

as far as i know all && will be evaluated first(from left to right) and then all || will be evaluated (from left to right) but it is not like this as seen by the output.

please clarify me.
 
Srikanth Basa
Ranch Hand
Posts: 241
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please note that the values substitution takes place from Left to right without bothering about operators. The operators come into picture only after the value substitution phase. So initially you should not be bothered about operators when expressions are evaluated.

Now the expression you gave is
( ((a=true) && (b=true)) || ((c=true)&&(d=true)&&(e=true)) || (f=true) )

As I said the substitution takes place from left to right .(Even this is a bit tricky since the operators are short ciruicted)

Step 1
( ((true) && (b=true)) || ((c=true)&&(d=true)&&(e=true)) || (f=true) )

After this step a=true is assigned.
Note that true && something = something. so the first expression must still be evaluated

Step 2
( ((true) && (true)) || ((c=true)&&(d=true)&&(e=true)) || (f=true) )
After this step b=true is assigned.
Now we are left with (true) || something1 || something2. As || is short circuited something1 and something2 need not be evaluated and the expression is always true

So the values are a=true b=true and the rest have default value false.
 
Gowher Naik
Ranch Hand
Posts: 643
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

i have added single commented to your code.Check this comment and try to
understand what is comment is indicating.
 
Vaibhav Chauhan
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
THANKS GOWHER N SRIKANTH....I GOT IT.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic