in java where and when do we use 'static int' and how does it differ from 'int'
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
static
means it is not instance specific. It belongs to theclass
. Usually it goes with final.EDIT : It does not have to be final, non final variables are fine as long as one is careful.
Well.
It's used when declare member variables, and
static
refers to whether or not you need an instance of the given class to access it.Typically,
static
is used for constants, or "helper" functions or variables. If you have too many, and if you end up combining static and non-static variables in a class, it ends up being suggestive of bad design (not all the time, though).If a variable is
static
, it's value is shared between all usages (i.e. between all instances of the object). That is, if you change it, all other accesses will see the change.A non-static variable will have a unique value per instance (as it can only be accessed per instance).
static int
, which can be accessed directly without using objects.int
, which cannot be accessed directly without using objects.static int: One variable per application Can be accessed without object.
int: One variable per object Cannot be accessed without object.
Using 'int' in a class means an integer field exists on each instance of the class. Using 'static int' means an integer field exists on the class (and not on each instance of the class)
The modifier static defines a variable as a class variable, meaning that there is exactly one of it only. Without it, a variable is an instantiable variable, so this variable exist per Object.
For example:
If you create 2 objects of the Test class, both objects will "share" the i variable. But each object will have its own j variable.
In the example above, the output will be
You can read more about it at The Java Tutorials - Variables