Java Reference
In-Depth Information
concerned with the details of this program. You only need to understand the effect of an
output statement, which is introduced in the program.
Consider the following Java (application) program:
//********************************************************
// This is a simple Java program. It displays three lines
// of text, including the sum of two numbers.
//********************************************************
2
public class ASimpleJavaProgram
{
public static void main(String[] args)
{
System.out.println("My first Java program.");
System.out.println("The sum of 2 and 3 = " + 5);
System.out.println("7 + 8 = " + (7 + 8));
}
}
Sample Run: (When you compile and execute this program, the following three lines
are displayed on the screen.)
My first Java program.
The sum of 2 and 3 = 5
7 + 8 = 15
This output is displayed on the screen when the following three lines are executed:
System.out.println("My first Java program.");
System.out.println("The sum of 2 and 3 = " + 5);
System.out.println("7 + 8 = " + (7 + 8));
To explain how this happens, let's first consider the statement:
System.out.println("My first Java program.");
This is an example of a Java output statement. It causes the program to evaluate whatever
is in the parentheses and display the result on the screen. Typically, anything in double
quotation marks, called a string, evaluates to itself, that is, its value is the string itself.
Therefore, the statement causes the system to display the following line on the screen:
My first Java program.
(In general, when a string is printed, it is printed without the double quotation marks.)
Now let's consider the statement:
System.out.println("The sum of 2 and 3 = " + 5);
In this output statement, the parentheses contain the string "The sum of 2 and 3 = " , +
(the plus sign), and the number 5 . Here the symbol + is used to concatenate (join) the
operands. In this case, the system automatically converts the number 5 into a string, joins
that string with the first string, and displays the following line on the screen:
The sum of 2 and 3 = 5
Search WWH ::




Custom Search