Google News
logo
Java Program to convert int type variables to double
In this program, we will learn to convert the integer (int) variables into the double in Java.

Example 1: Java Program to Convert int to double using Typecasting :

Program :
class Main {
  public static void main(String[] args) {

    // create int variables
    int a =33;
    int b = 29;

    // convert int into double
    // using typecasting
    double c = a;
    double d = b;

    System.out.println(c);    // 33.0
    System.out.println(d);    // 29.0
  }
}
Output :
33.0
29.0


In the above example, we have int type variables a and b. Notice the line,

double c = a;

Here, the int type variable is automatically converted into double. It is because double is a higher data type (data type with larger size) and int is a lower data type (data type with smaller size).

Hence, there will be no loss in data while converting from int to double.


Example 2: Convert int to object of Double using valueOf()  :

We can also convert the int type variable into an object of the Double class. For example,
Program :
class Main {
  public static void main(String[] args) {

    // create int variables
    int a = 332;

    // convert to an object of Double
    // using valueOf()
    Double obj = Double.valueOf(a);

    System.out.println(obj);    // 332.0
  }
}
Output :
332.0
In the above example, we have used the Double.valueOf() method to convert the variable a into an object of Double.

Here, Double is a wrapper class in Java.