is it possible to upcast an increment operator from int to long in java?

Viewed 64

let's say I assign max value for an int variable.

int a = 2147483647;

if I increment, it causes an overflow.

System.out.println(++(long)a);

is this even allowed?? the above line gives error java: unexpected type required: variable found: value

3 Answers

This is not allowed. Casting changes the type of expressions, and hence produces an expression. The ++ operator increments variables, not expressions, so it can't operate on the expression (long)a.

For ++(long)a to make sense, a would have the type long after it has run, but Java is statically typed. A variable's type can't be changed once it is declared! You can create another variable with type long, and assign a to it. Then you can increment the new variable without causing overflow.

long longA = a;
System.out.println(++longA);

Another way is to let the int overflow, and treat the overflowed int as a long:

System.out.println(Integer.toUnsignedLong(++a));

This will give the illusion that ints can suddenly store a wider range of numbers, but actually you are just interpreting the negative ints in an alternative way.

++ does not just increment the value, it also stores the resulting value back - it needs a variable, an expression that can be used in the left side of an assignment - similarly ((long) a = ... is not valid.

just use (long)a + 1


Documentation of ++ JLS 15.15.1. Prefix Increment Operator ++

... The result of the unary expression must be a variable ... or a compile-time error occurs. ...

Casting ((long)a) does not result in a variable, it cannot be used.

Let's understand in this way. (long)++a and (long)a++ will work but in case of (long)++a typecasting will happen after increment where bits are already flooded over for int. So, you will not get what you want to achieve. And in your case ++(long)a this is having invalid argument issue where your code will not compile. But you can do so like this:

int a = 2147483647;
long b=(long)a;
System.out.println(++b);
Related