Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

kindly explain the code.

 
ramanuja varun
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Test
{
public static void main(String args[])
{
int x = 11;

x &= 2; //1

System.out.println(x << 2 + x); //2
}
}
please explain why this code will print 32 instead of 10(x<<2 will give 8)
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please put all your code in CODE tags; it makes it much easier to read.

It is impossible for anything & 2 to equal 1; in fact 11 & 2 gives 2. The + operator has a higher priority than the bit shift operators, so you are shifting by 4, not by 2.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic