This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Beginning Java and the fly likes Unary opearator... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Unary opearator..." Watch "Unary opearator..." New topic

Unary opearator...

banu saro

Joined: Jul 12, 2005
Posts: 3
What is the output of following code and could some one explain me how it is.
int x = 1;
int y = ~x + 1;

How does ~x works?
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Moving to Java In General (Beginner)...

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Rishi Chopra
Ranch Hand

Joined: Mar 07, 2004
Posts: 108
int x=1;

this means:-- x=00000000 00000000 00000000 00000001 ( representing as 32 bit).

int y=~ x +1;

here ~x inverts all bits in x. so now x :-

~x =11111111 11111111 11111111 11111110 ;
y=~x+1 =11111111 11111111 11111111 11111111;

now this number has left most bit as one so the "y is negative" using 2-complement rule here..

according to it:

invert all digit and 1 to it

y = (-) 00000000 00000000 00000000 00000000 + 1;
y = (-) 00000000 00000000 00000000 00000001;
y= (-) 1;

thus System.out.println(y); prints -1

hope u get the logic of unary operator;

Life is Beautiful Learn to See it.........
Consider Paul's rocket mass heater.
subject: Unary opearator...