programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Unary opearator...

Greenhorn
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;
System.out.println(y);

How does ~x works?

Ranch Hand
Posts: 7729
Moving to Java In General (Beginner)...

Ranch Hand
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;

 I've got no option but to sell you all for scientific experiments. Or a tiny ad: The WEB SERVICES and JAX-RS Course https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS