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

364,628

Solution 1

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.

Solution 2

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.

Solution 3

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).

Solution 4

Well you are right public static variables are used without making an instance of the class but private static variables are not. The main difference between them and where I use the private static variables is when you need to use a variable in a static function. For the static functions you can only use static variables, so you make them private to not access them from other classes. That is the only case I use private static for.

Here is an example:

Class test {
   public static String name = "AA";
   private static String age;

   public static void setAge(String yourAge) {
       //here if the age variable is not static you will get an error that you cannot access non static variables from static procedures so you have to make it static and private to not be accessed from other classes
       age = yourAge;
   }
}

Solution 5

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

Yes, both are different. And the first one is called class variable because it holds single value for that class whereas the other one is called instance variable because it can hold different value for different instances(Objects). The first one is created only once in jvm and other one is created once per instance i.e if you have 10 instances then you will have 10 different private varName; in jvm.

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

Yes, static variables gets some different properties than normal instance variables. I've mentioned few already and let's see some here: class variables (instance variables which are declared as static) can be accessed directly by using class name like ClassName.varName. And any object of that class can access and modify its value unlike instance variables are accessed by only its respective objects. Class variables can be used in static methods.

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

Logically, private static variable is no different from public static variable rather the first one gives you more control. IMO, you can literally replace public static variable by private static variable with help of public static getter and setter methods.

One widely used area of private static variable is in implementation of simple Singleton pattern where you will have only single instance of that class in whole world. Here static identifier plays crucial role to make that single instance is accessible by outside world(Of course public static getter method also plays main role).

public class Singleton {
    private static Singleton singletonInstance = new Singleton();

    private Singleton(){}

    public static Singleton getInstance(){
        return Singleton.singletonInstance;
    }
}
Share:
364,628

Related videos on Youtube

Vaibhav Jani
Author by

Vaibhav Jani

I follow the mathematics, philosophy, and mysticism :) I plotted Butterfly curve using this (now on github) :

Updated on October 27, 2020

Comments

  • Vaibhav Jani
    Vaibhav Jani over 3 years

    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?

    • Martijn Courteaux
      Martijn Courteaux over 12 years
      Java variable names can't contain dashes (-).
  • Vaibhav Jani
    Vaibhav Jani over 12 years
    What is necessary of accessing as ClassName.var_nam ? Where i can access it directly : var_nam within class
  • Jon Skeet
    Jon Skeet over 12 years
    Well, unless your method is given a reference to an instance of the class of course.
  • Jesper
    Jesper over 12 years
    It is not necessary to access it via the class name, but some people think it is good style, to distinguish it from a non-static variable.
  • Dharmendra
    Dharmendra over 12 years
    Can you explain little bit more about the difference of private static and private not static variable access in one class?
  • Jon Skeet
    Jon Skeet over 12 years
    @Dharmendra: It's not clear to me what you mean. The private part is irrelevant - what exactly is confusing you about the difference between static variables and instance variables?
  • Dharmendra
    Dharmendra over 12 years
    What is the difference in accessibility when we use static and non static variable within the single class where they are declared ?
  • Jon Skeet
    Jon Skeet over 12 years
    @Dharmendra: None whatsoever. Private variables are accessible within the same class whether they're static or not.
  • Yog Guru
    Yog Guru about 11 years
    @JonSkeet Than in which case it be use full to make variable private sattic?
  • Jon Skeet
    Jon Skeet about 11 years
    @YogGuru: I don't see the relevance of the question. Make it private if you want it to be private, and static if you want it to be static. They're orthogonal.
  • chaitanya
    chaitanya over 10 years
    what is necessary to accessing it using static variable, We can write "private final String JDBC_PASSWORD = "password";" instead of using static variable for this password string.
  • Jesper
    Jesper over 10 years
    @chaitanya It's a constant. Why would you want to have a copy of the variable for each instance of the class by making it non-static?
  • ryvantage
    ryvantage over 10 years
    "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." Technically, a private static variable would need a class instance to access it.
  • Jon Skeet
    Jon Skeet over 10 years
    @ryvantage: No, not at all. A static method could access it with no problems.
  • Mukus
    Mukus about 10 years
    I think I like this answer the most. +1. The only time it makes sense to use static in a private variable is if a static method were to access it.
  • Ganesh Krishnan
    Ganesh Krishnan over 9 years
    This does not apply to private static variables unless you also write accessor methods for the private variable because they cannot be accessed from outside the class.
  • TofuBeer
    TofuBeer over 9 years
    Not true @GaneshKrishnan, any instance of the class has access to both variables. Naturally you can expect that the author of the class won't do something silly. Also, with reflection and JNI, all bets are off.
  • DanMan
    DanMan about 9 years
    WIthout giving the class a proper name you can't really say if this is a valid use case. Like, if the class was called Person, then it would probably be a bug, because you couldn't have multiple persons of different age (if that was an intended use case).
  • user1923551
    user1923551 about 9 years
    static is class level variable, which is common and only one copy exists for all instances of that class. The rule is applicable whether it is private or public. private just says I don't want out side world to corrupt my variable value (for non-final statics) . If a static is final then there is no harm in making it as public, as no one can change its value.
  • Lv99Zubat
    Lv99Zubat about 7 years
    I agree @Mukus. This might be the only real answer to this question. I think OP understands static already but people seem to want to explain it again. He is asking about a specific scenario. The ability to access variables in static methods is the functionality that 'private static' adds. I just want to also add that it allows nested static CLASSES access to the variables as well.
  • Lv99Zubat
    Lv99Zubat about 7 years
    What about memory? With static, you’d only be creating one copy for the class instead of a copy for every instance. And obviously with a constant, you'd only ever need one copy for the class. Does this save memory?
  • Lv99Zubat
    Lv99Zubat about 7 years
    I looked it up. The answer to my previous question is: yes, it saves memory
  • H.Rabiee
    H.Rabiee over 6 years
    I don't understand this answer. What do you mean?
  • getsadzeg
    getsadzeg about 5 years
    @Jesper If the class is an Android activity(extends AppCompatActivity, for example), would that make sense in that case? Because we don't really make instances of Android application components.
  • Jesper
    Jesper about 5 years
    @getsadzeg In principle you can put these constants in any class; what a good place is, depends on how your software is structured. It's hard to say in general if putting it in an Android activity is a good place.
  • getsadzeg
    getsadzeg about 5 years
    I think that if we're putting a constant in Activity(like TAG for logging), there's no need for it to be static. Private - OK, static - no real need.
  • Jesper
    Jesper about 5 years
    @getsadzeg If it's a constant, you should make it static. Otherwise Java will create a separate instance of it for every instance of the surrounding class, and that is unnecessary and ineffiecient. (See the comments above).
  • getsadzeg
    getsadzeg about 5 years
    I think it makes more sense for me now. So if Android makes a new instance of Activity several times(for dull example, let's say, if the user rotates the device) it'll also make a new instance of the non-static variable, right?
  • Jesper
    Jesper about 5 years
    @getsadzeg Yes, that's the difference between static and non-static.