CH3 – Centimeters to Inches

  1. Create a new file named CentToInch.java and add the following code.
public class CenToInch{
  public final static double CM_PER_INCH = 2.50;
  public static void main(String[] args){
    double cm = Double.parseDouble(args[0]);
    double pi = 3.14159;
    double x = (int)pi * 20.0;
    System.out.println(x);
  }
}
  1. Save, compile, and run the program. Don’t forget to pass a parameter.
$ javac CenToInch.java
$ java CenToInch 5
60.0
  1. Open the file and add the following two lines of code below the last line in the main method.
int inch = (int)(cm/CM_PER_INCH);
System.out.printf("%f cm = %d in\n", cm, inch);
  1. Save, compile, and run the program.
$ javac CenToInch.java
$ java CenToInch 5
60.0
5.000000 cm = 2 in

Note that here you are casting a double to an integer.

(int) pi

There are two types of casting – widening and narrowing. When widening, you are going from simple to more complex. When widening you are not required to cast the variable. The following conversions do not require casting.

  • byte to short, int, long, float, or double
  • short to int, long, float, or double
  • char to int, long, float, or double
  • int to long, float, or double
  • long to float or double
  • float to double

Narrowing, in contrast requires explicit casting or an error is generated by the compiler. The reason for this is because you loose precision. For example, suppose you cast a double of value 33.33333 to an int. An integer cannot store decimal numbers and so you loose precision when the number is truncated to 33. By casting you are “reassuring” the compiler you intended this narrowing. The following require explicit casting.

  • byte to a char
  • short to a byte or a char
  • char to a byte or a short
  • int to a byte, a short, or a char
  • long to a byte, a short, a char, or an int
  • float to a byte, a short, a char, an int, or a long
  • double to a byte, a short, a char, an int, a long, or a float