Topic
In this Java program, you will learn how to convert a distance given in kilometers to three different units: miles, meters, and centimeters. This is a basic conversion program that helps beginners practice variables, arithmetic operations, and printing formatted output in Java.
The key concepts involved include:
- Understanding of data types like
double - Arithmetic operations and conversion factors
- Printing results with
System.out.println
Examples
Example 1:
Input: 1.0 km
Output:
Miles: 0.621371
Meters: 1000.0
Centimeters: 100000.0
Example 2:
Input: 0.0 km
Output:
Miles: 0.0
Meters: 0.0
Centimeters: 0.0
Example 3:
Input: 3.5 km
Output:
Miles: 2.1747985
Meters: 3500.0
Centimeters: 350000.0
Interviewer Expectations
The interviewer expects you to:
- Know how to take input (if required) and perform unit conversions using constants.
- Demonstrate proper use of data types, especially
doublefor precision. - Format your program clearly with logical variable naming and output structure.
Approach
To convert kilometers into different units:
- 1 kilometer = 1000 meters
- 1 kilometer = 100000 centimeters
- 1 kilometer = 0.621371 miles
Steps:
- Declare a variable to store distance in kilometers.
- Multiply it by the respective conversion factors to get other units.
- Print each result using
System.out.println().
Dry Run:
Input: 2.0 km
Calculations:
- Miles = 2.0 * 0.621371 = 1.242742
- Meters = 2.0 * 1000 = 2000
- Centimeters = 2.0 * 100000 = 200000
Output: Miles: 1.242742, Meters: 2000.0, Centimeters: 200000.0
Java Program
public class DistanceConverter {
public static void main(String[] args) {
double kilometers = 5.0;
double miles = kilometers * 0.621371;
double meters = kilometers * 1000;
double centimeters = kilometers * 100000;
System.out.println("Miles: " + miles);
System.out.println("Meters: " + meters);
System.out.println("Centimeters: " + centimeters);
}
}
Miles: 3.106855
Meters: 5000.0
Centimeters: 500000.0
Possible Followup Questions with Answers
Q1: How would you convert kilometers to feet and inches?
1 kilometer = 3280.84 feet, and 1 kilometer = 39370.1 inches. Use similar multiplication as we did earlier.
double feet = kilometers * 3280.84;
double inches = kilometers * 39370.1;
Q2: What if the input comes from the user?
You can use Scanner to take input from the user:
Scanner sc = new Scanner(System.in);
System.out.print("Enter kilometers: ");
double km = sc.nextDouble();
Q3: Why do we use double instead of int for these conversions?
Because many converted values (like miles or inches) are not whole numbers. Using double ensures accurate decimal values.
