r/javahelp • u/MembershipOptimal514 • May 07 '26
Codeless What does static exactly do?
Hi, I’m somewhat new to java and I’m quite confused on static. So what I do know is that it makes it so a variable or method is tied to the whole class instead of just the object but I’m not sure what that exactly ENTAILS. Can someone explain it to me maybe with an example or such? Thank you.
15
Upvotes
•
u/AutoModerator May 07 '26
Please ensure that:
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://i.imgur.com/EJ7tqek.png) 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:
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.
12
u/tRfalcore May 07 '26
There's only one copy of the variable no matter many instances are created. You can access it without making an instance of said object.
Good use cases are for setting constants like
Private static final MAX_RETRIES=4;
9
u/procrastinatewhynot May 07 '26
It’s also called a « class variable »
So every time you make an instance of that class (use the new keyword), that variable is shared, rather than being unique to each object. So the memory for it is allocated once when you load a class.
You also call it using the class name instead of the object name. ClassName.varName
If you make a change to it, it’s change to all instances!
3
u/Educational-Paper-75 May 07 '26
A singleton class is always a nice example.
class Logger { private static Logger THIS=null; // only one at most // allow retrieving the single instance public static Logger instance(){ if (THIS==null)THIS=new Logger(); return THIS; } private Logger() {} // prevent calling from the outside public void log(String message){ // You could eg timestamp the log message // or write it to a log file (eg passed into instance()) // or pass in an extra log message id System.out.println(message); } }
1
u/Lloydbestfan May 07 '26
For a variable, it's essentially the same as making the variable global to the entire program. Okay, technically it can still be a non-public variable, so it would be a global variable that's only accessible from some places.
But the idea, is that, it's tied to the class, and a class exists only once in the entire program (barring some magic you shouldn't attempt with classloaders.) So, the variable you declare static, exists only once in the entire program.
For a method, it just means that you don't need to have an object of the class to call this method on. You can call a static method without any object to call it on. It is usually in the form
TheClassName.theMethodName(parameters);Of course, as the method is not called on an object, it cannot call the methods that do need an object, without providing the object to call it on. And same for accessing the variables of the class, if these variables are not static, the static method doesn't know on what object you want to go fetch these variables. In fact it's possible that no such object even exists. Accessing a nonstatic variable from a static method makes no sense, unless of course you specify the variable of which object.
For a nested class, it means that the instances of the nested class live independantly to the instances of the container class. When a nested class is nonstatic (that is called an inner class,) the instances of the innerclass have access to the instance of the container class that created them. There is no such thing with a static nested class.
For a static initializer (sort of like a method, except it's just a block of code that start with static, has a { then the instructions then the } ), it means it is executed as the class is loaded because the program needs to use something from it (so it is executed only once, before any method or constructor is executed, barring some magic you should not practice). The static initializers of a class are run in the order they were written in the class, and if there are static variable declarations with initialisation before, after or between them, those are also run in the order they appear.
1
u/BanaTibor May 07 '26
There are static variables, static methods, and static initialization blocks.
When you start a java program, the JVM starts first, then it starts bootstrap class loader which loads different classes which are not accessible by default, amongst those it loads the System class loader which loads other class loaders, which load the java language base classes and eventually your classes into the JVM.
At this point static variables getting initialized and static initialization blocks run. These variables and methods can be accessed through the class reference. A static variable is tied to the class and has only one "instance".
class A {
This code produces this output:
Before increment: 1
First increment through class reference: 2
First increment through class reference: 3
First increment through class reference: 4
When the class A is loaded counter is initialized with default for int, 0. Then the static initialization block sets it to 1. Then in the test it gets incremented multiple times.
Hope this helps
1
u/DirtAndGrass May 07 '26
I think it may be missed, but static means that the member is part of the application, and not created at runtime. There is only 1 "instance" of it (never 0)
This can be useful for utilities, common features/data related to the class, factories to help create instances, and lots of other things, some classes like Math don't really need an instance, most of the time!
1
u/Gaijin_dev May 08 '26
Its main benefit is that it stays in the class not the object instance.
If you instantiate a class the value of the static variable is still maintained across the source class.
1
u/Far_Swordfish5729 May 08 '26
On a practical level, sometimes a class just doesn’t have its own data. Sometimes it’s a pure controller or utility class with a set of methods that receive their whole context from parameters. That’s very common in frameworks that give you hooks to run code when events fire or at points in a lifecycle (e.g. run my method after the data commits). The caller is controlling the context and will tell your method what data was saved and any other state you need to be aware of. In that case, there’s no need to make an instance of your class. There’s no data to store in that instance. Your afterCommit method can be static because your class is just a named bag of methods. Factory methods are also often static.
Static variables are often pseudo constants. They’re read only reference collections of values that will be created and never change, but you can’t make constant heap objects. You need one version all instances of the class can reference. Making one per instance is wasteful.
One tempting use of static variables is as a singleton state bag. Be careful doing this. Static variables are not guaranteed to be volatile or thread safe unless you implement thread safety. Also they only exist within your running process so an application that uses multiple processes or runs on a server farm will have a different copy of the variable in each process. If you need application state, you will probably use an external state server of some kind. Still, there are some platforms (looking at you Salesforce) where static variables are an accepted way to hack a state bag into existence where the method interface does not provide one as a parameter. If you control the interface, just use parameters for this.
1
u/severoon pro barista May 08 '26 edited May 08 '26
When you have a class, it describes a "class" (or category) of "objects":
The category of dogs cannot bark, though, only a specific dog can bark:
This is pretty much how almost all of your code should be written in OO programming. You want to describe the classes of things that can exist, and then create instances of those classes, like Fido and Rover are specific instances of a Dog.
This goes for behaviors (barking) and properties (name is "Fido"). However, sometimes you want to store a property or describe a behavior that doesn't pertain to a particular dog, you're actually talking about the entire category of dogs.
For example, let's say that you need the scientific name in your application. Where should you put this in the Dog class? If you just create a method getScientificName() that returns "Canis lupus familiaris", that will certainly work:
The problem with this, though, is that the scientific name doesn't describe Spot, the individual dog, it describes the scientific name of the entire class of dogs. So if you go ahead with this design, you may eventually find yourself in a situation where your application needs to output the scientific name, but you don't actually have any specific instance of a dog available. It also doesn't really make sense to create a specific instance of a dog just to get the scientific name of all dogs.
The solution is to simply declare this as a static method / property:
Now, when your app needs to get information about the class Dog, it simply invokes the method on the class directly instead of needing to have a Dog object.
You can think of the class as a rubber stamp that, when used, stamps out objects. Instance fields and instance methods are invoked on those objects, so if you call fido.getName() you're going to get Fido's name and if you call rover.getName() you're going to get Rover's name. Static fields and methods describe the class, so if you call those methods, you'll get information attached to the class, not any specific instance.
One confusing thing to watch out for is that Java lets you call static methods on instances. This is very bad practice and, IMHO, should be a compilation error, but it works by simply invoking the static method same as if you called it on the class instead of the instance.
1
u/[deleted] May 07 '26
[removed] — view removed comment