• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

regarding negation operation

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 411
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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...
 
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.

 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic