Vaibhav A. Jani Vaibhav A. Jani - 2 years ago 77
Java Question

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

If a variable is declared as

public static varName;
, then I can access it from anywhere as
. 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
or as
from any other class.

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

Answer Source

Ofcourse it can be accessed as ClassName.var_name, but only from inside the class in which it is defined - that's because it is 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download