jQuery in Action, 2nd edition*
The moose likes Beginning Java and the fly likes inversion operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "inversion operator" Watch "inversion operator" New topic
Author

inversion operator

Rally Krish
Greenhorn

Joined: Jul 20, 2006
Posts: 5
What gets printed when the following program is compiled and run. Select the one correct answer.


public class test {
public static void main(String args[]) {
byte x = 3;
x = (byte)~x;
System.out.println(x);
}
}


pls expain

Thanks in advance
vidya sagar
Ranch Hand

Joined: Mar 02, 2005
Posts: 580
Answer is -4.

3 when represents in 8 bit(Because it is byte).It will be

3 = 0000 0011
~3 = 1111 1100

Binary 1111 1100 when converted to decimal it results in -4
Rally Krish
Greenhorn

Joined: Jul 20, 2006
Posts: 5
Thanks

Binary 1111 1100 when converted to decimal it results in -4

can u pls expalin the conversion
vidya sagar
Ranch Hand

Joined: Mar 02, 2005
Posts: 580
Operators
Rally Krish
Greenhorn

Joined: Jul 20, 2006
Posts: 5
vidya sagar,

studying, i got struck here "-6 in binary is 11111010"

again i need to know how exactly the conversion is taking place

Thanks
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18553
    
  40

Originally posted by Rally Krish:
vidya sagar,

studying, i got struck here "-6 in binary is 11111010"

again i need to know how exactly the conversion is taking place

Thanks


Java uses two's complement to represent integers. But to summarize the link -- to negate a number, the two's complement operation is to invert all the bits, and add one.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: inversion operator
 
Similar Threads
Getting error in this code??? why is that so?
~operator
The Shift Operators
Bitwise inversion operator question