Local Variables
A local variable is a variable that’s declared within the body of a method. Then you can use the variable only within that method. Other methods in the class aren’t even aware that the variable exists.
Here’s a program that uses a local variable:
public class HelloApp
{
public static void main(String[] args)
{
String helloMessage;
helloMessage = “Hello, World!”;
System.out.println(helloMessage);
}
}
You don’t specify static
on a declaration for a local variable. If you do, the compiler generates an error message and refuses to compile your program.
You may also declare local variables within blocks of code marked by braces. For example:
if (taxRate > 0)
{
double taxAmount;
taxAmount = subTotal * taxRate;
total = subTotal + total;
}
One way to initialize a variable is to code an assignment statement following the variable declaration. Assignment statements have this general form:
variable = expression;
Here, the expression
can be any Java expression that yields a value of the same type as the variable. For example, here’s a method that declares a local variable named i
, and then initializes the variable before using it:
public static void main(String[] args)
{
int i;
i = 0;
System.out.println(“i is “ + i);
}
Another way to initialize a variable is to use an initializer, which lets you assign an initial value to a variable at the time you declare the variable. Here’s the general form:
type name = expression;
Here are some examples:
int x = 0;
String lastName = “Lowe”;
double radius = 15.4;
In each case, the variable is declared and initialized in a single statement.
When you declare more than one variable in a single statement, each variable can have its own initializer:
int x = 5, y = 10;
static int x, y = 5;
Here, only y
is initialized.