Converting an int to a double in Java is a widening conversion, meaning you’re converting from a smaller data type (int, which is 32 bits) to a larger one (double, which is 64 bits). This type of conversion is safe and does not result in any data loss, as a double can hold any int value without issue.
int vs double
1. int is a 32-bit signed integer, with a range of -2^31 to 2^31 – 1 (i.e., -2,147,483,648 to 2,147,483,647).
2. double is a 64-bit floating-point number, which can represent a much wider range of values, including both large numbers and decimal values.
1. Implicit Conversion (Widening Conversion)
You can directly assign an int value to a double variable, and Java will automatically convert it. This is done through implicit casting.
Example:
public class IntToDoubleExample {
public static void main(String[] args) {
int intValue = 35; // 'int' type (32 bits)
// Implicit conversion from int to double
double doubleValue = intValue; // No casting needed
System.out.println(doubleValue); // Output: 35.0
}
}
Explanation:
1. In this example, we assign an int value (35) to a double variable (doubleValue).
2. Java automatically converts the int to a double when performing the assignment, and the result is 35.0. Note that the double version of 35 has a decimal point (.0), because double can represent decimal values.
2. Explicit Casting
Though explicit casting is typically used for narrowing conversions (such as converting a double to an int), it’s not necessary when converting from int to double. Java will automatically convert int to double without needing explicit casting.
Example:
public class IntToDoubleExample {
public static void main(String[] args) {
int intValue = 35; // 'int' type
// Explicitly cast int to double (not necessary but works)
double doubleValue = (double) intValue; // Explicit casting
System.out.println(doubleValue); // Output: 35.0
}
}
Explanation:
1. In this case, we are explicitly casting the int value to double using (double) intValue.
2. Even though this works, it is not necessary in this case because Java handles the conversion automatically as part of the widening conversion.