Ismail qouiqa 28 Jan 2020

Numeric promotion

During arithmetic operations, the type of operands could change into a larger one. This phenomenon is called numeric promotion, it happens when we perform arithmetic operations involving smaller and larger data types. For instance, if we add two numbers, one is int, the other is float. Java will promote the int one to float before performing addition, the result's type will be the larger type, which is float.

In the example above, on line 5, the number 5 is firstly promoted to its float version which is 5.0f before doing addition.

Notice that the statement on line 3 doesn't compile because assigning a result of larger type (float) to a variable of smaller type (int) is not possible. the float result must be casted to int as we've done on line 4.  Casting means adapting a value to its holder's type which usually implies loosing a part of that data to be able to fit in, this feature should be used with precaution.

Smaller operands types like byte, short, and char are always promoted to int , even if neither of the operands is int.