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

20

188

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?

Aperture answered 2/9, 2011 at 6:24 Comment(1)
Java variable names can't contain dashes (-).Amok
G
160

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.

Gabi answered 2/9, 2011 at 6:27 Comment(11)
What is necessary of accessing as ClassName.var_nam ? Where i can access it directly : var_nam within classAperture
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.Gabi
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.Lachus
@Lachus 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?Gabi
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.Disorder
@Gabi 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.Skip
@Skip 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.Gabi
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.Skip
@Skip 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).Gabi
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?Skip
@Skip Yes, that's the difference between static and non-static.Gabi
J
106

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.

Juvenal answered 2/9, 2011 at 6:27 Comment(2)
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.Dipsomania
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.Juvenal
B
54

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

Buckler answered 2/9, 2011 at 6:37 Comment(8)
Can you explain little bit more about the difference of private static and private not static variable access in one class?Artemisia
@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?Buckler
What is the difference in accessibility when we use static and non static variable within the single class where they are declared ?Artemisia
@Dharmendra: None whatsoever. Private variables are accessible within the same class whether they're static or not.Buckler
@JonSkeet Than in which case it be use full to make variable private sattic?Rem
@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.Buckler
"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.Thickhead
@ryvantage: No, not at all. A static method could access it with no problems.Buckler
E
16

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;
   }
}
Eccentricity answered 2/9, 2011 at 6:45 Comment(5)
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.Correy
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).Perlman
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.Lakh
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?Lakh
I looked it up. The answer to my previous question is: yes, it saves memoryLakh
M
12

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;
    }
}
Midway answered 20/6, 2016 at 18:32 Comment(0)
D
9

Well, private static variables can be used to share data across instances of that class. While you are correct that we cannot access the private static variables using constructs like ClassName.member or ClassInstance.member but the member will always be visible from methods of that class or instances of that class. So in effect instances of that class will always be able to refer to member.

Delaware answered 2/9, 2011 at 6:30 Comment(0)
O
8

What is the use of a private static class variable?

Let's say you have a library book Class. Each time you create a new Book, you want to assign it a unique id. One way is to simply start at 0 and increment the id number. But, how do all the other books know the last created id number? Simple, save it as a static variable. Do patrons need to know that the actual internal id number is for each book? No. That information is private.

public class Book {
    private static int numBooks = 0;
    private int id;
    public String name;

    Book(String name) {
        id = numBooks++;
        this.name = name;
    }
}

This is a contrived example, but I'm sure you can easily think of cases where you'd want all class instances to have access to common information that should be kept private from everyone else. Or even if you can't, it is good programming practice to make things as private as possible. What if you accidentally made that numBooks field public, even though Book users were not supposed to do anything with it. Then someone could change the number of Books without creating a new Book.

Very sneaky!

Olwen answered 9/11, 2013 at 20:55 Comment(0)
P
7

The private keyword will allow the use for the variable access within the class and static means we can access the variable in a static method.

You may need this cause a non-static reference variable cannot be accessible in a static method.

Punishable answered 28/3, 2014 at 10:1 Comment(0)
I
4

Another perspective :

  1. A class and its instance are two different things at the runtime. A class info is "shared" by all the instances of that class.
  2. The non-static class variables belong to instances and the static variable belongs to class.
  3. Just like an instance variables can be private or public, static variables can also be private or public.
Irruption answered 2/9, 2011 at 6:41 Comment(0)
F
3

Static variables are those variables which are common for all the instances of a class..if one instance changes it.. then value of static variable would be updated for all other instances

Fleabitten answered 23/11, 2013 at 4:42 Comment(0)
A
1

For some people this makes more sense if they see it in a couple different languages so I wrote an example in Java, and PHP on my page where I explain some of these modifiers. You might be thinking about this incorrectly.

You should look at my examples if it doesn't make sense below. Go here http://www.siteconsortium.com/h/D0000D.php

The bottom line though is that it is pretty much exactly what it says it is. It's a static member variable that is private. For example if you wanted to create a Singleton object why would you want to make the SingletonExample.instance variable public. If you did a person who was using the class could easily overwrite the value.

That's all it is.


    public class SingletonExample {
      private static SingletonExample instance = null;
      private static int value = 0;
      private SingletonExample() {
        ++this.value;
      }
      public static SingletonExample getInstance() {
        if(instance!=null)
        return instance;
        synchronized(SingletonExample.class) {
        instance = new SingletonExample();
        return instance;
        }
      }
      public void printValue() {
        System.out.print( this.value );
      }

      public static void main(String [] args) {
        SingletonExample instance = getInstance();
        instance.printValue();
        instance = getInstance();
        instance.printValue();
         }
    }

Affiliate answered 31/12, 2013 at 5:34 Comment(0)
S
1

I'm new to Java, but one way I use static variables, as I'm assuming many people do, is to count the number of instances of the class. e.g.:

public Class Company {
    private static int numCompanies;

    public static int getNumCompanies(){
        return numCompanies;
    }
}

Then you can sysout:

Company.getNumCompanies();

You can also get access to numCompanies from each instance of the class (which I don't completely understand), but it won't be in a "static way". I have no idea if this is best practice or not, but it makes sense to me.

Sobriquet answered 10/4, 2014 at 1:12 Comment(0)
E
1

In the following example, eye is changed by PersonB, while leg stays the same. This is because a private variable makes a copy of itself to the method, so that its original value stays the same; while a private static value only has one copy for all the methods to share, so editing its value will change its original value.

public class test {
private static int eye=2;
private int leg=3;

public test (int eyes, int legs){
    eye = eyes;
    leg=leg;
}

public test (){
}

public void print(){
    System.out.println(eye);
    System.out.println(leg);
}

public static void main(String[] args){
    test PersonA = new test();      
    test PersonB = new test(14,8);
    PersonA.print();    
}

}

> 14 3

Exclaim answered 21/1, 2017 at 10:32 Comment(0)
K
0

When in a static method you use a variable, the variable have to be static too as an example:

private static int a=0;  
public static void testMethod() {  
        a=1;  
}
Kesler answered 2/9, 2011 at 6:30 Comment(1)
Well, unless your method is given a reference to an instance of the class of course.Buckler
A
0

If a variable is defined as public static it can be accessed via its class name from any class.

Usually functions are defined as public static which can be accessed just by calling the implementing class name.

A very good example of it is the sleep() method in Thread class

Thread.sleep(2500);

If a variable is defined as private static it can be accessed only within that class so no class name is needed or you can still use the class name (upto you). The difference between private var_name and private static var_name is that private static variables can be accessed only by static methods of the class while private variables can be accessed by any method of that class(except static methods)

A very good example of it is while defining database connections or constants which require declaring variable as private static .

Another common example is

private static int numberOfCars=10;

public static int returnNumber(){

return numberOfCars;

}
Anything answered 10/2, 2014 at 3:54 Comment(0)
G
0

*)If a variable is declared as private then it is not visible outside of the class.this is called as datahiding.

*)If a variable is declared as static then the value of the variable is same for all the instances and we no need to create an object to call that variable.we can call that variable by simply

classname.variablename;

Goodlooking answered 22/9, 2015 at 9:10 Comment(0)
U
0

private static variable will be shared in subclass as well. If you changed in one subclass and the other subclass will get the changed value, in which case, it may not what you expect.

public class PrivateStatic {

private static int var = 10;
public void setVar(int newVal) {
    var = newVal;
}

public int getVar() {
    return var;
}

public static void main(String... args) {
    PrivateStatic p1 = new Sub1();
    System.out.println(PrivateStatic.var);
    p1.setVar(200);

    PrivateStatic p2 = new Sub2();
    System.out.println(p2.getVar());
}
}


class Sub1 extends PrivateStatic {

}

class Sub2 extends PrivateStatic {
}
Ungrateful answered 14/10, 2015 at 15:4 Comment(0)
D
0

If you use private static variables in your class, Static Inner classes in your class can reach your variables. This is perfectly good for context security.

Djerba answered 12/1, 2016 at 9:54 Comment(0)
H
0

ThreadLocal variables are typically implemented as private static. In this way, they are not bound to the class and each thread has its own reference to its own "ThreadLocal" object.

Handrail answered 22/6, 2017 at 13:2 Comment(1)
I don't understand this answer. What do you mean?Calvert
H
0

Private static fields and private static methods can useful inside public static methods. They help to reduce the too much logic inside public static methods.

Hollingsworth answered 8/11, 2022 at 3:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.