(^70) | Java Syntax and Semantics, Classes, and Objects
In contrast,readLineis called from within an expression. Java supports two kinds of
methods: value-returning methodsand void methods. They are distinguished by how they
are called.readLine, a value-returning method, is called within an expression. When
it returns, a value that it has computed takes its place in the expression and can be
used for assignment or further computation.println, a void method, doesn’t re-
turn a value. We call it as a separate statement and, when it has finished, execution
picks up with the statement that follows it.
Interactive Input and Output
When an application inputs and outputs values that a human user supplies and
reads, it performs interactive input/output. To make the application more user-
friendly, the programmer has to consider additional information that the user
needs beyond the raw input and output. For example, the user must be prompted to enter
values; otherwise, he or she won’t know when or where to type the input. When the appli-
cation outputs its results, it must label them so that they are meaningful. Labeling output
also helps the user to distinguish among different values displayed by the application.
The following code segment inputs the three parts of a name, using System.out.printto
display a prompting message for each input value:
System.out.print(“Enter first name: “); // Prompt for first name
first = in.readLine(); // Get first name
System.out.print(“Enter last name: “); // Prompt for last name
last = in.readLine(); // Get last name
System.out.print(“Enter middle initial: “); // Prompt for middle initial
middle = in.readLine(); // Get middle initial
The next code segment outputs the name with System.out.println, using a label to in-
dicate what is displayed:
System.out.println(“You entered the name: “+
first + “ “+ middle + “. “+ last);
When an application outputs data that has just been entered, it confirms to the user that the
data was typed correctly or indicates that an error occurred. This kind of input–output se-
quence is known as echo printing.
2.2 Application Construction
So far in this chapter, we have looked at the basic elements of Java code: identifiers, decla-
rations, variables, constants, expressions, assignment statements, method calls, input, out-
put, and comments. Now let’s see how to collect these elements into an application. A Java
application is a class containing class declarations: fields and methods. For the class to be a
Java application, one of the methods must be namedmain. Execution of the Java application
begins in themainmethod.
Value-returning method A
method that is called from
within an expression and
returns a value that can be used
in the expression
Void method A method that is
called as a separate statement;
when it returns, processing con-
tinues with the next statement
T
E
A
M
F
L
Y
Team-Fly®