3

Let's consider some simple expressions in Java.

byte var=0;

var=(byte)(var+1);

Here, in the above statement, obviously type casting is needed because of automatic type promotion.

The evaluation of the expression (var+1) is automatically promoted to int hence, must explicitly be cast to byte to assign the outcome of it to a byte variable on the right of the assignment which is var


Now, let's consider the following statement in Java.

var++;

This is somewhat equivalent to the previous statement and should have needed a cast though it works without a cast. Why?


Even the following statement doesn't require a cast. Why?

byte x=var++;
Lion
  • 18,729
  • 22
  • 80
  • 110
  • 1
    It's only equivalent if you couldn't add a (byte) 1 to var, but you can--why wouldn't ++ use the correct type? – Dave Newton Nov 14 '11 at 02:55

1 Answers1

9

From the Java Language Specification, §15.14.2:

The type of the postfix increment expression is the type of the variable.

On the other hand, for the expression var + 1, the following rules apply (JLS, §5.6.2):

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order, using widening conversion (§5.1.2) to convert operands as necessary:

• If any of the operands is of a reference type, unboxing conversion (§5.1.8) is performed. Then:
• If either operand is of type double, the other is converted to double.
• Otherwise, if either operand is of type float, the other is converted to float.
• Otherwise, if either operand is of type long, the other is converted to long.
• Otherwise, both operands are converted to type int.

So adding two numerical types will never give a result narrower than an int.

Community
  • 1
  • 1
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521