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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access
