CSC 153 Grinnell College Spring, 2005
 
Computer Science Fundamentals
Laboratory Exercise
 

An Introduction to Java

The Shift from Scheme to Java for CSC 153 Labs

Summary

This laboratory begins a transition from working with the Scheme programming language to Java. The lab first reviews a simple object-oriented program and test suite written in Scheme and then considers the direct translation of the program and testing to Java. The lab then considers details of compiling and running the Java program.

A Simple Course Class in Scheme

Consider a simple class that would maintain information about a course (e.g., CSC 153). Each object in the class might have the following characteristics:

Writing this course class requires some patience, but each method is reasonably straightforward. Program ~walker/public_html/courses/153.sp05/scheme/course.ss provides one implementation of such a class.

  1. Copy this program to your account, and load it into Scheme.

Testing of the course class might involve forming two objects (using the two construction options), retrieving the fields of the each object, modifying some fields, and printing the fields again.

  1. Test course.ss with the following sequence of commands:
    
    (define myCourse (course "CSC"  153  4  "CS Fundamentals"))
    (define yourCourse (course "Math"))
    
    ;; test of initialization, toString, and extractor methods
    (myCourse 'toString)
    (yourCourse 'getSubject)
    (yourCourse 'getNumber)
    (yourCourse 'getTitle)
    (yourCourse 'getCredits)
    
    ;; set fields
    (yourCourse 'setNumTitle 131 "Calculus I")
    (yourCourse 'setCredits 4)
    
    ;; print results of modification
    (yourCourse 'toString)
    


  2. Be sure you understand how this code works. In particular, you should be able to answer the following questions.

The Course Class in Java

The initial move from Scheme to Java requires at least four major adjustments:

In this lab, we address the last three of these major areas, considering the organization of classes into packages first, then reviewing a simple alternative for output, next describing steps to run a Java program, and finally starting an investigation of Java syntax and semantics. We accomplish the last three parts of this work in this lab; the discussion of Java syntax and semantics continues verbally in class and in the next lab.

Packages

Java groups related classes together into units, called packages. Within a Unix (or Linux) system, each package must have its own directory. Each class related to that package then is stored in a separate file within the package directory.

Directory Hierarchies

To illustrate a typical directory structure, consider the programs that will be used as examples for this course. The instructor's base directory for these examples ~walker/java/examples. That is, within my home directory ~walker, I have a subdirectory java where I put most or all of my Java programs. Within this java, programs are organized according to their uses. Sample programs for this course are located within an examples subdirectory.

The first example, class Course, is defined in a file, called Course.java, and this file is part of a package course. The names seem similar, although capitalization matters in both Unix/Linux and Java. The conventions are:

Thus, the initial directories and files for my copy of this program are organized into the following hierarchy:

my directory and file hierarchy for Course.java

The first part of this lab asks you to make a similar framework for your Java programs within your account, except that you likely will want to omit the "examples" directory. That is, subdirectory course will come directly under your java directory.

  1. To organize your forthcoming work in Java, open a terminal window, and create a new directory with the command
    
    mkdir java
    
    Now move to that directory with the command
    
    cd java
    
    Create new course and mathComputations subdirectories with the command
    
    mkdir course
    mkdir mathComputations
    
    Move to the course directory
    
    cd course
    
  2. Program ~walker/java/examples/course/Course.java provides a direct translation of course.ss to Java. Copy this file to your course subdirectory
.

The PrintWriter Class

Within Java, all work is done through the use of relevant classes and objects. In particular, an output class must be utilized to print material to the screen. In many applications, rather than write such a class ourselves, we utilize a class written by someone else. In this case, we will use a standard Java class PrintWriter.

Class PrintWriter has several useful methods for writing to the screen, including print to send material to the output device, and println to send material, with a newline character at the end.

The use of PrintWriter involves three main steps:

  1. import statement to tell Java that the program will reference this predefined Java class,
  2. Create an object (out in this example) of class PrintWriter, so there is an instance of this class available to do the actual work, and
  3. Use methods from out to perform the actual output; in this case print sends material to the output device, and println sends material, with a newline character at the end.

After the initial import and creation, the print and println methods may be used repeatedly as desired, without additional initialization.

  1. Examine program Course.java to find how this program implements each of these steps.

While we will look at Course.java shortly, we first consider how to run a Java program.

Compiling and Interpreting

As you may know, computers work with a number of different "languages". Each computer really understands only one language: its underlying machine language. We make computers understand another language by either

Already in this course, you have run Scheme programs, and these run using the second approach -- with a Scheme interpreter.

Java, however, uses an interesting combination of compilation and interpretation:

To compile and run Java programs, the first step in MathLAN is to tell the computers where to find the relevant Java compiler and interpreter. A second step is to tell the Java interpreter where to find your class libraries (it already knows about the pre-defined classes, but you need to include your own materials by setting a CLASSPATH variable in your account). This may be accomplished once and for all as follows:

  1. In your home directory, use an editor (e.g., emacs) to open the file .bashrc.

    This file is read whenever a process (e.g., a window) is started on these computers. Within this file, you probably will see several alias statements. These statements give easily used abbreviations for common commands, to make our work simpler.

  2. Immediately after any existing alias statements, add the following lines:
    
    # aliases for Java
      alias jcompile="/opt/jdk1.5.0/bin/javac"
      alias jrun="/opt/jdk1.5.0/bin/java"
    
    # set variable for Java class libraries
    export CLASSPATH="$CLASSPATH:/home/~yourUsername/java:.:/home/walker/java/examples"
    

    where you fill in yourUsername for MathLAN in the place shown. After editing, save your file.

The commands jcompile and jrun now will be defined for any new windows that are opened. (If you want to use these commands for windows already open, type the command


   source ~/.bashrc

at the prompt in the relevant window.)

Execution of Java programs now involves two steps:

We now use these commands to run the above test cases for Course.java.

  1. Use jcompile and jrun to compile and run the program Course.java

  2. Note that the two commands may be combined on one line with the statement:
    
    jcompile Course.java && jrun packageName.Course
    

    In this command, the connection && is read as a "conditional and". That is, the jcompile command is issued. Then, if the compilation proceeds without error, the jrun command is followed. However, if jcompile produces an error, then jrun is ignored.

The Course.java Program

Java programs may be edited with Emacs, in the same way you edit Scheme programs, labs, or other documents.

  1. Bring Course.java into your editor, so you can view it carefully.
    Also, print out a copy of course.ss.

  2. In comparing course.ss and Course.java, all field names and method names are exactly the same, and the methods do the same work in the same way. Try matching up elements of the two programs just by looking at the listings.

Either during the last part of today's class or in the next class, the class will talk about the parallels of the two courses, and the specific syntax and semantics of Java will be discussed at some length.


This document is available on the World Wide Web as

http://www.cs.grinnell.edu/~walker/courses/153.sp05/labs/lab-intro-java.shtml

created April 3, 2001
last revised March 24, 2005
Valid HTML 4.01! Valid CSS!
For more information, please contact Henry M. Walker at walker@cs.grinnell.edu.