Reference static field after declaration in Java


The static field variable is a class level variable and it belongs to the class not the class object.

So the static field variable is common to all the class objects i.e. a single copy of the static field variable is shared among all the class objects.

A program that demonstrates referencing the static field variable after declaration is given as follows:

Example

 Live Demo

public class Demo {
   static int a = 7;
   static int b = a + 5;
   public static void main(String[] args) {
      System.out.println("a = " + a);
      System.out.println("b = " + b);
   }
}

Output

a = 7
b = 12

Now let us understand the above program.

The class Demo contains static variables a and b. The method main() prints the values of a and b. A code snippet which demonstrates this is as follows:

static int a = 7;
static int b = a + 5;
public static void main(String[] args) {
   System.out.println("a = " + a);
   System.out.println("b = " + b);
}
raja
Published on 15-Feb-2019 10:56:44
Advertisements