Java Program to convert int type variables to double

To understand this example, you should have the knowledge of the following Java programming topics:


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

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

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. This is called widening typecasting. To learn more, visit Java Typecasting.


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,

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

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. To learn more, visit the Java Wrapper Class.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges