Java Reference
In-Depth Information
4 int x = 3;
5 int y = 7;
6 computeSum();
7 }
8
9 public static void computeSum() {
10 int sum = x + y; // illegal, x/y are not in scope
11 System.out.println("sum = " + sum);
12 }
13 }
In this example, the main method declares local variables x and y and gives them
initial values. Then it calls the method computeSum . Inside this method, we try to use
the values of x and y to compute a sum. However, because the variables x and y are
local to the main method and are not visible inside of the computeSum method, this
doesn't work. (In the next chapter, we will see a technique for allowing one method
to pass a value to another.)
The program produces error messages like the following:
ScopeExample.java:10: cannot find symbol
symbol : variable x
location: class ScopeExample
int sum = x + y; // illegal, x/y are not in scope
ScopeExample.java:10: cannot find symbol
symbol : variable y
location: class ScopeExample
int sum = x + y; // illegal, x/y are not in scope
It's important to understand scope in discussing the local variables of one method
versus another. Scope also has implications for what happens inside a single method.
You have seen that curly braces are used to group together a series of statements. But
you can have curly braces inside curly braces, and this leads to some scope issues.
For example, consider the following code:
for (int i = 1; i <= 5; i++) {
int squared = i * i;
System.out.println(i + " squared = " + squared);
}
This is a variation of the code we looked at earlier in the chapter to print out the
squares of the first five integers. In this version, a variable called squared is used to
 
Search WWH ::




Custom Search