Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type casting and automatic type promotion in Java

Tags:

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++;
like image 427
Lion Avatar asked Apr 22 '26 03:04

Lion


1 Answers

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.

like image 87
Ted Hopp Avatar answered Apr 24 '26 22:04

Ted Hopp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!