Sunday 18 January 2015

Java static Variables

If a variable in a class is static, it has only one value, which is shared by all members of the class. You can see this in the example below, where I created a class called Tax with a static variable called VAT:

andrew@UBUNTU:~/Java$ cat Tax.java
public class Tax  
  {
  static double VAT = 10;
  }
andrew@UBUNTU:~/Java$ javac Tax.java
andrew@UBUNTU:~/Java$


Then I wrote a program to use the class. In this program, I created 2 members called member1 and member2 and showed that they both had the same VAT value, i,e, 10. I changed member1.VAT to 11 and showed that member2.VAT changed to 11 too, without a specific assignment. Doing it this way can make your code difficult to follow. An alternative is to modify the static variable by prefixing it with the name of the class. To demonstrate this, I changed Tax.VAT to 12 and checked member1.VAT and member2.VAT to see that they had been altered in the same way:

andrew@UBUNTU:~/Java$ cat Tax_test.java
public class Tax_test
  {
  public static void main(String args[])
    {
    Tax member1 = new Tax();
    System.out.println("member1.VAT = " + member1.VAT);
    Tax member2 = new Tax();
    System.out.println("member2.VAT = " + member2.VAT);
    member1.VAT = 11;
    System.out.println("member1.VAT = " + member1.VAT);
    System.out.println("member2.VAT = " + member2.VAT);
    Tax.VAT = 12;
    System.out.println("Tax.VAT = " + Tax.VAT);
    System.out.println("member1.VAT = " + member1.VAT);
    System.out.println("member2.VAT = " + member2.VAT);
    }
  }
andrew@UBUNTU:~/Java$ javac Tax_test.java
andrew@UBUNTU:~/Java$ java Tax_test
member1.VAT = 10.0
member2.VAT = 10.0
member1.VAT = 11.0
member2.VAT = 11.0
Tax.VAT = 12.0
member1.VAT = 12.0
member2.VAT = 12.0
andrew@UBUNTU:~/Java$