CH3 – Literals and Constants

  1. Open InchesToCentimeters.java and add the following to the line just below the two static variables.
final static double CM_PER_INCH = 2.54;
  1. Replace the number 2.54 with CM_PER_INCH.
cm = inch * CM_PER_INCH;
  1. Save, compile and run the program.
$ java InchesToCentimeters
How many inches? 10
10 in =25.4 cm

The complete program should appear as follows.

import java.util.Scanner;
public class InchesToCentimeters {
  static int inch;
  static double cm;
  final static double CM_PER_INCH = 2.54;

  public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    System.out.print("How many inches? ");
    InchesToCentimeters.inch = in.nextInt();
    cm = inch * CM_PER_INCH;
    System.out.print(inch + " in =");
    System.out.println(cm + " cm");
  }
}

There are no written rules for constants. Lowercase, uppercase, it doesn’t matter, it will compile. However, convention dictates that variables intended as constants are to be uppercase. Moreover, constants with multiple words are separated by underscores.