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

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

Of course it can be accessed as ClassName.var_name, but only from inside the class in which it is defined – thats because it is defined as private.

public static or private static variables are often used for constants. For example, many people dont 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.

Static variables have a single value for all instances of a class.

If you were to make something like:

public class Person
    private static int numberOfEyes;
    private String name;

and then you wanted to change your name, that is fine, my name stays the same. If, however you wanted to change it so that you had 17 eyes then everyone in the world would also have 17 eyes.

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

Private static variables are useful in the same way that private instance variables are useful: they store state which is accessed only by code within the same class. The accessibility (private/public/etc) and the instance/static nature of the variable are entirely orthogonal concepts.

I would avoid thinking of static variables as being shared between all instances of the class – that suggests there has to be at least one instance for the state to be present. No – a static variable is associated with the type itself instead of any instances of the type.

So any time you want some state which is associated with the type rather than any particular instance, and you want to keep that state private (perhaps allowing controlled access via properties, for example) it makes sense to have a private static variable.

As an aside, I would strongly recommend that the only type of variables which you make public (or even non-private) are constants – static final variables of immutable types. Everything else should be private for the sake of separating API and implementation (amongst other things).

Leave a Reply

Your email address will not be published.