Java ProgramsBasics & I/OConvert Miles to Kilometers

Convert Miles to Kilometers in Java

beginner·  Basics & I/O  ·  Conversions

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.

Input
miles = 10.0
Output
10.0 miles = 16.0934 km

Java Program

Java
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

10.0 miles = 16.0934 km

Core Logic

Multiplying the mile value by the fixed conversion factor 1.60934 gives the equivalent distance in kilometers.

How It Works
  1. 1miles holds 10.0.
  2. 2miles * 1.60934 evaluates to 16.0934.
  3. 3Both values are printed together on one line.
For 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

doubleconversion factor

Approach 2: Java 8

Java
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

10.0 miles = 16.0934 km

Core Logic

The conversion factor can be stored as a reusable lambda instead of being written inline.

How It Works
  1. 1DoubleUnaryOperator toKilometers = m -> m * 1.60934; stores the formula as a lambda.
  2. 2toKilometers.applyAsDouble(miles) calls it, returning the same value the inline expression would.
  3. 3The result is printed exactly as before.
With 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.

Key Concepts

DoubleUnaryOperatorfunctional interfacelambda expression

Related Programs