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.

tip.eps 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;

}

Warning.eps 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 ...

Get Java For Dummies Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.