• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

~operator

 
jyothi godavarthy
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
please someone explain me how to do this inversion. The output is -9. thanks
class test {
public static void main(String args[]) {
byte x = 8;
x = (byte)~x;
System.out.println(x);
}
}
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's the way the Bitwise complement operator ~ works.
Read what JLS Section 15.15.5 Bitwise Complement Operator ~ says-

The type of the operand expression of the unary ~ operator must be a primitive integral type, or a compile-time error occurs. Unary numeric promotion (�5.6.1) is performed on the operand. The type of the unary bitwise complement expression is the promoted type of the operand.
At run time, the value of the unary bitwise complement expression is the bitwise complement of the promoted value of the operand; note that, in all cases, ~x equals (-x)-1.

Hence ~(8) = -8 - 1 = -9.
You can safely use this rule in the exam.

Ajith
 
jyothi godavarthy
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
got it Ajit. thanks a lot
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic