Difference between public static and private static variables

Android Girl picture Android Girl · May 5, 2012 · Viewed 97.7k times · Source
class Employee{
 // salary  variable is a private static variable
private static double salary;

// DEPARTMENT is a constant
 public static final String DEPARTMENT = "Development";

public static void main(String args[]){
   salary = 1000;
  System.out.println(DEPARTMENT+  "  average salary:"+salary);
}
}

This java program contains a static variable. But I cannot understand the difference between public and private static variables.

Answer

trutheality picture trutheality · May 5, 2012
  • A public variable is accessible from anywhere (well, anywhere where the class is accessible).

  • A private variable is only accessible inside the class.

  • A static variable belongs to the class rather than to an instance of a class.

  • Notice that the variable DEPARTMENT is also final, which means that it cannot be modified once it is set. This is important here because that's what saves this from being bad code -- the variable is a constant so it's okay to give things outside the class access to it.