• Post Reply Bookmark Topic Watch Topic
  • New Topic

~ operator  RSS feed

 
SanjayR Jain
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How the ~operator works?
 
Campbell Ritchie
Marshal
Posts: 56518
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does this Java™ Tutorials page help? Remember ~ is a unary operator and has a higher precedence than */%.
 
SanjayR Jain
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As I go through the tutorials, It is a bitwise complement operator.

I have made java application in which I do this.

public static void main(String[] args) {
System.out.println(~4);
}

Result of this is -5.
I am not getting why the output is -5?
 
Campbell Ritchie
Marshal
Posts: 56518
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You will have to write down the bit values for 4, then invert them, then convert them back to decimal remembering you are using two's complement arithmetic.

Then you will get -5.
 
SanjayR Jain
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok Now I got it.
Thanks a lot
 
Campbell Ritchie
Marshal
Posts: 56518
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well done
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!