DEV Community

Dayo
Dayo

Posted on

Type Conversion and Casting

Type casting is the process of converting a variable from one data type to another. In Java, which is a statically-typed language, variables have a specific type, and type casting allows you to change a variable’s type under certain conditions.

In Java, numeric values are typically stored using data types such as int, long, byte, double, and float. Character values are stored using String, char, and boolean for boolean values (true or false).

Implicit Conversion

Implicit or automatic conversion occurs when two conditions are met:

the two types are compatible, 

the destination type is larger than the source. 

For example, converting from a byte to a long is implicitly done by Java because the long type is large enough to hold all values of a byte. This is also known as widening conversion.

However, implicit conversion has drawbacks. For instance, if an operation results in a value that cannot be accommodated by the destination type, a compile-time error occurs.

Explicit Conversion

On the other hand, explicit conversion occurs when the destination type is smaller than the source type. For example, if a long value is being assigned to an int variable, explicit conversion is required. This is also known as narrowing conversion and is done using type casting with the general form: (target type) value.

Type Promotion Rules
Type promotion rules dictate the promotion of data types when performing operations. First, byte, short, and char values are promoted to int. If one operand is a long, the entire expression is promoted to long. If one operand is a float, the entire expression is promoted to float. If any operand is double, the result is double. These rules help ensure consistent and predictable behaviour during operations involving different data types.

Top comments (0)