Thank you for visiting Blazing Games

Variables

A variable is a named entity that holds a piece of information. For instance, if you wanted to hold a persons name, you would create a variable named "name." Every piece of data used by a program requires a variable to hold that piece of information. Java is what is known as a typed language. This means that variables have a type of information that they hold and can hold only that type of information.

Variables can be created within a class, or can be created within a method. Variables that are created within a class are commonly referred to as class variables. Every instance of a class has it's own copy of the class variables assigned to that class. These variables are accessible by all methods within the class. As with methods, class variables have an access type associated with them. Public class variables are accessible by other classes. Protected class variables are accessible by sub-classes of the class that the variable is part of. private class variables are only accessible by methods within the class. Class variables that don"t have an access type assigned to them are considered package variables and are accessible only by classes within the same package as the class that the variable belongs to.

The format of a class variable is
access_type optional_properties type variable_name;
The optional properties of a class variable will be described next chapter. The sample program does not use any class variables. Method variables are defined within a method and simply have a type and a name. Variables can be assigned an initial value by use of an equal sign, as in the following:
int number = 7;
The semi-colon at the end of the line is used to indicate that the line is finished, as java allows you to spread out commands over multiple lines or to have multiple commands on the same line.

The most used variable types in programming tend to be numeric variables. Java supports the following variables types: byte, short, integer, long, float, double. All variables (unlike C and C++) are signed, meaning they can be negative. Byte, short, integer, and long numbers are whole numbers while float and double have a decimal point.

Humans generally use words, which require letters. The char type holds a single character, while the String type uses a group of letters. In fact, the String variable is actually an instance of a class. Any type of class can be assigned to a variable. We will cover using classes as a variable briefly later in this chapter and in more detail in a future chapter.

Previous Chapter 3 Contents Page 7 of 10 Book Contents Next

About - Privacy Policy - Contact - Links - FAQ
Copyright © 2005-2006 Blazing Games Inc. All Rights Reserved