Open In App

Coercion in Java

Conversion of one data type to another is nowadays easy as many languages including Java supports the conversion as a convenience to the programmer. Here conversion can be done in two ways i.e. implicit or explicit conversion.



Coercion in Java 

here we will be discussing coercion (also known as type conversion). So, Coercion is the process of converting one type of data type to another. In a simple way, implicit conversion holds the title of coercion in java.



Example 1




// Java Program to Illustrate Coercion Via
// Integer  Data Type to Double  Data Type
 
// Importing required classes
import java.io.*;
 
// Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Declaring and initializing
        // integer and double variables
        int numerator = 15;
        double result = numerator / 5;
 
        // Print statement
        System.out.println("Result is in double format : "
                           + result);
    }
}

 
 

Output
Result is in double format : 3.0

In the above example, the constant (numerator) 15 is an integer but its context requires a double value.

 

Output explanation: Machine operation is performed on data at the execution time of the program are: 

 

 

Example 2

 




// Java Program to Illustrate Coercion Via
// Character data type to Integer data type
 
// Importing required classes
import java.io.*;
 
// Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Declaring character and integer variables
        char alphabet = 'A';
        int ascii_value = alphabet;
 
        // Print statement
        System.out.println("ASCII Value of A is: "
                           + ascii_value);
    }
}

 
 

Output
ASCII Value of A is: 65

 

In the above example, the ascii_value is an integer but its context requires a character value therefore with the help of coercion/implicit conversion it is possible with ease.

 

Here are a few more examples of few coercion done by JVM as listed below as follows:

 

Note: In the above points ” + ” be any arithmetic operator which is suitable with the corresponding data types.

Tip: Difference between Type Casting and Type Conversion?

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. 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.
 

 


Article Tags :