Numeric primitives can be implicitly cast when the source type has a smaller range than the target type.
// Implicit casting
byte byteVar = 42;
short shortVar = byteVar;
int intVar = shortVar;
long longVar = intVar;
float floatVar = longVar;
double doubleVar = floatVar;
In the above example, the smaller data types (byte, short, int) are implicitly cast to larger data types (short, int, long, float, double) without explicit type conversion.
Explicit casting is necessary when the source type has a larger range than the target type.
// Explicit casting
double doubleVar = 42.0d;
float floatVar = (float) doubleVar;
long longVar = (long) floatVar;
int intVar = (int) longVar;
short shortVar = (short) intVar;
byte byteVar = (byte) shortVar;
Here, explicit casting is performed to convert a larger data type (double, float, long, int, short) to a smaller data type (float, long, int, short, byte).
When casting floating-point primitives (float, double) to whole number primitives, the number is rounded down.
Numeric promotion automatically occurs in certain situations.
static void testNumericPromotion() {
char char1 = 1, char2 = 2;
short short1 = 1, short2 = 2;
int int1 = 1, int2 = 2;
float float1 = 1.0f, float2 = 2.0f;
// char1 = char1 + char2; // Error: Cannot convert from int to char;
// short1 = short1 + short2; // Error: Cannot convert from int to short;
int1 = char1 + char2; // char is promoted to int.
int1 = short1 + short2; // short is promoted to int.
int1 = char1 + short2; // both char and short promoted to int.
float1 = short1 + float2; // short is promoted to float.
int1 = int1 + int2; // int is unchanged.
}
In the testNumericPromotion
method, numeric promotion is demonstrated with different data types. For example, when adding char1
and char2
, they are promoted to int
.
The boolean type cannot be cast to/from any other primitive type.
A char can be cast to/from any numeric type by using the code-point mappings specified by Unicode. A char is represented in memory as an unsigned 16-bit integer value (2 bytes). Casting to byte (1 byte) drops 8 bits (safe for ASCII characters).
int badInt = (int) true; // Compiler error: incompatible types
char char1 = (char) 65; // A
byte byte1 = (byte) 'A'; // 65
short short1 = (short) 'A'; // 65
int int1 = (int) 'A'; // 65
char char2 = (char) 8253; // ‽
byte byte2 = (byte) '‽'; // 61 (truncated code-point into the ASCII range)
short short2 = (short) '‽'; // 8253
int int2 = (int) '‽'; // 8253