In the previous article we have discussed Java Program to Convert int to long
In this article we will see how to convert an integer type to double type.
Program to Convert int to Double
Before going into the program directly, let’s see some examples of both the types.
Example-1: int type int a = 23; int b=5;
Example-2: double type double a = 3.123456789; double b = 3.55502;
Let’s see different ways to do it.
Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.
Method 1 : Java Program to Convert int to Double Using typecasting
int type variable can be converted to double type by using typecasting let’s see how it actually works.
Here this method is also called widening typecasting because in this the lower data type int is converted into the higher data type double.
Approach :
- Take an
intvalue and store it in a int variableinput1. - Typecast the variable with
doubleand store it in a variableoutput. - Display the result .
Program:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
// creating scanner object
Scanner sc = new Scanner(System.in);
// input a int value through scanner class
System.out.print("Enter an int value : ");
int input1=sc.nextInt();
// converting to Double
double output= input1 ;
System.out.println("Converted Double value is : " + output);
}
}
Output : Enter an int value : 6 Converted Double value is : 6.0
Method 2 : Java Program to Convert int to Double Using valueof() method
int type variable can be converted to double type by using valueof() , let’s see how it actually works.
Here, the valueof() method will convert the int type variable into double type variable and returns it.
Approach :
- Take an
inttype value and store it in a int variableinput1. - Then pass that
input1variable as parameter tovalueof()method which will convert the int to double value and return it . - Store that Double value in a variable output .
- Display the result .
Program:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
// creating scanner object
Scanner sc = new Scanner(System.in);
// input an int value through scanner class
System.out.print("Enter an int value : ");
int input1=sc.nextInt();
// converting to Double
Double output= Double.valueOf(input1);
System.out.println("Converted Double value is : " + output);
}
}
Output : Enter a Int value : 6 Converted Double value is : 6.0
The best and excellent way to learn a java programming language is by practicing Simple Java
Program Examples as it includes basic to advanced levels of concepts.
Related Java Program: