Why mixing + and cast does not produce an error in "+(int)+(long)-1"?
You are not adding nor substracting. Those + and - operators are unary sign operators.
See documentation at The Unary Operators section.
The sequence at stake:
(byte)+(short)-(int)+(long)-1
is evaluated from right to left like this:
the initial value is -1
casting to long (which is still -1)
unary + sign (still -1)
casting to int (still -1)
unary - sign (now the value is 1)
so on (the value remains 1 until the end)
These +
and -
are unary ones.
More specifically, it is in fact:
System.out.println((byte) (+((short) (-((int) (+((long) -1)))))));
if you remove all casting from your example, because in this case it will do nothing
System.out.println((byte)+(short)-(int)+(long)-1);
will become
System.out.println( + - + -1);
now you can see that just the operators are still there and because minus and minus are plus your result will be 1
basically you can think of it like:
var mylong = +(long)-1; <- -1
var myint = -(int)mylong; <- 1
var myshort = +(short)myint; <- 1
var mybyte = (byte)myshort; <- 1