Problem Solving and Computing (CSC-103 98S)

[Instructions] [Search] [Current] [Changes] [Syllabus] [Handouts] [Outlines] [Journal] [Problems] [Computing] [SamR Docs] [Tutorial] [API]


Computing Assignment 4: Introduction to Java

Purpose: In this assignment, you will attempt to enter and run your first Java programs. Hopefully, this well begin to get you accustomed to Java's syntax, compiler, and interpreter.

Warning: At times, Java is incredibly verbose. At other times, it is confusingly terse. Why do we do things the way we do? Because the designers decided that we whould. (I.e., "it's just the way things are").

Your First Program: Hello World

Many people begin working in a new programming language by writing a short program that prints the words "Hello World". Here's one such program, written in Java.



import rebelsky.io.SimpleOutput;

/**
 * A simple Java program that illustrates textual output.
 *
 * @author Samuel A. Rebelsky
 * @version 1.0 of January 1998
 */
public class HelloWorld 
{
  /**
   * Print the string "Hello world." to standard output.
   */
  public static void main(String[] args) 
  {
    // The object we're using to print output
    SimpleOutput out;
    // Set up output
    out = new SimpleOutput();
    // And print
    out.println("Hello world");
    // That's it
    System.exit(0);
  } // main
} // HelloWorld


 

Let's deconstruct this program.

import Statement

import rebelsky.io.SimpleOutput;
This tells the Java compiler that we'll be using a SimpleOutput object which is in the library rebelsky.io. As you might guess, this is a library that I've created.

Introduction

/**
 * A simple Java program that illustrates textual output.
 *
 * @author Samuel A. Rebelsky
 * @version 1.0 of January 1998
 */
This is a comment about the program. A comment is a note for the reader of the program (rather than for the computer). Java supports a variety of commenting styles. This is a javadoc comment. It begins with a slash and two stars and ends with a star and a slash. Every class should have a javadoc comment which consists of a few-sentence summary of the intent of the class, a blank line, and the author and version (as above).

Class Header

public class HelloWorld
This is the beginning of the real code. We're defining a class (more or less, a combination of functions and templates for objects) named HelloWorld that can be used anywhere (public).

Begin Class Definition

{
This brace begins the definition (code) for the class. You'll see a corresponding closing brace later.

Method Summary

  /**
   * Print the string "Hello world." to standard output.
   */
Another javadoc comment. Each method (function, algorithm) you create should have a javadoc comment.

Method Header

  public static void main(String[] args)
This is the start of a method (function, algorithm) definition. In particular, we're defining a method called main. Every Java program must have one main function that begins just like this. For now, we won't worry about why it looks like this, it just does. When you execute a Java program, execution begins at the start of your main method.

Begin Method Definition

  {
This open brace begins the definition of main. You'll see another one later.

Comment

    // The object we're using to print output
This is another comment. You can begin a comment with two slashes. The comment then ends at the end of the line. I'd recommend making it a point to comment add a note as to the purpose of every variable.

Variable Declaration

    SimpleOutput out;
This is a variable declaration. It says that out refers to an object of type SimpleOutput.

Object Creation and Assignment

    // Set up output
    out = new SimpleOutput();
Initially, variables have no values. This line (and associated comment) tells Java to create a new SimpleOutput object and associate it with the variable we've just declared. The default SimpleOutput object writes to the screen. Eventually, you'll learn how to write to files.

Output

    // And print
    out.println("Hello world");
This says to print the string "Hello World". More precisely, this says to call the println method of the out object we've just created, and to pass it the string "Hello World". Note that the ordering here is similar to that we'd use if we were talking to someone, as in "Sam, write 'Hello World' on the board."

Cleanup

    // That's it
    System.exit(0);
This tells the program to end, and notes that the program finished without errors (0 means "without errors"; other numbers mean "with some error"). This isn't strictly necessary. However, while you don't need to include a System.exit statement, I strongly recommend that you do.

End Method Definition

  } // main
This matches the brace that opened the body of main. The comment isn't strictly necessary, but it makes it easier to read the proram. I'd recommend making it a point to comment every end brace to indicate what you are ending.

End Class Definition

} // HelloWorld
This matches the brace that opened the definition of HelloWorld. Again, the comment isn't strictly necessary, but it makes the program more readable.

Running The Program

Now, you're ready to create and run your first Java program. Copy the code from above and save the program as HelloWorld.java. Capitalization is important! You can cut and paste to copy the program, or you can retype it by hand. You may even want to do both (first copy and paste; then retype) as you'll learn different things from the different procedures. To copy and paste, select the text with the left mouse button, then move to your emacs window and click with them middle mouse button. Isn't that intuitive?

Next, you need to compile it. Use
% /home/rebelsky/bin/jc HelloWorld.java
(don't type the percent sign). If you've mistyped something, you may see an error. Let me know, and we'll fix the error together.

Finally, you can run the program. Type
% /home/rebelsky/bin/ji HelloWorld

Once you've gotten the program to run, try changing the message that it prints and recompiling. To do this, you'll need to open the program from within Xemacs (which you should remember how to do from a previous assignment), change the appropriate line, and save.

Your Second Program: Greetings

We've seen how to print output and a sketch of the overall structure of a simple Java program. Now, let's move on to one that also reads input.



import rebelsky.io.SimpleInput;
import rebelsky.io.SimpleOutput;

/**
 * A simple Java program that illustrates textual input and output.
 *
 * @author Samuel A. Rebelsky
 * @version 1.0 of January 1998
 */
public class Welcome
{
  /**
   * Prompt for the user's name and print a greeting.
   */
  public static void main(String[] args) 
  {
    // The object we're using to read input.
    SimpleInput in;
    // The object we're using to print output.
    SimpleOutput out;
    // The user's name.
    String name;
    // Set up input and output.
    in = new SimpleInput();
    out = new SimpleOutput();
    // Prompt for the name.
    out.print("What is your name? ");
    // Get the name.
    name = in.readLine();
    // Print a friendly message.
    out.println("Hello " + name + ", welcome to the joy of Java.");
    // That's it
    System.exit(0);
  } // main
} // Welcome



Again, we'll look at it, line by line (or at least chunk by chunk).

import Statements

import rebelsky.io.SimpleInput;
import rebelsky.io.SimpleOutput;
Here, we indicate that we're using two differt library objects, both from the rebelsky.io library. The first does simple input; the second does simple output.

Introductory Material

/**
 * A simple Java program that illustrates textual input and output.
 *
 * @author Samuel A. Rebelsky
 * @version 1.0 of January 1998
 */
public class Welcome
{
Again, we have a javadoc comment that describes the program and lists author and version. Then, we have a class header, indicating that the class name is Welcome. Finally, we have an open brace that begins the class.

Introduce main

  /**
   * Prompt for the user's name and print a greeting.
   */
  public static void main(String[] args)
  {
For simple programs, we always need this main() method. We begin with a javadoc comment describing the purpose of the method. Then we have the method header, which gives the name and some related information (for now, assume "that's just how they do it"; we'll look at detail later). Finally, we have an open brace to begin the definition.

Variables

    // The object we're using to read input.
    SimpleInput in;
    // The object we're using to print output.
    SimpleOutput out;
    // The user's name.
    String name;
This time, we have three variables. One will be used for reading input, one for writing output, and one to store the user's name (since we're reading the user's name, we need to store it somewhere). Note that I was able to use the type String without importing it. This is because strings are built into Java.

Initialization

    // Set up input and output.
    in = new SimpleInput();
    out = new SimpleOutput();

Prompt

    // Prompt for the name.
    out.print("What is your name? ");
Note that SimpleOutput permits you to use both println (which includes a carriage return) and print (which does not include a carriage return).

Input

    // Get the name.
    name = in.readLine();
SimpleInput provides a number of methods for reading values. The simplest is readLine, which reads and returns one line of text.

Output // Print a friendly message. out.println("Hello " + name + ", welcome to the joy of Java.");

Again, we print with println. Note that we can concatenate (join) strings by using a plus sign. If you're not sure what this code will do, try running the program.

Cleanup

    // That's it
    System.exit(0);
  } // main
} // Welcome

Running The Program

You're now ready to create and run thisJava program. Copy the code from above and save the program as Welcome.java. You can cut and paste to copy the program, or you can retype it by hand (at this point, I'd recommend retyping).

Compile and run the code to make sure that it works. Check with me if you get error messages.

Next, rename the program (to anything you'd like) and extend it to ask for an use two pieces of information (e.g., name and major). Note that you will have to rename your class to correspond to the name of the file.

It is likely that you will make some small errors. This is fine. Just let me know and we'll work on fixing them.

Your Third Program: Computing a Square

As our last exercise, let's work on some programs that read and write numbers. Our basic program will prompt for a number and print the square of that number.



import rebelsky.io.SimpleInput;
import rebelsky.io.SimpleOutput;

/**
 * A simple Java program that illustrates numeric input and output.
 *
 * @author Samuel A. Rebelsky
 * @version 1.0 of January 1998
 */
public class Square
{
  /**
   * Prompt for a number and print the square of the number.
   */
  public static void main(String[] args) 
  {
    // The object we're using to read input.
    SimpleInput in;
    // The object we're using to print output.
    SimpleOutput out;
    // The value entered.
    double val;
    // Set up input and output.
    in = new SimpleInput();
    out = new SimpleOutput();
    // Prompt for the value.
    out.print("Please enter a value and I will square it: ");
    // Get the name.
    val = in.readDouble();
    // Print a friendly message.
    out.println(val + " squared is " + val*val);
    // That's it
    System.exit(0);
  } // main
} // Square



This time, we'll only look at the "new" lines (the ones that differ significantly from those in previous programs).

Numeric Variables

    double val;
You declare numeric variables by writing the keyword double and the name of the variable.

Numeric Input

    val = in.readDouble();
SimpleInput also supports a readDouble method that reads a number. You may want to test what happens if we enter something other than a number.

Output and Computation

    out.println(val + " squared is " + val*val);
This line illustrates one of the oddities of Java (or comes close to illustrating one of those oddities). The meaning of some symbols is context-dependent. Usually, we think of the plus sign as being used to add two numbers. However, it can also be used to join strings. In this case, it is being used for the latter purpose. Note also that Java can automatically convert numbers to strings.

Running The Program

Again, try copying, compiling, and running this program. You may want to see what happens if you enter something other than a number, a very large number, or a very small number.

Building Your Own Program

Reflect on the previous programs and see if you can design a program that converts Centigrade to Fahrenheit. Use the conversion formula

F = C * (9/5) + 32

Work on your design on paper, rather than on the computer! Experience shows that we do much better when we think on paper and primarily transcribe on the computer.

More Testing

Try variants of the program. Try changing spacing, the value you're computing, names, or whatever. Observe what you learn from that testing.


[Instructions] [Search] [Current] [Changes] [Syllabus] [Handouts] [Outlines] [Journal] [Problems] [Computing] [SamR Docs] [Tutorial] [API]

Disclaimer Often, these pages were created "on the fly" with little, if any, proofreading. Any or all of the information on the pages may be incorrect. Please contact me if you notice errors.

Source text last modified Tue Feb 10 13:41:43 1998.

This page generated on Thu Apr 2 13:49:54 1998 by SiteWeaver.

Contact our webmaster at rebelsky@math.grin.edu