What is the use of a private static variable in Java?
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.
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.