Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

18 HOUR 2:Writing Your First Program


Displaying the Contents of a Variable
If you run the program at this point, it wouldn’t display anything. The
command to store a line of text in the greetingvariable occurs behind the
scenes. To make the computer show that it is doing something, you can
display the contents of that variable.
Insertanother blank line in the Salutonprogram after the String greeting
= “Saluton mondo!”statement. Use that empty space to enter the following
statement:
System.out.println(greeting);

This statement tells the computer to display the value stored in the greet-
ingvariable. The System.out.printlnstatement tells the computer to dis-
play a line on the system output device—your monitor.

Saving the Finished Product
Your program should now resemble Listing 2.2, although you might have
used slightly different spacing in Lines 3–4. Make any corrections that are
needed and save the file (by choosing File, Save or the Save All Files button).

LISTING 2.2 The Finished Version of the SalutonProgram
1: classSaluton {
2: public static void main(String[] args) {
3: String greeting = “Saluton mondo!”;
4: System.out.println(greeting);
5: }
6: }

When the computer runs this program, it runs each of the statements in the
mainstatement block on Lines 3 and 4. Listing 2.3 shows what the program
would look like if it were written in the English language instead of Java.

LISTING 2.3 A Line-by-Line Breakdown of the SalutonProgram
1: The Saluton program begins here:
2: The main part of the program begins here:
3: Store the text “Saluton mondo!” in a String variable named
greeting
4: Display the contents of the variable greeting
5: The main part of the program ends here.
6: The Saluton program ends here.
Free download pdf