Conversions and Promotions In Java

In this article we will discuss primitive conversion.
· Type Conversion ∘ Implicit type conversion ∘ Explicit type conversion · Automatic Type Promotion in Expressions · Difference between Type Casting and Type Coercion
In computer science, type conversion, type casting, type coercion, and type juggling are different ways of changing an expression from one data type to another. An example would be the conversion of an integer value into a floating point value or its textual representation as a string, and vice versa. Type conversions can take advantage of certain features of type hierarchies or data representations. Two important aspects of a type conversion are whether it happens implicitly (automatically) or explicitly,and whether the underlying data representation is converted from one representation into another, or a given representation is merely reinterpreted as the representation of another data type. In general, both primitive and compound data types can be converted.
Each programming language has its own rules on how types can be converted. Languages with strong typing typically do little implicit conversion and discourage the reinterpretation of representations, while languages with weak typing perform many implicit conversions between data types. Weak typing language often allow forcing the compiler to arbitrarily interpret a data item as having different representations — this can be a non-obvious programming error, or a technical method to directly deal with underlying hardware.
Java provides various data types just likely any other dynamic languages such as boolean, char, int, unsigned int, signed int, float, double, long, etc in total providing 7 types where every datatype acquires different space while storing in memory.

Type Conversion
If you have previous programming experience, then you already know that it is fairly common to assign a value of one type to a variable of another type If the two types are compatible, then Java will perform the conversion automatically (type conversion) . For example, it is always possible to assign an int value to a long variable. However, not all types are compatible, and thus, not all type conversions are implicitly allowed. For instance, there is no automatic conversion defined from double to byte. Fortunately, it is still possible to obtain a conversion between incompatible types. To do so, you must use a cast , which performs an explicit conversion between incompatible types . Let’s look at both automatic or widening type conversions (type coercion , type juggling) and narrowing or explicit Conversion (type casting).
As you can see, it’s possible to perform a cast on a numeric value as well as on a variable. Notice that you can introduce superfluous casts; for example, the compiler will automatically promote an int value to a long when necessary. However, you are allowed to use superfluous casts to make a point or to clarify your code. In other situations, a cast may be essential just to get the code to compile.
In C and C++, type conversion can cause some headaches. In Java, conversion is safe, with the exception that when you perform a so-called narrowing conversion (that is, when you go from a data type that can hold more information to one that doesn’t hold as much), you run the risk of losing information. Here the compiler forces you to use a cast (type casting), in effect saying, “This can be a dangerous thing to do — if you want me to do it anyway you must make the conversion explicit.” With a widening conversion a cast (explicit cast) is not needed, because the new type will more than hold the information from the old type so that no information is ever lost. Java allows you to convert any primitive type to any other primitive type, except for boolean, which doesn’t allow any casting at all. Class types do not allow casting. To convert one to the other, there must be special methods. (…)
Implicit type conversion
Also known as ‘automatic or wedninig type conversion’.

- Done by the compiler on its own, without any external trigger from the user.
- Generally takes place when in an expression more than one data type is present. In such condition type conversion (type promotion) takes place to avoid lose of data.
- All the data types of the variables are upgraded to the data type of the variable with largest data type.
bool -> char -> short int -> int ->
unsigned int -> long -> unsigned ->
long long -> float -> double -> long doubleWhen one type of data is assigned to another type of variable, an automatic type conversion will take place if the following two conditions are met:
- The two types are compatible. For example, data types such as numeric are compatible with other numeric data types, but they are not compatible with boolean, char, or String data types. In the same way as String is not compatible with a boolean data type.
- The destination type is larger than the source type.
When these two conditions are met, a widening conversion takes place. For example, the int type is always large enough to hold all valid byte values, so no explicit cast statement is required. For widening conversions, the numeric types, including integer and floating-point types, are compatible with each other. However, there are no automatic conversions from the numeric types to char or boolean. Also, char and boolean are not compatible with each other.
It is possible for implicit conversions to lose information, signs can be lost (when signed is implicitly converted to unsigned), and overflow can occur (when long long is implicitly converted to float).
sometimes we refer to this type of conversion as type ceorcion.
In Java, the mechanism of converting one type of object to another object of a different type with similar content is known as coercion. In other words, we can say that coercion is the process of converting one data type to another data type. In a more specific way, implicit conversion is called coercion. It is also known as type coercion.
In type ceorcion, a data type is automatically converted into another data type by a compiler at the compiler time. In type ceorcion, the destination data type cannot be smaller than the source data type, that’s why it is also called widening conversion. One more important thing is that it can only be applied to compatible data types.
Type Ceorcion example –
int x=30;
float y;
y=x; // y==30.000000.The following figure shows type conversions between Java’s numeric data types.

Java will automatically coerce data in the direction of the arrows, either solid or dashed. For example:

Coercions that traverse a dotted arrow are allowed but may result in loss of precision. It means that the converted value may not be equal to the starting value. For example:

The compiler occurs an error if any statement tries to coerce data against the direction of the arrows.

Let’s look at an example of implicit type casting in Java.
Here, we will convert an int value to a long value and finally to a double value by using a simple assignment operator:
public class Main {
public static void main(String[] args) {
int a = 20;
long b = a; //implicit casting from int to long data type
double c = b;
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
} // implicit casting from long to double data typeOutput:
20
20
20.0The key difference between type coercion and type conversion is that type coercion is always implicit, whereas type conversion can be either implicit or explicit.
In other words, “type conversion” refers to the general process of changing a type, whereas type coercion refers more specifically to the implicit conversion of a type. We can further sub-divide type coercion into two kinds — programmer controlled, and compiler controlled (sometimes referred to as juggling).
Explicit type conversion
Although the automatic type conversions are helpful, they will not fulfill all needs. For example, what if you want to assign an int value to a byte variable? This conversion will not be performed automatically, because a byte is smaller than an int. This kind of conversion is sometimes called a type casting and it is user-defined.
This process is also called narrowing type convertion, since you are explicitly making the value narrower so that it will fit into the target type.
To create a conversion between two incompatible types, you must use a type casting. A cast is simply an explicit type conversion.
In Java , it can be done by using a cast operator () :
This is done by explicitly defining the required type in front of the expression in parenthesis.
It has this general form:
(target-type) expressionwhere target-type indicates the data type to which the final result is converted.
Here, target-type specifies the desired type to convert the specified value to. For example, the following fragment casts an int to a byte. If the integer’s value is larger than the range of a byte, it will be reduced modulo (the remainder of an integer division by the) byte’s range.
int a;
byte b; // …
b = (byte) a;A different type of conversion will occur when a floating-point value is assigned to an integer type: truncation. As you know, integers do not have fractional components. Thus, when a floating-point value is assigned to an integer type, the fractional component is lost. For example, if the value 1.23 is assigned to an integer, the resulting value will simply be 1. The 0.23 will have been truncated. Of course, if the size of the whole number component is too large to fit into the target integer type, then that value will be reduced modulo the target type’s range.
The following program demonstrates some type conversions that require casts:
// Demonstrate casts.
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}This program generates the following output:
Conversion of int to byte. i and b 257 1
Conversion of double to int. d and i 323.142 323
Conversion of double to byte. d and b 323.142 67Let’s look at each conversion. When the value 257 is cast into a byte variable, the result is the remainder of the division of 257 by 256 (the range of a byte), which is 1 in this case. When the d is converted to an int, its fractional component is lost. When d is converted to a byte, its fractional component is lost, and the value is reduced modulo 256, which in this case is 67.
Lets look at an example of explicit casting in Java:
public class Main {
public static void main(String args[]) {
double d = 57.17;
int i = (int)d; // Explicit casting from long to int data type
System.out.println(d);
System.out.println(i); //fractional part lost
}
}Output:
57.17
57
57In the example above, we converted the double data type into an int data type. The decimal part of the value is lost after type casting.
Automatic Type Promotion in Expressions
Type promotion is a common occurrence in Java programming, which can be achieved automatically with primitive data types through the use of autotype promotion. It is also referred to as automatic data type promotion.
As you might know in addition to assignments, there is another place where certain type conversions may occur: in expressions.
Below is a diagrammatic illustration of possible type promotions:

You’ll discover that if you perform any mathematical or bitwise operations on primitive data types that are smaller than an int (that is, char, byte, or short), those values will be promoted to int before performing the operations, and the resulting value will be of type int. So if you want to assign back into the smaller type, you must use a cast. (And, since you’re assigning back into a smaller type, you might be losing information.) In general, the largest data type in an expression is the one that determines the size of the result of that expression; if you multiply a float and a double, the result will be double; if you add an int and a long, the result will be long.
To understand more :
consider the following. In an expression, the precision required of an intermediate value will sometimes exceed the range of either operand. For example, examine the following expression:
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;The result of the intermediate term a*b easily exceeds the range of either of its byte operands. To handle this kind of problem, Java automatically promotes each byte, short, or char operand to int when evaluating an expression. This means that the subexpression a*b is performed using integers — not bytes. Thus, 2,000, the result of the intermediate expression, 50 * 40, is legal even though a and b are both specified as type byte.
As useful as the automatic promotions are, they can cause confusing compile-time errors. For example, this seemingly correct code causes a problem:
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!The code is attempting to store 50 * 2, a perfectly valid byte value, back into a byte variable. However, because the operands were automatically promoted to int when the expression was evaluated, the result has also been promoted to int. Thus, the result of the expression is now of type int, which cannot be assigned to a byte without the use of a cast. This is true even if, as in this particular case, the value being assigned would still fit in the target type.
In cases where you understand the consequences of overflow, you should use an explicit cast, such as
byte b = 50;
b = (byte)(b * 2);which yields the correct value of 100.
Rules for automatic type promotion
The following rules for type promotion must be followed when executing expressions in Java to achieve correct results:
- All variables of the types byte, short, and char must be auto type promoted to int.
- If any variable taking part in an operation is long, the operation result must be long.
- If any variable taking part in an operation is float, the operation result must float.
in sample words all byte, short, and char values are promoted to int, as just described. Then, if one operand is a long, the whole expression is promoted to long. If one operand is a float, the entire expression is promoted to float. If any of the operands is double, the result is double.
Let’s see some Java examples depicting the numeric promotion rules in Java-
1- When one of the operand is double.
public class PromotionExample {
public static void main(String[] args) {
int i = 30;
double d = 2.5;
double result = i * d;
System.out.println("Result is- " + result);
}
}
// output :
// Result is- 75.0In the code one of the operand is int and another operand is double so the expression result has to be double because of the numeric promotion.
2- When one of the operand is float.
public class PromotionExample {
public static void main(String[] args) {
short s = 4;
int i = 30;
float f = 6.75f;
float result = (s+i) * f;
System.out.println("Result is- " + result);
}
}
//output
// Result is- 229.5In the code one of the operand is float so the whole expression is promoted to float.
3- Trying to assign the result to int when one of the operand is float.
public class PromotionExample {
public static void main(String[] args) {
byte a= 100;
byte b= 50;
int i= 80;
float f = 80;
result = f/i *b; // line 6
}
}
Difference between Type Casting and Type Coercion
Let’s see the difference between Type casting and Type Coercion which are given below:
- In type casting, a data type is converted into another data type by a programmer using casting operator. Whereas in type coercion, a data type is converted into another data type by a compiler.
- Type casting can be applied to compatible data types as well as incompatible data types.Whereas type coercion can only be applied to compatible datatypes.
- In type casting, casting operator is needed in order to cast a data type to another data type.Whereas in type coercion, there is no need for a casting operator.
- In type casting (explicit type conversion) , the destination data type may be smaller than the source data type, when converting the data type to another data type.Whereas in type coercion (implecit type convertion) , the destination data type can’t be smaller than source data type.
- Type casting takes place during the program design by programmer.Whereas type conversion (implecit type convertion) is done at the compile time.
- Type casting is also called narrowing conversion because in this, the destination data type may be smaller than the source data type.Whereas type coercion (implecit type conversion) is also called widening conversion because in this, the destination data type can not be smaller than the source data type.
- Type casting is often used in coding and competitive programming works.Whereas type coercion (implecit type conversion) is less used in coding and competitive programming as it might cause incorrect answer.
- Type casting is more efficient and reliable.Whereas type coercion (implecit type convertion) is less efficient and less reliable.
Thanks for reading.Happy learning 😄
Do support our publication by following it
Also refer to the following articles.






