Local variables

If a variable is declared within a statement block {}, then it is only valid within that statement block - but not outside of it, e.g. in other methods:

 1 public class Main {
 2 
 3     public static void main(String[] args) {
 4         localVar = 1;      // localVar is not valid yet
 5 
 6         int localVar = 1;  // Declaration of local variable - valid from here
 7         localVar = 2;      // OK
 8 
 9         for (int i = 0; i <= 10; i++) {
10             localVar = 2;  // OK - also valid in subordinate blocks
11             int localVar;  // For this reason new declaration of it not possible
12 
13             for (int localVar = 0; ...; ...;)   // New declaration therefore also here not possible
14             {
15             }
16 
17             for (; localVar <= 10; localVar++)   // OK (start value is 2)
18             {
19             }
20         }
21     }                       // localVar valid until here, the end of the method
22 
23     public void aSecondMethod() {
24         System.out.println(localVar);  // no validity outside the above method
25         int localVar = 1;   // OK - Declaration of a local variable with same name is possible here.
26                             // This local variable is new and independent
27     }                       // and valid until here.
28     
29     public void aThirdMethod(int localVar) // Declaration of local variable localVar
30     {
31         int localVar;  // This would be a new declaration, not possible as well
32     }
33 }


In general, then:

1 {
2      int localVar;    // Declaration of local variable - memory is allocated                      
3      {
4             localVar = 1;
5      }
6 
7 }                     // End of scope - memory will be released
8 int localVar;         // Declaration of a neu local variable



You have completed 0% of the lesson
0%