简体   繁体   中英

Type casting and automatic type promotion in Java

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++;

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM