What is the use of a private static variable in Java?

Vaibhav Jani picture Vaibhav Jani · Sep 2, 2011 · Viewed 317.4k times · Source

If a variable is declared as public static varName;, then I can access it from anywhere as ClassName.varName. I am also aware that static members are shared by all instances of a class and are not reallocated in each instance.

Is declaring a variable as private static varName; any different from declaring a variable private varName;?

In both cases it cannot be accessed as ClassName.varName or as ClassInstance.varName from any other class.

Does declaring the variable as static give it other special properties?

Answer

Jesper picture Jesper · Sep 2, 2011

Of course it can be accessed as ClassName.var_name, but only from inside the class in which it is defined - that's because it is defined as private.

public static or private static variables are often used for constants. For example, many people don't like to "hard-code" constants in their code; they like to make a public static or private static variable with a meaningful name and use that in their code, which should make the code more readable. (You should also make such constants final).

For example:

public class Example {
    private final static String JDBC_URL = "jdbc:mysql://localhost/shopdb";
    private final static String JDBC_USERNAME = "username";
    private final static String JDBC_PASSWORD = "password";

    public static void main(String[] args) {
        Connection conn = DriverManager.getConnection(JDBC_URL,
                                         JDBC_USERNAME, JDBC_PASSWORD);

        // ...
    }
}

Whether you make it public or private depends on whether you want the variables to be visible outside the class or not.