This blog will describe the method for converting int to double in Java.
How to Convert int to double in Java?
For converting int to double, you can use the:
- Assignment operator
- Typecasting
- valueOf() method
We will now check out each of the mentioned methods one by one.
Method 1: Convert int to double Using Assignment Operator
In Java programming language, the lower data type can be easily converted to the higher data type using the Assignment operator “=”. This is called an implicit conversion.
Syntax
Here, the assignment operator “=” will convert “a” int type variable to “b”, which is a double type variable.
Example
In this example, firstly, we will create an int variable named “a” with the following value:
Then, we will convert it to double using the “=” assignment operator and store the resultant value in “b”:
Lastly, execute the “System.out.println()” method to display the converted value on the console:
The output shows that the integer is successfully converted into a double value:
Method 2: Convert int to double Using Typecasting
Typecasting is used when we want to convert one datatype to another. More specifically, it can also be utilized for int to double conversion.
Syntax
Here, we will convert “a” int type variable to “b”, which is a double type variable. The (double) indicates the required typecasted data type.
Example
In this example, we will use the same integer type “a” variable and convert its value to “double” using Typecasting. Here, the assignment operator is also used; however, the specified integer is typecasted in the double and then stored in the double type variable “b”:
Then, print out the converted value using the “System.out.println()” method:
Output
Want to utilize any built-in Java method for the specified purpose? Head toward the next section!
Method 3: Convert int to double Using valueOf() Method
The “Double” Java wrapper class offers a “valueOf()” method that can be used to convert int to double. It is a static type method, which means we do not need to create an object and call the method by using the class name, as it can be accessed without this additional step.
Syntax
Here, we will convert “a” int type variable to “b” by passing it as an argument to the “valueOf()” method.
Example
Here, we will convert the value of the already created “a” variable using the valueOf() method. The method will take “a” as an argument and returns the converted double value:
Finally, print out the converted value using the “System.out.println()” method:
Output
We compiled all the essential instructions related to converting int to double in Java.
Conclusion
To convert int to double in Java, there are three methods: using the Assignment operator, using Typecasting, and the valueOf() method of the Double Java wrapper class. All these methods approximately work the same; however, you may choose any one depending on your preferences. In this post, we described the methods to convert an int to double in Java.