CS 214 Lab 1: Introductory Java Exercise


Today's exercise is to write our first Java, Ada, Clojure, and Ruby programs, and compare their implementations.

Getting Organized

It always helps to be organized, so begin by creating a 214 directory to hold your work for this course. Then create a labs subdirectory to hold the files you create during lab exercises; and within labs , create a subdirectory named 01 to hold the files you create during this exercise.

Text Editors

The source files for all four of our languages are text files, so they can (in theory) be created using any text editor. The files for this exercise were created using the vim text editor, which stands for vi improved. (vi is the visual editor that comes standard on all Unix-family operating systems; vim is a modern version of it, and on many systems, vi is just an alias for vim.)

If you have not used vi/vim before, here are two tips to using it:

  1. The vi/vim editor has two modes: When it starts up, vi/vim is in navigation mode.

    There are a variety of ways to switch from navigation mode to insert mode. The simplest is to press the i key (for insert).

    To switch from insert mode back to navigation mode, press the 'ESC' (Escape) key.

  2. When you are done editing, there are a variety of ways to quit vi/vim, all of which require you to be in navigation mode;
    1. Type ZZ (capital Z twice)..
    2. Enter :wq (colon, w (for write) and q (for quit).
    Either of these should return you to the command-line in your terminal/console window. You can also enter :w to write (i.e., save) the changes you have made without quitting.

If you are not familiar with vi/vim and want to use it in this course, you may want to bookmark or print a copy of one of this one-page Vim Cheatsheet for future reference.

Our First Java Program

Java source files should always be named with the name of the class they contain (case-sensitive), followed by the .java suffix. By convention, Java class names begin with an uppercase letter and use camel case.

Since our program is to calculate the area of a circle, we want to create and edit a file named CircleArea.java. From the commandline within your terminal window, make certain you are in your 214/labs/01 folder and enter:

   vim CircleArea.java
which will create the file CircleArea.java within that folder.

In that file, copy-paste the following Java source program:

/* CircleArea.java computes the area of a circle.
 *
 * Input: The radius of the circle.
 * Precondition: The radius is a positive number.
 * Output: The area of the circle.
 *
 * Begun by: Dr. Adams, for CS 214, at Calvin College.
 * Completed by:
 * Date:
 **********************************************************/


import java.util.Scanner;  // include class for Scanner

public class CircleArea {

     /* function circleArea() computes a circle's area, given its radius.
      * Parameter: r, a double
      * Precondition: r is not negative.
      * Returns: the area of the circle
      */
     public static double circleArea(double r) {
        return Math.PI * r * r;               // return an expression
     } // circleArea method
	
  // main program
  public static void main(String[] args) {
      // prompt for radius
      System.out.println("\n\nTo compute the area of a circle,");
      System.out.print(" enter its radius: ");

      // Create a connection named keyboard to standard in
      Scanner keyboard = new Scanner(System.in);

      //Get the number from the user
      double radius = keyboard.nextDouble();

      // output area
      System.out.println("\nThe area is " + circleArea(radius) + "\n");
      System.out.printf("The area is %f\n\n", circleArea(radius));
      System.out.printf("The area is %.15f\n\n", circleArea(radius));
  } // main method

} // class CircleArea

Using your text editor commands, customize the opening documentation with your name and today's date.

Note that Java uses /* and */ pairs to mark the beginning and end of multi-line comments, and // to indicate the beginning of an inline comment, which ends at the end of that line.

Take a few minutes to study the Java code and see how it implements our algorithm for computing the area of a circle.

When you understand the purpose of each Java statement in performing the algorithm, save the file and quit from your text editor. In vi/vim, you can do this by entering navigation mode and typing ZZ. This will return you to the commandline in your terminal window.

Compiling a Java Program

To run our Java program we must first compile our source file. Rather than compiling all the way to executable machine code (as happens when you compile Ada, C, or C++), Java code is instead compiled to an intermediate form called Java Virtual Machine (JVM) byte code. The JVM then takes the byte code and generates machine code which is actually run.

To compile our program, we will use the Java compiler javac. From the command line, javac can be used to compile an arbitrary Java program stored in SourceFileName.java and place the resulting byte code in SourecFileName.class with the following command:

   javac -deprecation SourceFileName.java
(The -deprecation switch will notify you if your program is using any language features of Java that have been deprecated, or planned to be unsupported in the near future. You generally want to avoid using any features the compiler identifies as deprecated.)

Using the above command as a template, use javac to compile your file CircleArea.java. Continue when it has compiled succesfully.

Running a Java Program

When your program compiles successfully, you can run it from the command-line by asking the java runtime environment (called java) to execute the byte code you created when you compiled it:

   java SourceFileName

Note that you do not include the extension .class!

Use the above command as a template to run your CircleArea program, and continue when it begins running succesfully.

Testing

Test your program using the following data values, recording the program's output for these values:


   1

   2

   2.5

   4.99999
Note that when your program terminates and prints its results, you can use your keyboard's up-arrow to repeat the previous command (and so avoid wasting time retyping that command).

How do Java's print, println and printf methods differ from one another?

When a real number is printed using printf, how can you control the number of decimal places being displayed?

Wrapping Up

Use the program script to capture your program and its execution, by following these steps:

  1. Enter script script.java to start the script program.
  2. Enter cat CircleArea.java to display your source program.
  3. Enter javac -deprecation CircleArea.java to compile your program and show there are no errors.
  4. Enter java CircleArea to run your program (entering the values given above).
  5. Enter exit or type Cntl-d (hold down Cntrl key and press d) to terminate the script program.
The script program will record everything that appears on-screen, saving it in the text file script.java. At the end of the exercise, you can print this file the same as you would any other text file.

Return to the lab 1 page to complete the other parts of this exercise.


Calvin > CS > 214 > Labs > 01 > Java


This page maintained by Joel Adams.