In this tutorial, you will learn how to convert int to double in Java. Since double has longer range than int data type, java automatically converts int value to double when the int value is assigned to double. In this guide, we will discuss three ways to do this conversion.
- Implicit Casting: As discussed, Java automatically converts an
int
to adouble
when required. - Explicit Casting: You can explicitly cast an
int
to adouble
. - Using
Double
Class: TheDouble
class provides valueOf() method for this conversion.
1. Implicit Casting
Since double data type has wider range and greater memory size than int, the conversion from int to double is implicit. As you can see we have not done the typecasting like we did in double to int conversion in Java.
public class JavaExample{ public static void main(String args[]){ int intValue = 100; double doubleValue = intValue; // Implicit casting System.out.println(doubleValue); // Output: 100.0 } }
2. Explicit Casting
You can explicitly cast an int to double as shown in the following example:
public class JavaExample{ public static void main(String args[]){ int intValue = 100; double doubleValue = (double) intValue; // Explicit casting System.out.println(doubleValue); // Output: 100.0 } }
3. Using valueOf() method of Double Class
In this example, we are converting int to double using valueOf()
method of Double wrapper class. This method accepts the other type value as argument and returns the value in double type.
public class JavaExample{ public static void main(String args[]){ int intValue = 100; // Using valueOf() method double doubleValue = Double.valueOf(intValue); System.out.println(doubleValue); // Output: 100.0 } }
Recommended Posts:
Leave a Reply