Java Reference
In-Depth Information
javac Scope.java
Scope.java:19: Variable 'outer' is already defined in this method.
int outer = 5; // Uncomment this for an error
^
1 error
javac Scope.java
Scope.java:23: Undefined variable: inner
System.out.println("inner = " + inner); // Uncomment this for an error
^
1 error
How It Works
The method main() in this program has one block nested inside the block containing the code for the
method. The variable outer is defined right at the start, so you can refer to this anywhere within the
method main() , including inside any nested blocks. You are not allowed to re-declare a variable, so
the commented statement that re-declares outer within the inner block will cause a compiler error, if
you remove the double slash at the beginning of the line.
The variable inner is defined inside the nested block with the initial value 2, and you can refer to it
anywhere from its declaration to the end of the inner block. After the closing brace of the inner block,
the variable inner no longer exists, so the commented output statement that refers to inner is illegal.
However, since the variable inner has expired, we can declare another one with the same name and
with the initial value 3.
Note that all this is just to demonstrate the lifetime of local variables. It is not good practice to redefine
variables that have expired, because of the potential for confusion. Also, although we have just used
variables of type int in the example above, scoping rules apply to variables of any type.
There are other variables called class variables which have much longer lifetimes
when they are declared in a particular way. The variables PI and E in the standard
library class Math are examples of these. They hang around as long as your program
is executing. There are also variables that form part of a class object called instance
variables. We will learn more about these in Chapter 5.
Loops
A loop allows you to execute a statement or block of statements repeatedly. The need to repeat a block
of code arises in almost every program. If you did the first exercise at the end of the last chapter, based
on what you had learned up to that point you would have come up with a program along the lines of:
public class TryExample1 _ 1 {
public static void main(String[] args) {
byte value = 1;
value *= 2;
System.out.println("Value is now "+value);
value *= 2;
Search WWH ::




Custom Search