The Wayback Machine - https://web.archive.org/web/20240731085737/https://www.geeksforgeeks.org/coercion-in-java/
Open In App

Coercion in Java

Last Updated : 25 Feb, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

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.

  • implicit conversion: This type of conversion is automatically done by the programming languages. In the case of Java, it is done by the JVM ( Java Virtual Machine ).
  • explicit conversion: This type of conversion has to be done by the programmer as per their requirements. (No rule of JVM)

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




// 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: 

 

  • Fetches the value of the numerator variable.
  • Use of the literal value i.e. 5.
  • Converts the value of the literal value to a floating point.
  • Performs floating-point division (CPU task).
  • Stores the result into memory allocated to the result variable.

 

Example 2

 

Java




// 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:

 

  • byte + short = int
  • short + byte = int
  • char + short = int
  • byte + byte = int
  • int + int = int
  • int + float = float
  • long + float = float
  • float + double = double
  • long + double = double….. and many more.

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.
 

 



Similar Reads

Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Java.util.TreeMap.floorEntry() and floorKey() in Java
Finding greatest number less than given value is used in many a places and having that feature in a map based container is always a plus. Java.util.TreeMap also offers this functionality using floor() function. There are 2 variants, both are discussed below. 1. floorEntry() : It returns a key-value mapping associated with the greatest key less than
3 min read
java.lang.Math.atan2() in Java
atan2() is an inbuilt method in Java that is used to return the theta component from the polar coordinate. The atan2() method returns a numeric value between -[Tex]\pi [/Tex]and [Tex]\pi [/Tex]representing the angle [Tex]\theta [/Tex]of a (x, y) point and the positive x-axis. It is the counterclockwise angle, measured in radian, between the positiv
1 min read
java.net.URLConnection Class in Java
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL cl
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg