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);
}

Rishi Raj
Rishi Raj

I am a coder

Updated on: 30-Jul-2019

158 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements