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

(singke) #1
ptg7068951

52 HOUR 5:Storing and Changing Information in a Program


the computer is being told to set the productNamevalue to the same value
as a variable named Larvets.
After adding the charand Stringstatements, your program resembles
Listing 5.1. Make any necessary changes and be sure to save the file.

LISTING 5.1 TheVariableProgram
1: classVariable {
2: public static voidmain(String[] args) {
3: int tops;
4: floatgradePointAverage;
5: charkey = ‘C’;
6: String productName = “Larvets”;
7: }
8: }

The last two variables in the Variableprogram use the =sign to assign a
starting value when the variables are created. You can use this option for
any variables you create in a Java program, as you discover later in this
hour.
This program can be run but produces no output.

Other Numeric Variable Types
The types of variables you have beenintroduced to thus far are the main
ones you use for most of your Java programming. You can call on a few
other types of variables in special circumstances.
You can use the first, byte, for integer numbers that range from –128 to


  1. The following statement creates a variable called escapeKeywith an
    initial value of 27:
    byteescapeKey = 27;


The second, short, can be used for integers that are smaller in size than the
inttype. Ashortinteger can range from –32,768 to 32,767, as in the fol-
lowing example:
shortroomNumber = 222;

The last of thenumeric variable types, long, is typically used for integers
that are too big for the inttype to hold. Alonginteger can be from –9.22
quintillion to 9.22 quintillion, which is a large enough number to cover
everything but government spending.

NOTE
Although the other variable
types are all lowercase letters
(int,float, and char), the cap-
ital letter is required in the
wordStringwhen creating
string variables. A string in a
Java program is different than
the other types of information
you use in variable statements.
Yo u l e a r n a b o u t t h i s d i s t i n c t i o n
in Hour 6,“Using Strings to
Communicate.”

Free download pdf