, , ,

As we know that, static keyword denotes that a member variable, or method, can be accessed without requiring an instantiation of the class to which it belongs. So, you can call a method, even if you have never created the object to which it belongs!

static is often valuable when you know something is not going to change across instances. Static member variables are shared by all instances of the class to which they belong.

When you make a method static, it means that the method can be called without an instance of the class. It also means that the method cannot access instance variables unless it is passed a reference to an object.

rule of thumb: ask yourself “does it make sense to call this method, even if no object has been constructed yet?” If so, you can make it to be static.

Here we see in which situations we can create static members in your application.

Methods which are not using instance variables.

Utility classes which are not supposed to be changed.
Example: method trimValue(String str) which apply trim() if the string value is not null.

Any operation which are not dependent on instance creation. means, it never depends on constructors and variables.

If there is some code that can easily be shared by all the instance methods, extract that code into a static method.

If you are sure that the definition of the method will never be changed or overridden. As static methods can not be overridden.

Common functionality in your application which does the routine operation.

Constants are usually declared as static. So, we no need to create instance each time to when you use the constant variable (reduces object weight too).