Navigator


Archive

201139
201230
201312
20151
201633
201755
201865
201955
20231

Creation date:

Variable hiding

class A {
   static int n=5;
   static void go(){
      int n=15;
      System.out.println(n);
      for (n=0; n<1; n++) {
         System.out.println(n);
      }
   }

   public static void main(String[] args) {
      System.out.println(n);
      go();
      System.out.println(n);
   }
}

Here the first declared n is a class variable. The second n in method go() is a stack variable. Inside of method go() it hides a class variable. Therefore the result will be as follows.

5
15
0
5

First println, inside of main method prints a class variable's value. The second println (inside go() method) prints a stack variable because stack variable here hides a class variable. The third println prints the same stack variable's modified value. The last println shows us that class variable remains the same after go() method.

Author: Jafar N.Aliyev (Jsoft)

Read also

Static methods can not be overriden

Here I explain, why static methods can not be overriden

Use instanceof carefully

Usage of 'instanceof' method in some situations will give you a compilation error

Java access and nonaccess modifiers

Look at this cheat sheet for Java access and nonaccess modifiers

© Copyright

All articles in this site are written by Jafar N.Aliyev. Reproducing of any article must be followed by the author name and link to the site of origin(this site). This site also keeps the same rules relative to the articles of other authors.