A Simple Java Program

In this web page, the Addition.java program from the book (Figure 2.7) will be described. The following project file contains this program and other examples from chapter 2 and can be imported into Eclipse. The line numbers referred to below can be found on this pdf file.

Line 1: This is an import declaration. This tells the compiler that this program uses the Scanner class from the java.util package. Java's API (Application Programmer Interface) includes a very large and very useful set of predefined classes organized into several packages.

Lines 3-8: The comments from the original code were turned into a Javadoc comment for the class. A Javadoc comment starts with /** and ends with */. A Javadoc comment documents the class or method that immediately follows it.

Line 10: This is a class declaration. The name of the program is Addition, which will contained in a file named Addition.java. The code for the class is within the matching braces.

Lines 11-13: This comment from the original code was turned into a Javadoc comment for the main method. When Javadoc is run on this class, it produces a file named Addition.html. The full documentation describes other programs from Chapter 2 of the textbook, with some comments converted to Javadoc comments. To view the html file in Eclipse, right-click on on the file, then:
Open With -> Web Browser

Line 14: This declares the main method. When a Java program is run, the program starts by executing the main method. The code for the main method is within the matching braces.

Line 16: This assignment statement declares and initializes a variable with name input and type Scanner. The variable is initialized to a new Scanner object for reading data from standard input.

Lines 18-20: These statements declare three variables of type int named number1, number2, and sum. They are not initialized.

Lines 22-23: A prompt is printed on standard output, then an assignment statement stores a value in number1; this value is an int read from the Scanner. In more detail, input.nextInt() reads the next token on standard input, converts the token to an int, and returns the int. If the token cannot be converted to an int, a runtime error occurs.

Lines 25-26: This is a similar sequence for number2.

Line 28: This stores the value of number1 + number2 in sum.

Line 30: This prints data to standard output. The data includes the value of sum.

Variables

A variable is a location to store a value. The term variable simply means that an assignment statement can change the value that is stored. Any Java variable has the following properties:

An assignment statement stores a value in a variable. Despite the way it looks, an assignment statement is not an equation to be solved. Inserting a statement like:

number1 = 42;
at line 29 will not magically change sum.