Java Reference
In-Depth Information
Rule #2
This rule is an offshoot of the first rule. A local variable cannot be accessed in the program until it is assigned
a value. The following snippet of code will generate a compiler error because it tries to print the value of the local
variable, sum , before it is assigned a value. Note that Java runtime has to read (or access) the value of the sum variable
before it prints the value.
int add(int n1, int n2) {
int sum;
// A compile-time error. Cannot read sum because it is not assigned a value yet.
System.out.println(sum);
}
The following snippet of code will compile fine because the local variable sum is initialized before it is read:
int add(int n1, int n2) {
int sum = 0 ;
System.out.println(sum); // Ok. Will print 0
}
Rule #3:
A local variable can be declared anywhere in the body of a method. However, it must be declared before it is used.
The implication of this rule is that you do not need to declare all local variables at the start of the method body. It is a
good practice to declare a variable closer to its use.
Rule #4
A local variable hides the name of an instance variable and a class variable with the same name. Let's discuss this
rule in detail. Every variable, irrespective of its type, has a scope. Sometimes the scope of a variable is also known as its
visibility. The scope of a variable is the part of the program where the variable can be referred to with its simple name.
The scope of a local variable declared in a method is the part of the method body that follows the variable declaration.
The scope of a local variable declared in a block is the rest of the block that follows the variable declaration. The
scope of the formal parameters of a method is the entire body of the method. It means that the name of the formal
parameters of a method can be used throughout the body of that method. For example,
int sum(int n1, int n2) {
// n1 and n2 can be used here
}
The scope of an instance variable and a class variable is the entire body of the class. For example, the instance
variable n1 and the class variable n2 can be referred to with its simple name anywhere in the class NameHidingTest1 ,
as shown:
class NameHidingTest1 {
int n1 = 10; // An instance variable
static int n2 = 20; // A class variable
// m1 is a method
void m1() {
// n1 and n2 can be used here
}
int n3 = n1; // n1 can be used here
}
 
Search WWH ::




Custom Search