javaalgorithmintellij-idealinedefinition

Why do we have to add public static void main(String[] args)?


Why do we have to add "public static" and "args"? Is it required?

Every time I run a program in Java without the "public static void main(String[] args)", it gives me a error. What is this and why do we need it?


Solution

  • "Because the spec says so".

    There really isn't a lot more to say.

    But why does the spec say so?

    You'd have to ask the authors. But if you want some guesses:

    1. It doesn't matter. Developing software is really difficult. But, writing really simple software isn't. Hence, focussing on making something that is already quite simple to do (write a simple app you can knock out in an hour), even simpler, isn't a valuable exercise. In fact, if you make engage in "make an already doable thing even simpler" at the cost of "... by making hard things even harder", you're actively doing it wrong.

    2. Java is 30 years old, and at the time, inherited a lot from C. In particular, the general structure of a source file. This structure involves "at the top level there are type declarations, type declarations contain only methods and fields and initializers, and actual code goes inside those". Java copied that style as it was suitable, and familiar. Given that messing with this structure is painful (in that it is hard to do without making existing java code 'break' which is bad), that 30 year old history has resulted in 'well, for reasons that are mostly irrelevant today, it started out this way, and nobody has bothered to modify it because it's not all that important'.

    Is there hope?

    Current java is already different and you don't actually need this. This is legal java today. In JDK23 even (current java is 24).

    void main() {
      System.out.println("Hi, there!");
    }
    

    Just that. That's the entire file. Save it as whatever.java. It's still in preview so you run it with:

    java --enable-preview whatever.java
    

    main is still required here because of the way java as a model operates: You have types, and types contain members, which contain code. Code has to be 'in a thing'. It can't just exist on its own. Breaking this rule gets into all sorts of hairy complications: What does it mean if you can just dump code straight into a class - when is that code run, then? Java isn't interpreted like e.g. python or javascript. This preview feature still has a class (it simply has no name). That main method is inside that unnamed class.