Convert Kilometers to Miles in Java
beginner· Basics & I/O · Conversions
Problem
One kilometer equals about 0.621371 miles — converting between the two is a single multiplication by that fixed factor.
Given a distance in kilometers, convert it to miles.
Input
km = 10.0
Output
10.0 km = 6.21371 miles
Java Program
Java
public class ConvertKilometersToMiles {
public static void main(String[] args) {
double km = 10.0;
double miles = km * 0.621371; // fixed km-to-miles conversion factor
System.out.println(km + " km = " + miles + " miles");
}
}Output
10.0 km = 6.21371 miles
Core Logic
Multiplying the kilometer value by the fixed conversion factor 0.621371 gives the equivalent distance in miles.
How It Works
- 1
kmholds10.0. - 2
km * 0.621371evaluates to6.21371. - 3Both values are printed together on one line.
For
km = 10.0, 10.0 * 0.621371 gives 6.21371.💡
Key Point: 0.621371 is a fixed physical conversion factor, the same way Math.PI is a fixed mathematical constant — it never changes, so it's safe to hardcode directly in the formula.
Key Concepts
doubleconversion factor
Approach 2: Java 8
Java
import java.util.function.DoubleUnaryOperator;
public class ConvertKilometersToMilesLambda {
public static void main(String[] args) {
double km = 10.0;
// The conversion factor is stored as a reusable lambda
DoubleUnaryOperator toMiles = k -> k * 0.621371;
double miles = toMiles.applyAsDouble(km);
System.out.println(km + " km = " + miles + " miles");
}
}
Output
10.0 km = 6.21371 miles
Core Logic
The conversion factor can be stored as a reusable lambda instead of being written inline.
How It Works
- 1
DoubleUnaryOperator toMiles = k -> k * 0.621371;stores the formula as a lambda. - 2
toMiles.applyAsDouble(km)calls it, returning the same value the inline expression would. - 3The result is printed exactly as before.
With
km = 10.0, toMiles.applyAsDouble(10.0) returns 6.21371.💡
Key Point: Once toMiles exists as a lambda, it can be reused for any number of kilometer values without repeating the conversion factor each time.
Key Concepts
DoubleUnaryOperatorfunctional interfacelambda expression