Local Variables in Java - dummies

By Doug Lowe

A local variable in Java 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!";

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.

Unlike class and instance variables, a local variable is fussy about where you position the declaration for it: You must place the declaration before the first statement that actually uses the variable.

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;

Local variables are not given initial default values. Thus, you must assign a value before you use a local variable.

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; 

When you declare two class or instance variables in a single statement but use only one initializer, the initializer applies only to the last variable in the list. For example:

static int x, y = 5;

Here, only y is initialized.