The blog of Jafar Aliyev

Archive

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

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

Wrapper objects

Static and instance initilization blocks

Overloading

Java access and nonaccess modifiers
Look at this cheat sheet for Java access and nonaccess modifiers

Implicit typecasting

Protected details

Interface methods are always public

Static methods can not be overriden
Here I explain, why static methods can not be overriden

Implicit typecasting

Java Tips

Postfix operators

Tricky Polymorphism

Pattern Matching

Default values

String equality

© 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.