This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Bitwise Operators

 
sudha siva
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hai everyone,
class Test{
public static void main(String args[]){
int x=0;
boolean b1,b2,b3,b4;
b1=b2=b3=b4=true;
x=(b1 | b2 & b3 ^b4) ? x++ : --x; // line 1
System.out.println(x);
}
}

The output of the above code is 0.And in the answer the line 1 is evaluated as (b1 | (b2 & (b3 ^ b4)).But the AND operator should be evaluated first in this type of expression.(I think i,m correct).I'm confused of this code.Can anyone clear my doubt.

Thanks
sudha
 
Simeon Shi
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,sudha...
u r right about the operators' priority--&->^->|,
then the result of (b1 | b2 & b3 ^b4) is true.
okay, the next step is x = x++; yes,it is where u confused.
such code as x=x--;x=x++; won't change the the value of x.
so x still is 0;
the output should be 0
 
Philip Hung
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Operator Precedence would be & then ^ then |. So b2 & b3 gets evaluated first (results to true), then ^ b4 (results to false) lastly | b1 (results to true). Evaluate x++ which returns 0.
 
vishal avad
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi sudha siva
i dont think it has any relation with bitwise operator.it is has problem with increment operator
for ref.
see post increment operator posted by ravish kumar
i m also waiting 4 its answer. its really complicated.
rgds
vishal
 
R K Singh
Ranch Hand
Posts: 5384
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sudha
operators' priority is & -> ^ -> |
it is evaluated as (b1 | ((b2 & b3) ^b4))
so
b2 & b3 = true
true ^ b4 = false
b1 | false = true
hence x = x++;
but now I am confused ??

------------------
Regards
Ravish
 
Uma Viswanathan
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
x=(b1 | b2 & b3 ^b4) ? x++ : --x;
First let us evaluate
true | ( (true & true ) ^ true )
i.e., true | (true ^ true )
i.e., true | false
i.e., true
Now, the expression is equivalent to
x = x++;
The steps are
1) Return the value of x
2) Increment the value of x
3) Assign the value returned by step 1 to L.H.S variable
So,
The value 0 is assigned to the variable x
Hope this helps...
Uma
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic