RedSea
RedSea

Reputation: 301

Type Casting, Operator Precedence or something else?

I was asked to explain why the following snippet prints 1. I have stared at it for a while but not yet able to say why it prints out 1 or even why it does compile. Can someone kindly tell me why?

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

Upvotes: 1

Views: 243

Answers (2)

ernest_k
ernest_k

Reputation: 45339

This is just a sequence of casts and number/char conversions:

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

can be made verbose as:

int a = -1;
long b = (long) a;
int c = (int) -b; //makes it positive
char d = (char) c;
byte e = (byte) d;
int f = e;

System.out.println(f);

Upvotes: 2

Eran
Eran

Reputation: 394026

You have here 4 casting operators and 4 +/- operators.

Since +/- can't be applied to casting operators, the only way to evaluate this expression is by treat the - and + as unary operators :

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

Upvotes: 1

Related Questions