English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java Input/Output (I/O)

Java Reader/Writer

Other Java topics

Java program converts int type variable to double

Java Examples

In this program, we will learn how to convert an integer (int) variable to a double value in Java.

To understand this example, you should understand the followingJava programmingTopic:

Example1A Java program that uses type conversion to convert int to double

class Main {
  public static void main(String[] args) {
    //Creating an int variable
    int a =33;
    int b = 29;
    //Convert int to double
    //Using type conversion
    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. Note this line,

double c = a;

In this case, an int type variable will be automatically converted to double. This is because double is a higher data type (a data type with a larger size) and a lower int data type (a data type with a smaller size).

Therefore, there will be no situation where data is truncated, and at the same time, from converting int to double. This is calledWidening Type Conversion. For more information, please visitJava Class Type Conversion.

Example2: Using valueOf() to convert int to Double object

We can also convert an int type variable to an object of the Double class. For example

class Main {
  public static void main(String[] args) {
    // Creating an int variable
    int a = 332;
    //Converting to Double object
    //Using valueOf()
    Double obj = Double.valueOf(a);
    System.out.println(obj);    // 332.0
  }
}

In the above example, we use the Double.valueOf() method to convert the variable a to a Double object.

Here, Double is a wrapper class in Java. For more information, please visitJava Wrapper Classes.

Java Examples