r/javahelp • • Nov 21 '20

Codeless Static variables and why do we need them?

Hello, I'm just curious about static variables. When do we use them? What is the difference between a static variable and a variable?

20 Upvotes

11 comments sorted by

•

u/AutoModerator Nov 21 '20

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions

  • You include any and all error messages in full

  • You ask clear questions

  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

24

u/tsvk Nov 21 '20

A static variable is in a way a "singleton", it is a value that is shared among all instances of a class, and it can also be accessed without even creating an instance of the class, possibly using a static method.

19

u/[deleted] Nov 21 '20

When you create an instance of a class you allocate memory for every field that class have.

This way, if you class has an integer and you instantiate 10 objects, you consume the memory for 10 integers.

Now, if that int is a constant, then having 10 duplicates is a waste. That's where static comes in.

Static members belong to the class, not to the instances. What that means is that if you have a class with a static integer and you instantiate 10 objects, this time you consume the memory of a single Integer, since all objects share the same memory reference (they all use, literally, the same integer, not copies of it).

That's why if you change a static value every object of that class is affected. And that's also why public static values are recommended to be final. It's a bad idea that your object behavior can be affected because someone on a totally different part of the system decided to change a value.

6

u/fortune_telling_fish Nov 21 '20

I like that you talked about memory in your response. It seems so obvious, but I've mostly seen "theoretical" justifications for static variables, citing hierarchy and the quintessential "pi does not change, so it shouldn't be represented as a dynamic entity," which are all true and important, but it's enlightening to be able to think about from the perspective of memory usage. Why have ten baskets for one egg?

2

u/Lurkin_N_Twurkin Nov 22 '20

I'm going to quibble because this is definition land. Constants are different from static.

A constant is defined with final and might not take up any memory address(depending on the constant and the instruction set architecture), but be built into an instruction. A static can change, but will be tied to all instances of a class.

Edit: code block added. And words bettered

1

u/[deleted] Nov 22 '20 edited Nov 22 '20

I didn't mean that every static member is a constant (sorry if I wasn't clear enough) I just used a constant as an example for static members.

Static members can be variables (but please, keep them private) or even methods.

On Java methods cannot existe by themselves, usually they belong to an object, but if you need a function (on the mathematical sense, that is, they do not depend on the state of an object) there's no point attaching them to individual objects, that's when you declare them as static so they belong to the class, not to the object.

Edit. Rewording

9

u/mit74 Nov 21 '20

Because you need to create a class instance to access a variable. Static allow you to simply do MyClass.myvariable eg Math.PI.

Or you can access a method static like Helper.convertNumber(45);

9

u/le_bravery Extreme Brewer Nov 21 '20

A primary use of static variables is for constants.

Public static final String HELLO = “Hello”;

Static variables can be useful, but I would say that using them for anything that is actually variable is likely a place where some fragility will be introduced. If you want to change the value at runtime, you can have multi threading problems. If you expect the value to change at startup time from how it was compiled, then you should look into dependency injection instead.

For small applications, it can be useful but I’d argue you should avoid it except for true constants, where it is acceptable.

2

u/dastardly740 Nov 21 '20

I want second this. Avoid static variables that are modified at runtime unless you know what you are doing.

I had a contractor assigned to my team who i thought was fairly skilled, until he made a single variable in a class static for no apparent reason. Passed all unit tests but failed when run end to end in the normal multi-threaded way. And, I had to track it down.

Also, worth noting Java is used in web applications a lot, and web applications are multi-threaded. So, the multi-threading pitfall kicks in just by being in a web application. If you write a library that others might use you had better document that it is not thread safe or do the work to make it thread safe and document the potential performance issue you might have created because you don't know where it will be used.

To repeat, it is not worth the headaches of making a static variable that is modified at runtime without a very good reason.

5

u/HotRodLincoln Nov 21 '20 edited Nov 21 '20

Say, you need to have a count of how many instances of a class there are, if you didn't have static variables, you'd need an entire "count_myClass" class with one member to keep track of how many there are a lot of situations like this where you want to monitor information about the class as a whole rather than one object, and it's much more convenient than a class/metaclass pattern in most situations, and obviously you could do either. You also have no good way of linking the class and metaclass instances together without static variables at some point you're linking every class into some kind of class manager, which is comparatively a lot to write and easy for you to forget.

Like say I have a remote server and I'm allowed by license 30 connections to it. The Connection class itself can monitor and ensure I don't violate this and get upcharged by the remote service, rather than needing more.

1

u/umlcat Nov 22 '20

Static variables act more like global singletons.

A lot of code that is migrated from Java or C++ with static variables to programming languages that offer global variables, those become global singletons !!!

This is overlooked, because the class is used as a module.

Static variables, global variables and singletons, should be used carefully.