1066

I am wondering when to use static methods? Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instance object of the class. Does this mean I should use a static method?

Example:

Obj x = new Obj();
x.someMethod();

...or:

Obj.someMethod(); // Is this the static way?

I'm rather confused!

Lii
  • 11,553
  • 8
  • 64
  • 88
KP65
  • 13,315
  • 13
  • 45
  • 46

24 Answers24

1639

One rule-of-thumb: ask yourself "Does it make sense to call this method, even if no object has been constructed yet?" If so, it should definitely be static.

So in a class Car you might have a method:

double convertMpgToKpl(double mpg)

...which would be static, because one might want to know what 35mpg converts to, even if nobody has ever built a Car. But this method (which sets the efficiency of one particular Car):

void setMileage(double mpg)

...can't be static since it's inconceivable to call the method before any Car has been constructed.

(By the way, the converse isn't always true: you might sometimes have a method which involves two Car objects, and still want it to be static. E.g.:

Car theMoreEfficientOf(Car c1, Car c2)

Although this could be converted to a non-static version, some would argue that since there isn't a "privileged" choice of which Car is more important, you shouldn't force a caller to choose one Car as the object you'll invoke the method on. This situation accounts for a fairly small fraction of all static methods, though.

Lii
  • 11,553
  • 8
  • 64
  • 88
not-just-yeti
  • 17,673
  • 1
  • 18
  • 15
  • 378
    A few good examples here. I would add, however, that "static" is often valuable when you know something is not going to change across instances. If this is the case, I would really consider the "Single Responsability Principle", which implies a class should have one responsability and thus only one reason to change. I feel one should consider moving the "ConvertMpgToKpl(double mpg)" function, and similar methods, to their own class. The purpose of a car object is to allow instantiation of cars, not provide a comparison between them. Those should be external to the class. – Zack Jannsen Aug 13 '12 at 11:04
  • 37
    I think I would rather the method `Car#isMoreEfficientThan(Car)`. It has the advantage that which car you return in a tie isn't arbitrary. It's obvious by the title of the method what is returned in a tie. – Cruncher Jan 07 '14 at 14:03
  • 11
    I would also be careful about creating a static method that is using some external resource (filesystem, database, etc) this type of static can make it horrendous to test the consuming methods. I personally try to keep statics in the realm of "utility." – Seth M. Apr 07 '14 at 13:50
  • 10
    In fact, it should be implemented as a [Comparator](http://www.tutorialspoint.com/java/java_using_comparator.htm). – Dogweather Feb 03 '15 at 23:36
  • just to simply add ,when you don't have any data/code dependency go for static else if data comes into picture its simply private(preferably)/public – shivi Apr 22 '15 at 06:58
  • @Cruncher shouldn't `isMoreEfficientThan(...)` return a `boolean`? (`true` if more efficient, `false` if as or less efficient) – Braden Best Jan 14 '16 at 20:27
  • 3
    @B1KMusic Of course. What I mean by "which car is returned in a tie" is "true maps to the called on car, and false maps to the passed car". It's without ambiguity. – Cruncher Jan 14 '16 at 20:28
  • Am I save to assume that any basic linear script running as a JAR on a linux machine should be static? For example a java program which processes a bunch of files by filtering (Blacklist/whitelist), packaging and deposits them in a archive directory. Basically all your classes are Utility classes which the main calls directly. Is this correct? – Kenny Steegmans Aug 02 '16 at 18:08
  • @KennySteegmans No, I think it's unrelated. For example, I could envision a 'class FileList', perhaps even with sub-classes 'ImageFileList' and 'AppFileList' etc., and so you might use an OO system. Admittedly, that's *probably* overkill in the situation you describe, and a bunch of well-designed static methods would probably suffice. (And of course, you would launch your program running by calling a static method (`main`).) – not-just-yeti Aug 10 '16 at 04:11
  • Thanks for your excellent answer. I now know java static method is shared by all instances of a certain class, dose it mean each instance has its own non-static method like non-static variable? Thanks. – typeof programmer Jun 02 '17 at 19:23
  • is there a general statement regarding state/sideeffects of static methods? – philx_x Oct 20 '17 at 10:29
  • 2
    -1 The example methods `double convertMpgToKpl(double mpg)` and `Car theMoreEfficientOf( Car c1, Car c2 )` are clearly not the methods of Car class. And today, in 2017, in the age of DI and loose coupling, these methods should not be static at all even in another class. – Aqeel Ashiq Nov 15 '17 at 06:14
  • 3
    Contrary to some of the comments, I actually appreciate the second example. Even though it may not be the best method in practical use, it helped me understand the answer to the question better. – jamesc1101 Dec 04 '17 at 17:23
  • 1
    @TomBrito No performance considerations as there's no performance difference after the code gets JIT compiled. Virtual method calls are expensive, but they obviously don't apply when the method can be static. Method is classes without ancestors get special treatment and so do non-overridden methods (whether `final` or not). – maaartinus Mar 13 '18 at 20:39
603

Define static methods in the following scenarios only:

  1. If you are writing utility classes and they are not supposed to be changed.
  2. If the method is not using any instance variable.
  3. If any operation is not dependent on instance creation.
  4. If there is some code that can easily be shared by all the instance methods, extract that code into a static method.
  5. If you are sure that the definition of the method will never be changed or overridden. As static methods can not be overridden.
Simon Forsberg
  • 13,086
  • 10
  • 64
  • 108
Mohd
  • 6,039
  • 1
  • 14
  • 2
  • 59
    good points, but they are requirements if you *want* to make a method static, not reasons to make one. – tetsuo Dec 11 '13 at 14:17
  • 4
    @Mohd about requirement 5: When can you be 100% sure a method will never be changed or overridden? Aren't there always unknown factors you can't take in account at the moment you write your static method? – PixelPlex Aug 31 '15 at 12:03
  • 11
    "Utility-Classes" are very difficult to reason about, the bad thing is that sooner or later everything starts 'looking like' an utility (yeah I'm referring to that "util" package that is bloated, untouchable and poorly tested), and your test cases will need more work (to mock static utils is HARD). Prefer objects first. – Sergio Jun 15 '16 at 08:00
  • 2
    @Mohd this answer is exactly what I am looking for. I faced a lot of problems using static methods in multithreading. Can you please elaborate points 2, 3 more (with example 100 thumbs up for you) – Prakash P Dec 17 '16 at 17:24
  • I think a "static class" should be invented if you are going to use static variables and methods. – Robert Feb 26 '18 at 14:08
  • Shouldnt 4 be an instance method? No need to make it static no? – Yassin Hajaj May 22 '18 at 11:22
219

There are some valid reasons to use static methods:

  • Performance: if you want some code to be run, and don't want to instantiate an extra object to do so, shove it into a static method. The JVM also can optimize static methods a lot (I think I've once read James Gosling declaring that you don't need custom instructions in the JVM, since static methods will be just as fast, but couldn't find the source - thus it could be completely false). Yes, it is micro-optimization, and probably unneeded. And we programmers never do unneeded things just because they are cool, right?

  • Practicality: instead of calling new Util().method(arg), call Util.method(arg), or method(arg) with static imports. Easier, shorter.

  • Adding methods: you really wanted the class String to have a removeSpecialChars() instance method, but it's not there (and it shouldn't, since your project's special characters may be different from the other project's), and you can't add it (since Java is somewhat sane), so you create an utility class, and call removeSpecialChars(s) instead of s.removeSpecialChars(). Sweet.

  • Purity: taking some precautions, your static method will be a pure function, that is, the only thing it depends on is its parameters. Data in, data out. This is easier to read and debug, since you don't have inheritance quirks to worry about. You can do it with instance methods too, but the compiler will help you a little more with static methods (by not allowing references to instance attributes, overriding methods, etc.).

You'll also have to create a static method if you want to make a singleton, but... don't. I mean, think twice.

Now, more importantly, why you wouldn't want to create a static method? Basically, polymorphism goes out of the window. You'll not be able to override the method, nor declare it in an interface (pre-Java 8). It takes a lot of flexibility out from your design. Also, if you need state, you'll end up with lots of concurrency bugs and/or bottlenecks if you are not careful.

tetsuo
  • 10,726
  • 3
  • 32
  • 35
  • 2
    A lot of good reasons listed here on when static can be useful. One more I can think of is that writing unit tests for such methods is just plain simple – nilesh Jul 24 '16 at 22:08
  • 1
    @tetsuo Thanks! Your explanation is very clear and the reasons provided are very logical and make a lot of sense. – Deniss M. May 09 '17 at 07:48
  • 5
    *And we programmers never do unneeded things just because they are cool, right?* +1 – Scaramouche Mar 07 '18 at 16:54
  • 1
    That said a static method becomes a full named function https://stackoverflow.com/questions/155609/whats-the-difference-between-a-method-and-a-function –  Jul 12 '18 at 23:53
  • 1
    I agree with Performance and Practicality, but not Purity. The static method can modify static members of the class (which may be private). This can be useful. For example, you could have a method like "static synchronized int allocateID() {return idNext++;}". In fact, a static method can be just as pure or impure as a non-static method in terms of side effects. – Adam Gawne-Cain Sep 06 '19 at 19:01
  • @AdamGawne-Cain Fair enough, Java is not a functional language, and has no real support for pure functions. I guess my thought process when I wrote this was, since with static methods you give up many features - such as polymorphism, dynamic binding, inheritance and instance scopes - it would be easier to keep methods pure, since you only have to worry about not using any class state, and only calling other pure methods. But yes, you're right, it still shares many concerns about side effects with instance methods. – tetsuo Sep 09 '19 at 13:39
46

After reading Misko's articles I believe that static methods are bad from a testing point of view. You should have factories instead(maybe using a dependency injection tool like Guice).

how do I ensure that I only have one of something

only have one of something The problem of “how do I ensure that I only have one of something” is nicely sidestepped. You instantiate only a single ApplicationFactory in your main, and as a result, you only instantiate a single instance of all of your singletons.

The basic issue with static methods is they are procedural code

The basic issue with static methods is they are procedural code. I have no idea how to unit-test procedural code. Unit-testing assumes that I can instantiate a piece of my application in isolation. During the instantiation I wire the dependencies with mocks/friendlies which replace the real dependencies. With procedural programing there is nothing to "wire" since there are no objects, the code and data are separate.

Alfred
  • 60,935
  • 33
  • 147
  • 186
  • 22
    I don't understand the part about not being able to unit-test procedural code. Don't you just set up test cases that map correct input to correct output using the static method together with the class as your "unit"? – tjb Mar 21 '12 at 18:40
  • 3
    You could do that to test those functions. But when using these static methods in other classes you want to test, I believe you can't fake them(mocks/friendlies) or anything, because you can not instantiate a class. – Alfred Mar 21 '12 at 23:01
  • But can't static methods only access static members?, If my understanding of this is correct then how could instantiation of the class make a difference? – tjb Mar 22 '12 at 07:55
  • Have you read the complete article => http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/? You should try to understand the 3rd paragraph about seams/isolation. Especially the last line of the 3rd paragraph => " Yes, static methods are easy to call, but if the static method calls another static method there is no way to overrider the called method dependency." – Alfred Mar 22 '12 at 10:55
  • Thanks for pointing to that paragraph, after reading all three articles I think I'm beginning to understand. – tjb Mar 22 '12 at 11:42
  • I hope so. You could also watch a video from misko explaining testing a bit => http://www.youtube.com/watch?v=wEhu57pih5w. There are even more video's available at youtube. – Alfred Mar 22 '12 at 12:57
  • 4
    @Alfred: Please have a look at [PowerMock](http://code.google.com/p/powermock/) which has the ability to mock static methods. Using PowerMock there are few scenarios, if any, where you find method dependencies which cannot be mocked. – Carles Sala May 20 '13 at 16:33
  • "Are You stupid or from Google?" Please go away with that guy. Programming is not just all about unit testing. And if You are a bad programmer - then unit testing is the only way You can write working software. – luke1985 Oct 08 '13 at 13:18
  • 7
    You can unit test statics using PowerMock, however you'll soon find you run out of Permgen space (done that, got the T-shirt), and its still nasty. Unless you KNOW (based on at least a decade of your own experience in true OO languages, not migrating from C) then DON'T DO IT. Seriously, the worst code I've ever seen came from an embedded developer's use of statics and in most cases we were stuck with it, forever, and adding more code just locked us into the unmodifiable monolith even more tightly. Loose coupling: no, testable: barely, modifiable: NEVER. Avoid! – user1016765 May 26 '14 at 18:12
  • 16
    I can understand the difficulty of testing static methods that depend on static state. But when you're testing *stateless* static methods like `Math.abs()` or `Arrays.sort()`, even methods you can *pass all dependencies into*, I don't see how that would ever impede unit testing. I would say a simple rule of thumb is: if you'd ever have any reason to mock out the procedural logic, then don't put it in a static method. I've never had a reason to mock out `Arrays.sort()` or `Math.abs()`. – Andy May 08 '15 at 20:24
  • @Andy If you are pulling in all the dependencies, then you are not "Unit testing" the Static method anymore. You are indirectly testing the dependencies of the static method. It's a not unit test anymore. – user6123723 Feb 27 '20 at 18:14
  • @user6123723 I was talking about passing mocks of the dependencies into the method being tested – Andy Feb 27 '20 at 21:48
  • @Andy Fair enough! – user6123723 Feb 27 '20 at 23:16
  • It's 2022, and +1 to Andy's comment. – starflyer May 20 '22 at 02:54
38

A static method is one type of method which doesn't need any object to be initialized for it to be called. Have you noticed static is used in the main function in Java? Program execution begins from there without an object being created.

Consider the following example:

 class Languages 
 {
     public static void main(String[] args) 
     {
         display();
     }

     static void display() 
     {
         System.out.println("Java is my favorite programming language.");
     }
  }
Jonah
  • 1,013
  • 15
  • 25
Zishan
  • 613
  • 8
  • 12
22

Static methods in java belong to the class (not an instance of it). They use no instance variables and will usually take input from the parameters, perform actions on it, then return some result. Instances methods are associated with objects and, as the name implies, can use instance variables.

Kevin Sylvestre
  • 37,288
  • 33
  • 152
  • 232
13

No, static methods aren't associated with an instance; they belong to the class. Static methods are your second example; instance methods are the first.

duffymo
  • 305,152
  • 44
  • 369
  • 561
13

If you apply static keyword with any method, it is known as static method.

  1. A static method belongs to the class rather than object of a class.
  2. A static method invoked without the need for creating an instance of a class.
  3. static method can access static data member and can change the value of it.
  4. A static method can be accessed just using the name of a class dot static name . . . example : Student9.change();
  5. If you want to use non-static fields of a class, you must use a non-static method.

//Program of changing the common property of all objects(static field).

class Student9{  
 int rollno;  
 String name;  
 static String college = "ITS";  

 static void change(){  
 college = "BBDIT";  
 }  

 Student9(int r, String n){  
 rollno = r;  
 name = n;  
 }  

 void display (){System.out.println(rollno+" "+name+" "+college);}  

public static void main(String args[]){  
Student9.change();  

Student9 s1 = new Student9 (111,"Indian");  
Student9 s2 = new Student9 (222,"American");  
Student9 s3 = new Student9 (333,"China");  

s1.display();  
s2.display();  
s3.display();  
}  }

O/P: 111 Indian BBDIT 222 American BBDIT 333 China BBDIT

Yosidroid
  • 2,053
  • 16
  • 15
11

Static methods should be called on the Class, Instance methods should be called on the Instances of the Class. But what does that mean in reality? Here is a useful example:

A car class might have an instance method called Accelerate(). You can only Accelerate a car, if the car actually exists (has been constructed) and therefore this would be an instance method.

A car class might also have a count method called GetCarCount(). This would return the total number of cars created (or constructed). If no cars have been constructed, this method would return 0, but it should still be able to be called, and therefore it would have to be a static method.

Charlie S
  • 4,366
  • 6
  • 59
  • 97
10

Static methods are not associated with an instance, so they can not access any non-static fields in the class.

You would use a static method if the method does not use any fields (or only static fields) of a class.

If any non-static fields of a class are used you must use a non-static method.

Carsten
  • 4,204
  • 4
  • 32
  • 49
6

Actually, we use static properties and methods in a class, when we want to use some part of our program should exists there until our program is running. And we know that, to manipulate static properties, we need static methods as they are not a part of instance variable. And without static methods, to manipulate static properties is time consuming.

Sagar
  • 161
  • 2
  • 7
  • Keeping state in static variables is a bad thing to do for many reasons - like multi-threading safety, debugging, data-encapsulation..etc etc Static methods are OK if they are pure functions (work with params only, without changing them). Good example would be an utility class, for say math calculations. – Vladimir Demirev Nov 07 '19 at 17:12
5

Use a static method when you want to be able to access the method without an instance of the class.

jamz
  • 4,991
  • 4
  • 24
  • 19
5

Static: Obj.someMethod

Use static when you want to provide class level access to a method, i.e. where the method should be callable without an instance of the class.

Finbarr
  • 31,350
  • 13
  • 63
  • 94
4

Static methods don't need to be invoked on the object and that is when you use it. Example: your Main() is a static and you don't create an object to call it.

Vaishak Suresh
  • 5,735
  • 10
  • 41
  • 66
4

Static methods can be used if

  • One does not want to perform an action on an instance (utility methods)

    As mentioned in few of above answers in this post, converting miles to kilometers, or calculating temperature from Fahrenheit to Celsius and vice-versa. With these examples using static method, it does not need to instantiate whole new object in heap memory. Consider below

    1. new ABCClass(double farenheit).convertFarenheitToCelcium() 
    2. ABCClass.convertFarenheitToCelcium(double farenheit)
    

    the former creates a new class footprint for every method invoke, Performance, Practical. Examples are Math and Apache-Commons library StringUtils class below:

    Math.random()
    Math.sqrt(double)
    Math.min(int, int)
    StringUtils.isEmpty(String)
    StringUtils.isBlank(String)
    
  • One wants to use as a simple function. Inputs are explictly passed, and getting the result data as return value. Inheritence, object instanciation does not come into picture. Concise, Readable.

NOTE: Few folks argue against testability of static methods, but static methods can be tested too! With jMockit, one can mock static methods. Testability. Example below:

new MockUp<ClassName>() {
    @Mock
    public int doSomething(Input input1, Input input2){
        return returnValue;
    }
};
Amit Kaneria
  • 5,466
  • 2
  • 35
  • 38
4

Static methods are the methods in Java that can be called without creating an object of class. It is belong to the class.

We use static method when we no need to be invoked method using instance.

rashedcs
  • 3,588
  • 2
  • 39
  • 40
4

I found a nice description, when to use static methods:

There is no hard and fast, well written rules, to decide when to make a method static or not, But there are few observations based upon experience, which not only help to make a method static but also teaches when to use static method in Java. You should consider making a method static in Java :

  1. If a method doesn't modify state of object, or not using any instance variables.

  2. You want to call method without creating instance of that class.

  3. A method is good candidate of being static, if it only work on arguments provided to it e.g. public int factorial(int number){}, this method only operate on number provided as argument.

  4. Utility methods are also good candidate of being static e.g. StringUtils.isEmpty(String text), this a utility method to check if a String is empty or not.

  5. If function of method will remain static across class hierarchy e.g. equals() method is not a good candidate of making static because every Class can redefine equality.

Source is here

Jake N
  • 59
  • 4
4

Static methods and variables are controlled version of 'Global' functions and variables in Java. In which methods can be accessed as classname.methodName() or classInstanceName.methodName(), i.e. static methods and variables can be accessed using class name as well as instances of the class.

Class can't be declared as static(because it makes no sense. if a class is declared public, it can be accessed from anywhere), inner classes can be declared static.

Echilon
  • 10,064
  • 33
  • 131
  • 217
3

A static method has two main purposes:

  1. For utility or helper methods that don't require any object state. Since there is no need to access instance variables, having static methods eliminates the need for the caller to instantiate the object just to call the method.
  2. For the state that is shared by all instances of the class, like a counter. All instance must share the same state. Methods that merely use that state should be static as well.
hemanto
  • 1,900
  • 17
  • 16
3

You should use static methods whenever,

  1. The code in the method is not dependent on instance creation and is not using any instance variable.
  2. A particular piece of code is to be shared by all the instance methods.
  3. The definition of the method should not be changed or overridden.
  4. you are writing utility classes that should not be changed.

https://www.tutorialspoint.com/When-to-use-static-methods-in-Java

Amitesh Bharti
  • 14,264
  • 6
  • 62
  • 62
1

In eclipse you can enable a warning which helps you detect potential static methods. (Above the highlighted line is another one I forgot to highlight)

eclipse setting

ave4496
  • 2,950
  • 3
  • 21
  • 48
1

I am wondering when to use static methods?

  1. A common use for static methods is to access static fields.
  2. But you can have static methods, without referencing static variables. Helper methods without referring static variable can be found in some java classes like java.lang.Math

    public static int min(int a, int b) {
        return (a <= b) ? a : b;
    }
    
  3. The other use case, I can think of these methods combined with synchronized method is implementation of class level locking in multi threaded environment.

Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instance object of the class. Does this mean I should use a static method?

If you need to access method on an instance object of the class, your method should should be non static.

Oracle documentation page provides more details.

Not all combinations of instance and class variables and methods are allowed:

  1. Instance methods can access instance variables and instance methods directly.
  2. Instance methods can access class variables and class methods directly.
  3. Class methods can access class variables and class methods directly.
  4. Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.
Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
  • Can't we access static fields through regular methods? Then this `A common use for static methods is to access static fields.` is not an argument. – parsecer Jul 09 '19 at 07:58
0

Whenever you do not want to create an object to call a method in your code just declare that method as static. Since the static method does not need an instance to be called with but the catch here is not all static methods are called by JVM automatically. This privilege is enjoyed only by the main() "public static void main[String... args]" method in java because at Runtime this is the method Signature public "static" void main[] sought by JVM as an entry point to start execution of the code.

Example:

public class Demo
{
   public static void main(String... args) 
   {
      Demo d = new Demo();

      System.out.println("This static method is executed by JVM");

     //Now to call the static method Displ() you can use the below methods:
           Displ(); //By method name itself    
      Demo.Displ(); //By using class name//Recommended
         d.Displ(); //By using instance //Not recommended
   }

   public static void Displ()
   {
      System.out.println("This static method needs to be called explicitly");
   }
} 

Output:- This static method is executed by JVM This static method needs to be called explicitly This static method needs to be called explicitly This static method needs to be called explicitly

Amrit
  • 135
  • 1
  • 5
-1

The only reasonable place to use static methods are probably Math functions, and of course main() must be static, and maybe small factory-methods. But logic should not be kept in static methods.

Danon
  • 2,771
  • 27
  • 37
  • No they are very different from global variables. The problem with a global variable is that it's very hard to track where they are being modified from. A static method can't be modified so doesn't have that problem. They are fine – DavidW Dec 13 '22 at 19:02
  • @DavidW I never said anything about global variables. I suggest you read the answers more carefully next time. – Danon Dec 14 '22 at 11:06
  • Sorry you're quite right you didn't say anything about global variables. I still disagree though - there's nothing wrong with a global function either. – DavidW Dec 14 '22 at 11:34
  • For example `Math.sin`. There's no state associated with it. It takes a number in and returns a number out. So it may as well be static or global. There's no need to instantiate a pointless empty class for it. – DavidW Dec 14 '22 at 11:41
  • @DavidW `Math` functions is a rare exception to this, and I agree, `Math.sin()` and `cos()` can be static. But that's it. – Danon Dec 15 '22 at 14:01
  • But for regular logic in your application (persistence, view, domain, business) static methods shouldn't be used. – Danon Dec 15 '22 at 14:10
  • You can effectively consider a constructor a static method (it doesn't depend on having an instance of a class), and factory functions are also static methods. Are you proposing to ban those? – DavidW Dec 15 '22 at 14:22
  • @DavidW Please don't try to take my argument out of propotions to have me say we should ban constructors. I'm not trying to come up with some absolute ban. What I'm saying, is that in normal situations regular methods and constructors are perfectly valid choice for virtually all projects, and `static` methods should never be used, with the limited exception of maybe `Math`. If you're creating services, repositories, views, utitlities or other classes and declare them `static`, you're making it harder for yourself. – Danon Dec 15 '22 at 15:57