Coercion in Java
Many programming languages, including Java, allow conversion of a data type to another data type as a convenience to the programmer. The kind of conversion may be implicit or explicit. The implicit conversion is done automatically by JVM but explicit conversion is done by the programmer.
In this section, we will discuss coercion (also known as type conversion).
What is Coercion?
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.
It occurs because the datum (information) is stored as one data type but its context requires a different data type. For example, the constant (sum) 20 is an integer but its context requires a double value.
Example of Coercion
Conversion of String to Integer, Long to Double would be coercion.
Another example, if we want to coerce the StringBuffer to an Integer, in such a case the following series of coercions will execute.
Consider the following code statements. In the third statement, the value of the count is automatically converted to double before executing the division (/) operator.
There is a hidden machine operation performed on data at the execution time of the program.
Numeric Data Coercion
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.
To overcome the above problem, we can use type casting to specify a data conversion against the direction of an arrow.
Difference Between Type Casting and Type Coercion
The conversion of primitive data type into another data type is known as type casting or type conversion. There are two ways to cast the primitive data type, widening, and narrowing. It is also known as implicit type casting because it is done automatically.
Casting is the process by which we treat an object type as another type while coercing is the process of converting one object to another.