File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes negation operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Storm Applied this week in the Other Open Source APIs forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "negation operator" Watch "negation operator" New topic

negation operator

tue march

Joined: Mar 09, 2005
Posts: 16
Hi guys,

public class Flip{
public static void main(String argv[]){

can anybody explain why the output of this program is -5.

Thanks in advance
Good guy
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
~ is not negation; it's called two's complement. You flip all the bits, sobecomesCan you see how it can be used for negation?
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24189

Originally posted by David Harkness:
~ is not negation; it's called two's complement.

Two's complement would be flipping the bits and then adding one. Just flipping the bits is "one's complement".

[Jess in Action][AskingGoodQuestions]
Ryan McGuire
Ranch Hand

Joined: Feb 18, 2005
Posts: 1030
To combine and extend what David and Ernest said...

If we just look at 16 bits 4 = 0000000000000100. The ~ does a one's complement operation, so ~4 = 1111111111111011. The - does a two's complement operation, which is the one's complement plus 1, so -4 = 1111111111111100. Since 5 = 0000000000000101, -5 = 1111111111111011, which is the same things as ~4.

Why use two's complement for negative numbers? Because it makes subtraction work. For instance let's try 5 + (-4): 0000000000000101 + 1111111111111100 = 0000000000000001 with a 1 bit that got carried off the left end. With the one's complement, the answer is off by one.

One other clever thing about two's complment is that -0 = 0, while ~0 != 0.

[ April 26, 2005: Message edited by: Ryan McGuire ]
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Too long outside of the classroom. Thanks guys for clarifying!
I agree. Here's the link:
subject: negation operator