I just started learning java using eclipse IDE. I noticed that main method has to be static else it throws error. Because of this I have to declare many Scanner class' objects for each user-given input. Is there a way to make the main method non-static or defining main method without the static keyword in eclipse??
-
5Could you clarify "_Because of this I have to declare many Scanner class' objects for each user-given input_"? Preferably with code (see [mcve]). – Slaw Dec 23 '18 at 05:07
-
*I noticed that main method has to be static else it throws error.* Correct. The `main` method must be `static`. *Is there a way to make the main method non-static or defining main method without the static keyword in eclipse?* **No** (with Java). Yes if you use another language where `main` isn't required to be `static`. – Elliott Frisch Dec 23 '18 at 05:07
-
Include code (possibly at Code Review if it's on-topic there but not here); you normally should not create more than one `Scanner` object per input stream. – chrylis -cautiouslyoptimistic- Dec 23 '18 at 05:50
3 Answers
Is there a way to make the main method non-static or defining main method without the static keyword [...]?
No, this is part of how java works. There is no way around it. But it shouldn't impact your application since you can always create an instance of your main class and call another method on it:
public class X {
public static void main(String args[]) {
new X().nonStaticMain();
}
public void nonStaticMain() {
// just pretend this is your main
}
}

- 77,657
- 34
- 181
- 348
-
I would recommend putting the application code into the constructor of `X` and call `X` `App`. – howlger Dec 23 '18 at 08:49
The main method is the first method that JVM looks for during compilation. This main method has to be executed even before the instantiation of any object of the class. so that later these instantiated objects will invoke other required methods. And hence, static will help the main to run before object instantiation. It is not possible to run the main method without the static keyword.

- 317
- 5
- 12

- 11
- 4
The answer is no. You can have a look at these links too:
[A Closer Look at the "Hello World!" Application] (https://docs.oracle.com/javase/tutorial/getStarted/application/index.html)

- 43
- 1
- 8