Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding java program [duplicate]

Tags:

java

Possible Duplicate:
Weird java behavior with casts to primitive types

Why following prints 1?

int i = (char) - (int) + (long) - 1;
System.out.println(i);

Why above lines of code prints 1? How come the value of i become 1?

like image 296
Harry Joy Avatar asked Jul 05 '26 12:07

Harry Joy


1 Answers

Look at it this way, with each expression getting its own variable (well, aside from the -1).

long a = (long) -1; // a = -1
int b = (int) a;    // b = -1
int c = -b;         // c = 1
int d = (char) c;   // d = 1
int i = (int) d;    // i = 1 (implicit conversion)
like image 92
Jon Skeet Avatar answered Jul 07 '26 01:07

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!