aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes regarding negation operation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "regarding negation operation" Watch "regarding negation operation" New topic
Author

regarding negation operation

betzi kuriakose
Greenhorn

Joined: Jun 26, 2005
Posts: 12
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

Joined: Aug 27, 2004
Posts: 411
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...


Cheers,<br />Jay<br /> <br />(SCJP 1.4)<br />Heights of great men were not achieved in one day, they were toiling day and night while their companions slept.
Joe Sondow
Ranch Hand

Joined: Apr 10, 2005
Posts: 195
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.



SCJA 1.0 (98%), SCJP 1.4 (98%)
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: regarding negation operation