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

(singke) #1
ptg7068951

50 HOUR 5:Storing and Changing Information in a Program


Some statements are calledexpressionsbecause they involve a mathematical
expression and produce a result. Line 4 in the preceding example is an
expression because it sets the value of the cvariable equal to 8 multiplied
by 5. You work with expressions during this hour.

Assigning Variable Types
Variables are the main way that a computer remembers something as it
runs a program. The Salutonprogram in Hour 2 used the greetingvari-
able to hold “Saluton mondo!”. The computer needed to remember that
text so that the message could be displayed.
In a Java program, variables are created with a statement that must include
two things:

. The name of the variable
. The type of information the variable will store


Variables also can include the value of the information being stored.
To see the different types of variables and how they are created, run
NetBeans and create a new empty Java file with the class name Variable.
Start writing the program by entering the following lines:
classVariable {
public static void main(String[] args) {
// Coming soon: variables
}
}

Go ahead and save these lines before making any changes.

Integers and Floating-Point Numbers
So far, theVariableprogram has a main()block with only one statement
in it—the comment // Coming soon: variables. Delete the comment and
enter the following statement in its place:
int tops;

This statement creates a variable named tops. It does not specify a value
for tops, so for the moment this variable is an empty storage space. The
inttext at the beginning of the statement designates topsas a variable
Free download pdf