Suggested reading: sections 1.7, 1.9, 2.2-2.11

Elements of a Java Program

The basic working elements of a Java program are statements organized into methods, which are grouped into classes. A collection of classes make up a Java program.

Below is the source code for the simplest Java program: a program that prints a greeting message.

package hello;

public class Hello {

  public static void main(String[] args) {
    System.out.println("Hello, World!");
  }

}

Here are some things to notice about this program.

Using NetBeans to create this first program

We will be using the NetBeans development environment to write Java programs for this class. NetBeans provides a number of useful tools to help you write Java programs quickly.

To create a Java program in NetBeans, you will start by creating a project. A project is a collection of files needed to build a program.

To make your first project in Java, start up NetBeans and select New Project... from the File menu.

This brings up the New Project dialog box. NetBeans can create a wide variety of different projects, so the first step is to select an appropriate project type. Click the "Java with Ant" category in the category listing, and then click the "Java Application" project type. Click Next to move to the next dialog.

In this dialog you will specify a project name and a location for the project. For each project you create, NetBeans will make a project folder to hold the files for the project. Fill in the name "Hello" in the project name field. In the field below that you will specify a location for the project folder. By default, NetBeans will offer to place the project folder inside a NetBeansProjects folder in your home directory. If you want to put the project folder in a different location, you can click the Browse button to specify a different location.

Every project has to contain at least one package and one class inside that package. NetBeans names both the package and the class based on the project name. As soon as we set the project name to "Hello", NetBeans automatically creates a single package named "hello" and a single class named "Hello" inside that package.

Click Finish to finish setting up the project.

Once the project is set up, NetBeans will open an editor pane showing the source code for the Hello class.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package hello;

/**
 *
 * @author joe
 */
public class Hello {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
    }

}

This code has the same general structure as the code I showed above. Additionally, you will see some comments that NetBeans has inserted in the code. In programming, a comment is a block of text that is intended to be read by human readers: Java will ignore any text that appears in a comment. Java uses two styles of comment. The multiline comment start with the symbols /* and ends with the symbols */. As the name suggests, a multiline comment can span multiple lines. A single line comment starts with the symbols //. Java will ignore any text that appears after the // up to the end of the line.

Note the TODO comment inside the main method. This comment points out the fact that the main method currently does not have any code statements in it. To make this program actually do something, you should remove the TODO comment and replace it with the print statement shown here:

System.out.println("Hello, World!");

Now that the program is complete, you can run the program by selecting Run Project from the Run menu, or by clicking the triangular green run button in the tool bar. When the program runs you will see the message it prints in the output pane in the NetBeans window.

A second example

Here is a somewhat longer example program that we will be studying in greater detail later in these notes.

/* A first example program for CMSC 150 */
package fahrenheittocelsius;

import java.util.Scanner;

public class FahrenheitToCelsius {

  public static void main(String[] args) {
    // Set up a Scanner
    Scanner input = new Scanner(System.in);

    // Get input from the user
    System.out.print("Enter a temperature in Fahrenheit: ");
    float fahrenheit = input.nextFloat();

    // Convert Fahrenheit to Celsius
    float celsius = 5 * (fahrenheit - 32)/9;

    // Print output
    System.out.println("Fahrenheit " + fahrenheit + " is " +
      celsius + " in Celsius");
  }

}

If you would like to create a project to run this example program, follow the procedure shown above to make a new project named "FahrenheitToCelcius" and paste the source code above into the editor pane for the FahrenheitToCelsius.java source code file.

Variables

Computer programs exist to process and manipulate information. The basic unit of information in a Java program is the Java variable. Like a variable in mathematics, a Java variable represents a single item of data that can be manipulated. Unlike mathematical variables, which usually represent numerical quantities, Java variables can represent a wide array of different kinds of information, such as numbers, text, sounds, and even rich data such as feature length motion pictures.

The Java language requires that all variables be declared before being used. A variable declaration consists of a type and a variable name. The type specifies what kind of information this variable will hold, while the name identifies the variable. In the first few examples we see we will only be using three basic data types, the float, the int, and the String. The int is used to store integer values. The float is used to store floating point numbers. String variables are used to store text.

Here are two examples of simple variable declaration statements.

int x;
float y;

The first statement declares an integer variable named x, while the second declares a floating point variable named y.

Declaring a variable does not give it a value. To give a variable a value, you must initialize it with an assignment statement. This can be done in the same statement as the declaration or separately, as this example shows.

int x = 2;
float y;
y = 3.5;

You can also assign the value of one variable to another.

float pi = 3.14159;
float omega = pi;

String variables are typically initialized with text enclosed in double quotes.

String greeting;
greeting = "Hello, I am a String";

Arithmetic

You can use Java statements to do simple arithmetic. Here are some rules that govern the behavior of arithmetic in Java.

String Concatenation and Automatic Type Conversion

String variables are designed to hold text. The simplest way to create some text is to put some text in quotes. This works fine if you know exactly what you want the text to say. In many other cases you will not know in advance what the text should say and you will have to construct an appropriate text string at run time. The most common scenario in which this happens is when you want to display the value of a variable as the program runs. The example program above computes a Centigrade temperature value and stores that in the variable named cTemp. To display that numerical value, we have to have a method that will convert the number into text. Here is the Java code that does the conversion:

message = "68 degrees F = " + cTemp + " degrees C.";

Two things are happening in this statement. The first is that we are assembling some text by concatenation, or gluing together several pieces of text. Java uses the '+' operator to do text concatenation. One of the items we are concatenating here, cTemp, is a variable of type double containing a numerical value. Java does an automatic type conversion to convert the numerical data stored in the cTemp variable into text before doing the text concatenation. The end result here is that the String variable message ends up containing a block of text made up of the pieces specified here.

Text Output

For a program to be useful, it has to have some mechanism for displaying the results it computes. Java offers several mechanisms for displaying output. The simplest mechanism looks something like this:

System.out.println(message);

When this statement gets executed as the program runs in NetBeans, the text contained in the message variable will be displayed in the output pane at the bottom of the NetBeans window.

Getting input from the user

We saw in the first example program that when a program prints some output to System.out the text appears in an Output pane when the program runs. When a program needs to read input from the user, the program will also use the Output pane to read that input.

The usual procedure is to start by printing a special message called a prompt. The purpose of the prompt is to tell the user that the program now expects some input. In this program the prompt gets printed by the statement

System.out.print("Enter a temperature in Fahrenheit: ");

To read the requested input from the user, we make use of a Java object called a Scanner. The first step in using a Scanner is to create a Scanner object. The statement

Scanner input = new Scanner(System.in);

at the start of the main method does this. Scanners can be set up to read their input from text the user types or from a file. By specifying System.in as the source of the Scanner's data we are setting this Scanner up to read its input from the system input, which means to read input data from text the user types in the Output pane. This statement creates the Scanner object and stores a reference to that object in the variable input.

To read input from the user, we issue a command to the Scanner stored in the input variable:

float fahrenheit = input.nextFloat();

This statement does two things: it declares a variable named fahrenheit to store the input, and then it issues the nextFloat() command to the input object to ask the Scanner to read a float value that the user types.