Experiments in Java


Session J1: An Introduction to Java

A hello world program

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 SimpleOutput;

/**
 * A simple Java program that illustrates textual output.
 *
 * @author Samuel A. Rebelsky
 * @version 1.1 of March 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 = new SimpleOutput();
    // And print
    out.println("Hello world");
  } // main(String[])
} // class HelloWorld


Let's examine the pieces of this program.

The import statement


import SimpleOutput;


This statement tells the Java compiler that we'll be using one or more SimpleOutput objects to support our program. The name of that class suggests that we will be using the objects to print output (to the screen or elsewhere).

Introduction


/**
 * A simple Java program that illustrates textual output.
 * <p>
 * Copyright (c) 1998 Addison Wesley Longman.  All rights reserved.
 *
 * @author Samuel A. Rebelsky
 * @version 1.1 of March 1998
 */


These lines are 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. The preceding comment is an introductory one. Every introductory comment begins with a slash and two stars and ends with a star and a slash. Every class should have an introductory comment that 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 {


The class header begins the real code. We're defining a class named HelloWorld that can be used anywhere (because it is public). The left curly brace begins the definition (or code) for the class. You'll see a corresponding closing brace later.

What is a class? The notion of ``class'' is one of the central components of object-oriented programming, and classes are used for many purposes. Classes serve as templates to guide the creation of objects. Classes gather methods that provide functionality for objects. Classes can suggest or limit usage.

In this case, the HelloWorld class is used to gather methods. In particular, it has a single method, called ``main''.

Method summary


  /**
   * Print the string "Hello world" to standard output.
   */


This method summary is another introductory comment. Each component of a program or class (you'll learn more about these components and classes later) should have an introductory comment.

Method header


  public static void main(String[] args) {


This header starts a method (also known as a function or procedure) 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. The curly brace begins the code for the main method.

Comment


    // The object we're using to print output.


This line shows another way to comment. The earlier comments began with a slash and a star and ended with a star and slash. You can also begin a comment with two slashes and end it with the end of the line. Generally, you use the slash-star comments for longer descriptions (outside of components and classes) and the double-slash comments for shorter descriptions (usually for a few lines of code).

This particular comment indicates that the following line creates and names an object that we'll be using to print output.

Variable declaration and creation


    SimpleOutput out = new SimpleOutput();


This variable declaration says that out refers to a new object of type SimpleOutput. SimpleOutput objects provide mechanisms for writing to the screen.

Output


    // And print
    out.println("Hello world");


This line says to print the string "Hello World". More precisely, we use this line 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''.

End of method definition


  } // main(String[])


This line matches the brace that opened the body of main. For every opening brace you write, you'll need a corresponding closing brace. The comment isn't strictly necessary, but it makes it easier to read the program. I'd recommend making it a point to comment every end brace to indicate what you are ending.

End of class definition


} // HelloWorld


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

Compilation

Computers typically cannot execute programs written in source text (such as the Java program above). Before being executed, these programs must be translated or compiled into a form the computer can better understand. Hence, you will need to execute the Java compiler to translate any Java program to an executable form. The executable form of a Java program is called a ``class'' file and has the suffix .class. For example, if I compile the program HelloWorld.java, the compiled program will be called HelloWorld.class.

Java differs from many languages in what you do with the translated program. Typically, programs are compiled to machine code, which the computer can then execute directly. In Java, programs are compiled to Java machine code, which ``Java machines'' can execute directly. Most computers cannot directly execute such code. Hence, you must run a Java machine simulator (also known as an interpreter) to execute your Java programs. Why the difference? Because Java provides many features (typically having to do with security) that typical machines do not provide directly.

In Experiment J1.1 you will execute HelloWorld and consider some principal issues in Java development. In Experiment J1.2 you will extend HelloWorld.

Reading input

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 SimpleInput;
import SimpleOutput;

/**
 * A simple Java program that illustrates textual input and output.
 *
 * @author Samuel A. Rebelsky
 * @version 1.1 of March 1998
 */
public class Greetings {
  /**
   * 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 = new SimpleInput();
    // The object we're using to print output.
    SimpleOutput out = new SimpleOutput();
    // The user's name.
    String name;
    // Prompt for the name.
    out.print("What is your name? ");
    // Get the name.
    name = in.readString();
    // Print a friendly message.
    out.print("Hello ");
    out.print(name);
    out.println(", welcome to the joys of Java.");
  } // main(String[])
} // Welcome


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

import statements


import SimpleInput;
import SimpleOutput;


Here, we indicate that we're using two different library objects. The first does simple input; the second does simple output.

Introductory material


/**
 * A simple Java program that illustrates textual input and output.
 * <p>
 * Copyright (c) 1998 Samuel A. Rebelsky.  All rights reserved.
 *
 * @author Samuel A. Rebelsky
 * @version 1.1 of March 1998
 */
public class Greetings {


Again, we begin with an introductory comment that describes the program and lists author and version. Next is a class header, indicating that the class is named Greeting. 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) {


We begin with an introductory comment describing the purpose of the method. Then we have the method header, which gives the name and some related information. Finally, we have an open brace to begin the definition.

While methods can have many names, the name ``main'' has particular meaning to Java. In fact, the main method is the core of any Java application. Java uses the main method as the starting place for the program.

You may be wondering about the other parts of the method declaration (the public, static, and such). Unfortunately, at this stage of your career, you are best served by accepting that this code is just how you indicate the start of your program. For those of you who can't wait for more explanation, you can find a basic explanation in the notes at the end of this section.

Object declarations and initialization


    // The object we're using to read input.
    SimpleInput in = new SimpleInput();
    // The object we're using to print output.
    SimpleOutput out = new SimpleOutput();
    // The user's name.
    String name;


This time, we have three named objects. 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).

String is a special type of class, used to describe collections of letters and numbers. Strings appear regularly in Java programs. For example, "Hello world" is a string (with eleven characters). When you deal with textual input and output, you will need strings. Note that we were able to use the type String without importing it. This is because strings are built into Java. Note also that we did not use new to create a new String object. This is because we will be getting a string later in the program, and the method we use to get the string will create the new string.

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.readString();


SimpleInput provides a number of methods for reading values. The simplest is readString, which reads and returns one line of text.

Output


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


Again, we print with print and println.

Cleanup


  } // main(String[])
} // Welcome


As before, we need to close the definitions of main and the complete class.

In Experiment J1.4, you will execute Greetings and learn about some of the ways that programmers inadvertently break programs. In Experiment J1.4, you will extend Greetings to read and print additional information.

Concatenating strings

As you may have noted from the prior example, it can become tedious to print a sequence of outputs. In that example, we needed separate calls to the println method for the greeting, the name, and the welcome. It would be useful to be able to print all three with one statement. Fortunately, Java permits you to concatenate (join) strings together with the plus (+) operation. For example, I could rewrite the three lines above as

    out.println("Hello " + name + ", welcome to the joys of Java.");

Variables

When programming, it is often necessary to store and name values temporarily. In most languages (including Java), we need to create a storage cell for the value, name that storage cell, and store and retrieve values. Such storage cells are typically called variables.

In Java, all variables are typed. That is, you must describe what type of values are stored within the variables. You might store numbers, strings, or even objects. In our first program we needed to work with an object of type SimpleOutput, so we created a variable called out of that type. In subsequent programs, you will create variables of other types.

Note that we can get the value stored in a variable by using the name of the variable and we can store values in variables by writing the name of the variable, an equals sign, and an expression. For example, we can declare alpha and beta to be string variables with

    String alpha;
    String beta;

We can assign the string "Java" to alpha with

    alpha = "Java";

We can assign two copies of alpha to beta with

    beta = alpha + alpha;

Numeric input and output

Our previous programs worked with text. A great deal of computation uses numbers instead of text. Let's move on to some programs that read and write numbers. Our basic program will prompt for a number and print the square of that number.


import SimpleInput;
import SimpleOutput;

/**
 * A simple Java program that illustrates numeric input and output.
 *
 * @author Samuel A. Rebelsky
 * @version 1.1 of March 1998
 */
public class BasicComputations
{
  /**
   * 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 = new SimpleInput();
    // The object we're using to print output.
    SimpleOutput out = new SimpleOutput();
    // The value entered.
    double val;

    // 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));
  } // main
} // class BasicComputations


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 which says that val is a variable that stores numbers. You will soon discover that double variables store numbers that include a fractional portion (e.g., 3.5 and 1.2). If you only want to store integers (numbers without a fractional portion; some people call these whole numbers), you can use int.

Numeric input

    val = in.readDouble();

SimpleInput also supports a readDouble method that reads a number. This line says to read a number and store that number in val. If you want to read in integer, you can use readInt.

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, as we've already seen, it can also be used to join strings. In this case, it is being used for the latter purpose. Surprisingly, when you add a string and a number, Java automatically converts the number to a string and adds as if they were both strings.

In Experiment J1.5 you will explore numeric input and output, as well as some simple numeric computation.

Applets

This section is optional and is intended for classes emphasizing applets or pursuing a simultaneous discussion of applications and applets.

In addition to supporting the standard application model of programming, Java also supports a variant model, known as the applet model. Applets are programs that are designed to be run within other programs. Most often, applets are graphical programs that run within Web pages. In the first lab session, you may have experimented with applets that drew pictures on the screen or animated balls or balloons. In this session, we'll focus on the static applets.

Interestingly, the structure of an applet differs from that of an application. In particular, applets typically do not contain constructors or a main method. You also declare applets in a somewhat different way than you declare applications.

The following is a small Java applet that prints the words ``Hello World''.


import java.applet.Applet;
import java.awt.Graphics;

/**
 * A simple Java applet that illustrates textual output.
 *
 * @author Samuel A. Rebelsky
 * @version 1.0 of June 1999
 */
public class HelloWorldApplet
  extends Applet
{
  /**
   * Print/draw the string "Hello world".
   */
  public void paint(Graphics paintBrush) {
    paintBrush.drawString("Hello world", 10, 20);
  } // paint(Graphics)
} // class HelloWorldApplet


You might include this applet in a Web page as follows.

<html>
  <head>
    <title>A Sample Applet</title>
  </head>
  <body>
    <applet code="HelloWorldApplet.class" width="400" height="300">
    </applet>
  </body>
</html>

As you may have noticed, many things set HelloWorldApplet.java apart from our HelloWorld.java application:

Let's consider these differences. We begin by noting the way in which Web browsers and other things that run applets operate.

We are now ready to look at the individual parts.

Imported classes

import java.applet.Applet;
import java.awt.Graphics;

These statements tell Java that you will be using two helper classes. One, called Applet, is part of the standard Java distribution (specified by java.) and is one of the applet classes (specified by applet.). The other, called Graphics, is also part of the standard Java distribution, and is one of the abstract windowing toolkit classes (specified by awt.).

Class header

public class HelloWorldApplet
  extends Applet

This class header looks a lot like our other class declarations, but adds the ``extends Applet''. This new phrase tells Java that your new class is an applet rather than an application. Whenever you write an applet, you need to include this phrase.

Method header

  public void paint(Graphics paintBrush) {

Many applets paint/draw pictures on the screen. They know when to do so because the browser calls their paint method. They use a Graphics object (which we call paintBrush) to do the actual painting.

Method body

    paintBrush.drawString("Hello world", 10, 20);

This statement tells the the Graphics object to draw the string "Hello world" ten units from the left of the applet's drawing area, and twenty units from the top of the applet's drawing area.

HTML code

    <applet code="HelloWorldApplet.class" width="400" height="300">
    </applet>

This HTML tag tells the browser to load the applet named HelloWorldApplet, which is stored in the file HelloWorldApplet.class. The tag gives the applet a space in the Web page with a width of four-hundred units and a height of 300-hundred units.

We have neither time nor space here to introduce HTML, the Hypertext Markup Language used for the World-Wide Web. You can use the document above as a template and experiment on your own.

In Experiment J1.6, you will begin your exploration of applets. In Experiment J1.7, you will explore some of the things that can go wrong when you use applets.


Copyright (c) 1998 Samuel A. Rebelsky. All rights reserved.

Source text last modified Tue Oct 26 12:49:45 1999.

This page generated on Tue Oct 26 15:38:30 1999 by Siteweaver.

Contact our webmaster at rebelsky@math.grin.edu