Java Reference
In-Depth Information
Local variables can be declared at any place inside a method, just like any other Java
statement, but they must be declared before they can be used. The normal place for vari-
able declarations is immediately after the statement that names and identifies the method.
In the following example, three variables are declared at the top of a program's main()
method:
public static void main(String[] arguments) {
int total;
String reportTitle;
boolean active;
}
If you are creating several variables of the same type, you can declare all of them in the
same statement by separating the variable names with commas. The following statement
creates three String variables named street , city , and state:
String street, city, state;
Variables can be assigned a value when they are created by using an equal sign ( = ) fol-
lowed by the value. The following statements create new variables and give them initial
values:
int zipCode = 90210;
int box = 350;
boolean pbs = true;
String name = “Zoom”, city = “Boston”, state = “MA”;
As the last statement indicates, you can assign values to multiple variables of the same
type by using commas to separate them.
You must give values to local variables before you use them in a program or the program
won't compile successfully. For this reason, it is good practice to give initial values to all
local variables.
Instance and class variable definitions are given an initial value depending on the type of
information they hold, as in the following:
Numeric variables: 0
n
Characters: '\0'
n
Booleans: false
n
Objects: null
n
Search WWH ::




Custom Search