java – Difference between casting and promotion


What is casting ? What is promotion ? What is the basic difference between these types of conversions in Java?


Promotion is the elevation of the numeric types that exist in the language to a type that can represent a greater magnitude. The rules of what can be promoted are specified in the language and always indicate that a primitive type * of less numerical capacity can be used in a place where a type with greater capacity will be needed. Promotion never causes data loss. It is done implicitly by the compiler.

Casting is the change from one type to another explicitly through the casting operator (the type name in parentheses). There may or may not be a change of representation of the value, and in this conversion there may be data loss. A runtime error will occur if the conversion cannot be performed or the compiler may detect the impossibility of the operation first. Casting may or may not change the representation of the value, which does not run on types by reference.

Documentation for more information.

Note that this is only valid for Java. Other languages ​​have their own rules and terminology. I don't know what it looks like with the advent of struct s in Java.

* This primitive idea is going to get complicated when Java has such basic data that isn't primitive (and it will soon). And I want to see how they're going to deal with casting once they've decided not to have operator overload, are they going to change their minds or is it just another lame thing?

Scroll to Top