Helen Andrew
Helen Andrew

Reputation: 87

What do you mean by stateless in static method?

Static method should not contain a state. What does 'state' means here ?

I have read that static method do not need to be instantiated, and do not use instance variables. So when can I use static methods? I have read that static methods are bad? Should I include it when coding?

Upvotes: 0

Views: 1878

Answers (3)

tamilselvan
tamilselvan

Reputation: 33

Static members are not Objects of the class. They are initialized when classes are loaded. They operate on class not on objects. When creating N number of objects for a class, each object will hold individual non-static members. But, the static members are shared among them. Hence, they don't have any stateful data.

Upvotes: 0

dchekmarev
dchekmarev

Reputation: 459

As an answer here's an example:

public class SomeUtilityClass {
  private static boolean state = false;
  public static void callMeTwiceImBad() throws Exception {
    if (state) {
      throw new Exception("I remember my state from previous call!");
    }
    state = true;
  }
  public static int sum(int a, int b) {
    return a + b;
  }
}

By themselves they are neither bad nor good, they are just static.

Upvotes: 0

Shailesh
Shailesh

Reputation: 717

State means storing some information, static methods are loaded when a class is loaded so there is no need of instance to call the static methods, you can call this methods using name of class, it's depend on condition when to use static methods. you can use static methods as single component of product just pass your parameters and get your work done.

Upvotes: 2

Related Questions