Question:
What is a static variable in Java?
Quietfury
2013-10-03 06:43:18 UTC
I know what it does, but I can't seem to form the words in my head. And a static function?
Six answers:
2013-10-03 06:53:57 UTC
'static' makes an element usable without the need to instance a class.

You can think of it them class' fields or methods.

You don't have to create an instance to use them; you can use them straight on by class name.

For example:



public class Class1{

public int method(){return 5;}

public static int static_method(){return 5;}

}



Now, notice that both of method and static_method will work in this case:

Class1 c = new Class1();

c.static_method();

c.method();



But in this case, only static_method works:

Class1.static_method();

Class1.method() //Doesn't work!





It's called "static" probably because you can't declare them in runtime.

I mean, you can create more than 1 instance of the class.

But you can't "create more classes" in the runtime.
husoski
2013-10-03 13:56:03 UTC
The more descriptive name is "class variable". There's a single value of that variable shared by all instances of the class and by all "class methods". (aka "static methods")



Change "function" to "method" and you have the second answer above. Class methods are methods declared as static, and they aren't associated with instances (individual objects of the class type). That means they can only access class ("static") variables in the class definition.



Java doesn't really use the term "function" officially. That term comes from earlier languages like C and Fortran. The closest Java equivalent to "function" is "class method" (aka "static method").
?
2013-10-07 08:22:54 UTC
A static variable is one that’s associated with a class, not objects of that class. A static variable is shared by all instances of the class.
?
2013-10-04 04:27:25 UTC
Static variables have a single value for all instances of a class.
green meklar
2013-10-04 08:02:08 UTC
It's associated with a class rather than an individual object, so there's only one for the entire class. Kind of like as if the class were also a single giant object.
?
2014-02-21 12:44:17 UTC
class variables associated with class, i.e, available for all objects.

Class methods also called as static methods. Static methods called with class name.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...