Java program to convert centimeter to inch, meter and kilometer

Quick links 

Write a Java program to input centimeter and convert to inch, meter and kilometer. How to convert centimeter to inch, meter and kilometer in Java programming.

Example
Input 

Enter centimeter : 12.5

Output

12.5 cm is equal to 4.925 inch.
12.5 cm is equal to 0.125 meter.
12.5 cm is equal to 4.925 kilometer.

Required knowledge

Basic Input/Output, Arithmetic operators

Logic to convert centimeter to inch, meter and kilometer

Step-by-step explanation of how can we convert centimeter to inch, meter and kilometer.

  1. Let us first establish relation between centimeter, inch, meter and kilometer.
    1 cm = 0.394 inch
    1 cm = 0.01 meter
    1 cm = 0.00001 kilometer
  2. After you know how many inches, meters and kilometers are there in 1 centimeter. You can easily find total inches, meters and kilometers in centimeter. To get desired result, multiply given centimeter to inches/meters/kilometers in 1 centimeter.
    Example: 

    10 cm = 10 * 0.394 inches
          = 3.94 inches
    10 cm = 10 * 0.01 m
          = 0.1 m
    10 cm = 10 * 0.00001
          = 0.0001 km

Program to convert centimeter to inch, meter and kilometer

/**
 * Java program to convert centimeter to inch, meter and kilometer.
 */
import java.util.Scanner;

public class MeasurementConversion {

    public static void main(String[] args) {

        /*
         * Constants for inch, meter and kilometer in 1 centimeter.
         */
        final double INCH       = 0.394;
        final double METER      = 0.01;
        final double KILOMETER  = 0.00001;
 
        Scanner in = new Scanner(System.in);
        
        /* Read centimeter input from user */
        System.out.print("Enter length in centimeters : ");
        double cm = in.nextDouble();
        

        /* Convert cm into inch, m and km */
        double inch = cm * INCH;
        double m    = cm * METER;
        double km   = cm * KILOMETER;
        
        
        /* Print result on console */
        System.out.println(cm + " cm is equal to " + inch + " inches.");
        System.out.println(cm + " cm is equal to " + m    + " meters.");
        System.out.println(cm + " cm is equal to " + km + " kilometers.");
    }
}
 

Output

 
 
 
Enter length in centimeters : 12.5
12.5 cm is equal to 4.925 inches.
12.5 cm is equal to 0.125 meters.
12.5 cm is equal to 4.925 kilometers.

Happy coding 😉