File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Soft Skills: The software developer's life manual this week in the Jobs Discussion forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

regarding negation operation

 
betzi kuriakose
Greenhorn
Posts: 12
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class check
{
public static void main(String h[])
{
byte x =3;
x=(byte)~x;
System.out.println(x);



}
}

The following code produces -4 .
I thought the answer was 0 as the result flows out of the range for byte primitive type.
Could anybody advise on this?

regards & thanks
betzi
 
Jay Pawar
Ranch Hand
Posts: 411
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The easiest way to calculate the result of negation operator :

Consider the code below;


The result can be calculated using the formula y = (x+1) * (-1);
in this case it would y = (6+1) * (-1) which is -7.

Hope that helps...
 
Joe Sondow
Ranch Hand
Posts: 195
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And to understand why Jay's formula works, you can write out the bits.


Again, the formula is
~x = (x+1) * (-1)
or
~x = -(x+1)

You can see the formula in action from this chart of values. Remember that 11111111 is -1.

 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic