You can use Bitwise unary NOT operator

Check the Java Language Spec... there no such thing as a "Bitwise unary NOT operator". There is bitwise complement operator, just like the previous poster already said.

ps You can also exclusive OR with a value of all 1 bits.

Edited 3 Years Ago by JamesCherrill: Fixed UK spelling for bitwize (Thanks Tux) ;)

Comments
There's no such thing as "bitwize" :P

As james said:

You can use bitwise complement operator to get the complement of any number as like:

int a = 15;
int b = ~a;
System.out.println(b);

This code prints complement of 15.

Thanks

Comments
Adds no new info, just repeats previous

i have do it,but i don't understand why it gives output -16

because 15 in binary=1111 and complement of it=0000

can anyone tell this?

please.

In Java ints are represented using 32 bits, so 15 is represented as 0000 0000 0000 0000 0000 0000 0000 1111, and the complement of that is 1111 1111 1111 1111 1111 1111 1111 0000

i know that int is represented in 32 bit pattern,but how it calculate -16....as given output is...

1111 1111 1111 1111 1111 1111 1111 0000

It's a bit difficult to explain why -16 is 1111 1111 1111 1111 1111 1111 1111 0000, but that is what it is. Perhaps it will help if you know that -1 is 1111 1111 1111 1111 1111 1111 1111 1111 and then you do -1 + -1 to get 1111 1111 1111 1111 1111 1111 1111 1110 which is -2, and you can keep on going until you get to -16. Try it and see.

Also, it might help to read this wikipedia article: http://en.wikipedia.org/wiki/Two%27s_complement

Even though it looks like zero value is in the middle between positive and negative because the opposite of all-zero-bit is all-one-bit, it is not. Because 0 is (somewhat) being included in the positive side, there are 2^31 positive integer (0 up to (2^31)-1) and 2^31 negative integer (-1 up to -2^31) numbers. The first bit of the 32-bit is the sign bit.

Now, when you flip bits, it is not going to be exact as you think -- the flipped bit value of 15 is not -15. Below is value pairs from flipping bits. You can see that the pair is not perfectly matched to its own number but is off by 1.

/*
.. 8  7  6  5  4  3  2  1  0 -1 -2 -3 -4 -5 -6 -7 -8 -9 ..
   |  |  |  |  |  |  |  |  +--+  |  |  |  |  |  |  |  |
   |  |  |  |  |  |  |  +--------+  |  |  |  |  |  |  |
   |  |  |  |  |  |  +--------------+  |  |  |  |  |  |
   |  |  |  |  |  +--------------------+  |  |  |  |  |
   |  |  |  |  +--------------------------+  |  |  |  |
   |  |  |  +--------------------------------+  |  |  |
   |  |  +--------------------------------------+  |  |
   |  +--------------------------------------------+  |
   +--------------------------------------------------+
*/
This article has been dead for over six months. Start a new discussion instead.