Convert Miles to Kilometers in Java
Problem
One mile equals about 1.60934 kilometers — converting between the two is a single multiplication by that fixed factor, the inverse of the kilometers-to-miles factor.
Given a distance in miles, convert it to kilometers.
Java Program
public class ConvertMilesToKilometers {
public static void main(String[] args) {
double miles = 10.0;
double km = miles * 1.60934; // fixed miles-to-km conversion factor
System.out.println(miles + " miles = " + km + " km");
}
}Output
Core Logic
Multiplying the mile value by the fixed conversion factor 1.60934 gives the equivalent distance in kilometers.
- 1
milesholds10.0. - 2
miles * 1.60934evaluates to16.0934. - 3Both values are printed together on one line.
miles = 10.0, 10.0 * 1.60934 gives 16.0934.Key Point: 1.60934 and 0.621371 (used on the kilometers-to-miles page) are each other's approximate reciprocals — converting a distance one way and then back the other way returns very close to the original value, aside from tiny rounding differences.
Key Concepts
Approach 2: Java 8
import java.util.function.DoubleUnaryOperator;
public class ConvertMilesToKilometersLambda {
public static void main(String[] args) {
double miles = 10.0;
// The conversion factor is stored as a reusable lambda
DoubleUnaryOperator toKilometers = m -> m * 1.60934;
double km = toKilometers.applyAsDouble(miles);
System.out.println(miles + " miles = " + km + " km");
}
}
Output
Core Logic
The conversion factor can be stored as a reusable lambda instead of being written inline.
- 1
DoubleUnaryOperator toKilometers = m -> m * 1.60934;stores the formula as a lambda. - 2
toKilometers.applyAsDouble(miles)calls it, returning the same value the inline expression would. - 3The result is printed exactly as before.
miles = 10.0, toKilometers.applyAsDouble(10.0) returns 16.0934.Key Point: Having both toMiles (see the Kilometers to Miles page) and toKilometers as separate lambdas keeps each conversion direction explicit, rather than trying to make one formula do both jobs.