How to Convert int to double in Java
How to Convert int to double in Java
When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to common data type before evaluating the expression. Java compiler follows certain rules to decide which variable’s data type is to be converted. It converts the lower data type to that of a higher data type implicitly.
The double data type has a longer range than an int data type. In Java, JVM automatically converts int value to double when we assign an integer value to double data type.
In the above figure, the left-side value can assign to any right-side value, and it is done implicitly. It is known as implicit type conversion or type promotion or widening conversion. There are two methods to convert int to double.
- Using Assignment Operator (without typecasting)
- Using Double.valueOf() method
Using Assignment Operator
Assignment of int to double is done implicitly. You can convert int to double by using assignment operator.
Example
In the following example, we have taken a variable s of type int and initialize the value 20 to it. We have assigned the variable s to the variable d of type double. The println statement prints the double value of s.
public class intTodoubleExample { public static void main(String args[]) { int s=20; double d=s; System.out.println(“double value of s is: ”+d); } }
Output
double value of s is: 20.0
Using Double.valueOf() method
You can also convert int to double using the valueOf() method of Double wrapper class. This method accepts the int type value as parameter and returns the same value converted in double type.
Example
In this example, we have taken two variables i and r of type int and initialized 50 and 29 to it, respectively. Double is a wrapper class, and d is an object of Double class. It parses the integer value i as an argument and returns the converted double value. The valueOf() is the method of Double class. It parses an integer value r as an argument and returns the converted double value of the variable r. The first println statement prints the double value of the variable i. and the second println statement prints the double value of the variable r.
public class intTodoubleExample1 { public static void main(String args[]) { int i=50; int r=29; Double d= new Double(i); //Using object of Double class Double dbl= Double.valueOf(r); //Using valueOf() method System.out.println("double value of i is: "+d); System.out.println("double value of r is: "+dbl); } }
Output
double value of i is: 50.0 double value of r is: 29.0