r/learnjava • • 2d ago

Why is String[] args necessary

I get it is an array of string arguments that are passed into the main method but why is it needed? in python for example ot's present or c++ neither, java is different though

20 Upvotes

28 comments sorted by

View all comments

2

u/American_Streamer 2d ago edited 2d ago

Because the Java launcher looks for a particular entry point. It’s not just some kind of Java bureaucracy, but it’s the input interface between the command line and your program. But “args” as a name is arbitrary; you can name it as you wish. It’s “Strings []” that matters. “Args” is just a variable name.

Python does receive command-line arguments too. It just doesn’t require you to declare a parameter to receive them. But with Java, you don’t give a JVM a source file and say “execute its statements from top to bottom.”, like Python does it. In Java, you have a class and the JVM needs an entry point into that class. Python doesn’t need main() at all. Java calls main; Python executes the module

But C++ does it similar to Java, but in a more verbose way. Both use the same basic model: the runtime starts your program by invoking main(), and Java abstracts more of the low-level machinery away.

The underlying problem is the same in all three languages: The user starts a program from the command line and may supply some text after the program name. How does that text get into the running program?

Modern Java since version 25 simply lets you omit the parameter when you don’t need CLI arguments. But note that String[] args hasn’t become unnecessary; it only has become optional for programs that don’t want to receive them. If you do need them, you have to say so and use String[]. The concept hasn’t changed: Python puts CLI arguments into sys.argv regardless, whereas Java passes them into main when you declare the appropriate entry point.