Previous Section  < Day Day Up >  Next Section

Storing Information in a Variable

In the programs you write, one thing that's often needed is a place to store information for a brief period of time. You can do this by using a variable, a storage place that can hold information such as integers, floating-point numbers, true-false values, characters, and lines of text. The information stored in a variable can change, which is where the name "variable" comes from.

Load the file into your word processor (if it's not already loaded) and replace Line 3 with the following:

String greeting = "Saluton mondo!";

This statement tells the computer to store the line of text "Saluton mondo!" into a variable called greeting.

In a Java program, you must tell the computer what type of information a variable will hold. In this program, greeting is a stringa line of text that can include letters, numbers, punctuation, and other characters. Putting String in the statement String greeting = "Saluton mondo!" sets up the variable to hold string values.

When you enter this statement into the program, a semicolon must be included at the end of the line. Semicolons are used at the end of each statement in your Java programs. They're like periods at the end of a sentence. The computer uses them to determine when one statement ends and the next one begins.

Displaying the Contents of a Variable

If you ran the program at this point, it wouldn't display anything. The command to store a line of text in the greeting variable occurs behind the scenes. To make the computer show that it is doing something, you can display the contents of that variable.

Insert another blank line in the Saluton program after the String greeting = "Saluton mondo!" statement. Use that empty space to enter the following statement:


This statement tells the computer to display the value stored in the greeting variable. The System.out.println statement tells the computer to display a line on the system output device. In this case, the output device is your computer monitor.

Watch Out!

If you learned to type on a typewriter rather than a computer, watch out for hitting the "1" key as an alternative to the "l" key (lowercase "L"). A1though your cerebra1 cortex is perfect1y happy to treat the numera1 as the 1etter when it appears, a computer isn't as f1exib1e as your brain. Your program won't compile if you use print1n instead of println, for example.

    Previous Section  < Day Day Up >  Next Section