Alex
Alex

Reputation: 2030

Primitive conversions code | Help needed to understand

Please help me to understand how following code is working?

int i = (byte) +(char) -(int) +(long) -1;

Upvotes: 0

Views: 40

Answers (1)

jrtapsell
jrtapsell

Reputation: 7001

Expanded code

final long longValue = +(long) -1;
final int intValue = -(int) longValue;
final int charValue = +(char) intValue;
final int byteValue = (byte) charValue;
System.out.printf("%s %s %s %s%n", longValue, intValue, charValue, byteValue);

Output:

-1 1 1 1

Explanation

  • The long value is the same -1 as before, but as a long, because + by iteself does nothing
    • After value: -1
  • The int value is equal to 1, as it inverts the -1
    • After value: 1
  • The char value keeps this value, but converts to a char
    • After value: 1
  • The byte value keeps this value, but converts to a byte
    • After value: 1

So the end result is 1

Upvotes: 3

Related Questions