I understand its use,but when they designed java why they did not allow to main
run without String [] args
(If i, as a programmer, do not need the array)?
there a logic behind the decision?
Advertisement
Answer
Effectively this question cannot be answered at all unless your name is James Gosling, and I don’t think he’s particularly active on SO.
No, there is no ‘logic’ to it, it just is what it is. The main had to take some form. Specifically:
- Java is not structurally typed. Even if I have
interface Camera {void shoot(Person p); }
as well asinterface Gun {void shoot(Person p);}
, even though the structure of a camera and the structure of a gun is identical (they both have ashoot(Person)
method), you don’t just get to treat or even cast a Camera to a Gun or vice versa – java is nominal. Structure doesn’t matter.
Except for main, which is all about structure. It’s inconsistent with itself. No real logic.
- Using a string array is itself weird; arrays, especially of non-primitive types, are best reserved for weird hackery and the core library. They can’t grow or shrink, they are not immutable and cannot be made immutable (except zero-len arrays), their toString impl is mostly useless, and their hashCode/equals impls don’t do what you wanted them to.
List<String>
would have made more sense.
But.. WHYY????
Simple:
List
wasn’t around in java 1.0. There wasjava.util.Vector
but that was definitely seen as a bolt-on thing. generics definitely weren’t around.- The idea of using the structural aspect: Have a static method named main that takes a string array – is a straight copy of C. A lot of bizarro java things (such as the syntax for
switch
. Have you looked at it? What the heck, right?) has the explanation: … because it looks familiar to C programmers. As anachronistic and silly that seems today, java did put a real dent in C’s dominance, no other language really did that (a bunch, like Python, are older than java and popular too, but python didn’t get popular until way later compared to when java got popular. You can make an argument that Perl and PHP did get in C’s way a bit, though).
In ‘modern’ java, you’d have something like:
public class Main extends Application { @Override public void run (Args args) { ... } }
with a rule that such a thing must have a public no-args constructor.
Given that java started out that way, it doesn’t change, in order to keep backwards compatibility. It’s not important enough to try to redesign things this way, at least, team OpenJDK doesn’t appear to think so.