0

So, I'm pretty new to Java, and as far as I can see, both of these are the same things:

public class HelloWorld {
    public void test(String test) {
        System.out.println(test);
    }
    public static void main(String args[]) {
        HelloWorld helloworld = new HelloWorld();
        helloworld.test("Hello world!");
    }
}

and

public class HelloWorld {
    public static void test(String test) {
        System.out.println(test);
    }
    public static void main(String args[]) {
        test("Hello world!");
    }
}

Are these both the same thing, and what's the reason you would use one over the other?

Jon
  • 21
  • 2
  • https://stackoverflow.com/questions/11993077/difference-between-static-methods-and-instance-methods – Reimeus Jun 25 '18 at 16:43
  • This assumes one main method. What happens if your application has multiple entry points depending on execution method? – Compass Jun 25 '18 at 16:44
  • It’s very opinion-based. Here’s a fairly common opinion, but just one out of many: [Why Static is Bad and How to Avoid It](https://dzone.com/articles/why-static-bad-and-how-avoid). Search for more. – Ole V.V. Jun 25 '18 at 16:47
  • For this particular kind of example, it might make sense to define `test()` to be a non-static method of class `HelloWorld`. The static `main()` method creates a new `HelloWorld` object, then calls its `test()` method. The advantage is that `test()` and whatever other member methods exist can share instance variables within the class object, instead of relying exclusively on static variables. – David R Tribble Jun 25 '18 at 17:41

1 Answers1

0

Static methods sometimes are difficult to test.

Non-static methods specify the behavior of objects. Static methods are typically for utility functions (such as Collections.sort())

fallaway
  • 423
  • 2
  • 10