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