You are here

Static Variables

Get the entire book!
Java for the Beginning Programmer

Static variables always retain their values. Static local variables will hold their values between method or function calls. Static class-level variables will hold their values across all instances of a class. First I will show you an example of a static local variable. Listing 6.1 shows using a local variable.

Listing 6.1: Using a Static Variable (MyClassStatic.java)

public class MyClassStatic
{
  static int x = 0;

  public static void myMethod()
  {    
    System.out.println( "Value of x:" + x );
    x++;
  }

  public static void main(String args[])
  {
    myMethod();
    myMethod();
    myMethod();
  }
}

If you were to run this program the output would be the numbers 0,1 and 2 all on separate lines. The keyword static in front of the local variable x is causing it to hold its value between method calls. This is not normal behavior for local variables, as you will see later in this section.

Static variables can also be class level, as the following example shows. Listing 6.2 shows an example of using a class level static variable.

Listing 6.2: Using a Static Class Variable (MyClassLevelStatic.java)

public class MyClassLevelStatic
{
  static int x = 0;

  public static void myMethod()
  {
    System.out.println( "Value of x:" + x );
    x++;
  }

  public static void main(String args[])
  {
    x = 10;
    myMethod();
    myMethod();
    myMethod();
  }
}

If you were to run the above program the output would be 10,11 and 12 all on separate lines. The variable x is declared outside of any method or function, because of this, it is class level and can be accessed from anywhere in the class. The variable is also static, so it can be accessed from both static and nonstatic methods. When x is assigned to 10 in the main method, that x is the same x that is increased by myMethod.

Technology: 

Theme by Danetsoft and Danang Probo Sayekti inspired by Maksimer