How to Convert Miles to Kilometers in Java

Miles and Kilometers are different units used for distance measurement. Miles is part of the imperial system and Kilometers is part of the metric system. The following formula can be used to convert miles into kilometers,

Distance in km = 1.60934 * distance in miles.

The following formula can be used to convert kilometers to miles,

Distance in miles = 0.621371 * distance in km

The following Java example program contains methods for converting miles to kilometers and vice versa.

import java.util.Scanner;

// Java example - converts miles to km and km to miles
public class DistanceConverter {
    public static void main(String[] args) {
        System.out.print("Enter distance in miles:");
        Scanner s = new Scanner(System.in);

        double distanceInMiles = s.nextDouble();

        System.out.println(distanceInMiles + " miles = " + milesTokm(distanceInMiles) + " km");

        System.out.print("Enter distance in km:");
        double distanceInKm = s.nextDouble();

        System.out.println(distanceInKm + " km = " + kmTomiles(distanceInKm) + " miles");
        s.close();

    }

    private static double milesTokm(double distanceInMiles) {
        return distanceInMiles * 1.60934;
    }

    private static double kmTomiles(double distanceInKm) {
        return distanceInKm * 0.621371;
    }
}