When to use static variables/methods and when to use instance variables/methods in Java? [closed]

i would like to ask the question when it would be advantageous to use static variables/methods or in the other case instance variables/methods in Java?

I know that it depends on the certain case (like programming util-classes as static methods), but can we declare something like a general strategy?


At novice level :

Use instance variables when : Every variable has a different value for different object. E.g. name of student, roll number etc..

use static variables when : The value of the variable is independent of the objects (not unique for each object). E.g. number of students.


Static variable: When you need something that will be used through out the application and every instance need to know the variable.

Instance variable: It will be different from object to object and object's property while static variable is Class's property.

Static function: Used to do some utility task. Can be called without any object declaration.

Instance function: Need object to call this function.

static or instance depends on your uses .


static variables are often used for constants, which is common to all the instances if the class. 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.

In Short

Any method or variable that is independent of the state of an instance of the class should be static.


Think of static variables as class-wide global variables or, if you use "final" keyword, as class-wide global constants. Use static non-final variables wisely - they are shared among all class instances and it may lead to some non-obvious mistakes. I would recomend avoid using mutable static variables at all - there are small to none cases, where such need couldn't be implemented using dependency injection.

Also using globals always makes unit-testing lot harder - one more drawback to consider.