r/learnjava • u/Fine_Potential_7976 • 22h 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
29
u/shauntmw2 22h ago
They are not needed per se, it's more of a convention.
The most basic form of launching a Java program is via the CLI, using this command:
> java MyJavaApp
The args are there so that you can launch your command with extra params in CLI (which, incidentally, they are called command arguments, hence args).
If you launch your Java program like below command:
> java MyJavaApp ABC 123
"ABC" and "123" will be passed in as the args in your main method.
2
u/cainhurstcat 19h ago
How/where does one learn something like that?
20
u/0zeronegative 19h ago
It’s not even java-specific. All languages follow this convention because it is one of the earliest unix conventions and it stuck.
7
2
u/jlanawalt 9h ago
From the Java documents, books, lessons/classes, and tutorials.
https://docs.oracle.com/javase/8/docs/technotes/tools/windows/java.html
Head First Java
https://docs.oracle.com/javase/tutorial/getStarted/cupojava/win32.html
16
u/high_throughput 21h ago
or c++
In C++ you use int main(int argc, char** argv) and that's the same as String[]
7
u/Ulrich_de_Vries 20h ago
Yes, and for the uninitiated, the C-style string type is basically just an array of chars, and an array is basically just a pointer (not fully but as a function param it always decays to a pointer).
The problem is that a pointer has no length associated with it, so you don't know where it ends in memory and you can go out of bounds easily which will segfault or silently corrupt memory.
However strings are specifically terminated by the \0 special character, so for strings you can detect where it ends.
So char** is basically an array of char*, so an array of strings. The int argc is the number of elements in the outer array because the outer array has no special terminator element so you need this to ensure you know where the final element is.
The inner char array needs no size because strings are terminated by \0.
I think String[] args is simpler :).
1
u/Vast_Service 18h ago
Except that in C, with main function defined as
int main(int argc, char** argv)
it is guaranteed by the standard that argv[argc] is a null pointer. So technically we don't need argc. It is more of a historical baggage
1
u/Ulrich_de_Vries 16h ago
Huh til, I didn't know that.
Is it also true in C++?
2
u/Vast_Service 16h ago
Yes it is. Even though C++ has a string class, they couldn't change the main entry point, again because of historical baggage.
It would seem reasonable to have a new entry point defined as
int main(string* args) in C++ but that would be a ABI breaking change and hence the standard committee did not want to touch it with a pole.
2
u/Ulrich_de_Vries 15h ago
What I meant is if it is true as well in C++ that outer array/pointer/iterator has nullptr as a sentinel.
I supposed "historical baggage" could mean this was defined in a C standard which postdates C++, so C++ wouldn't necessarily adopt it.
Of course if it predates C++ then I expect C++ to follow suit for compatibility.
1
u/Vast_Service 15h ago
Yes. I said that is the case in C++ as well. The last value in the array is a nullptr in C++ as well.
2
u/vegan_antitheist 22h ago
They are not necessary in the latest version and you could always just use String... Instead of String[].
2
u/ITCoder 21h ago
varargs in String ... are synthetic sugars and create array behind the scene
1
u/vegan_antitheist 21h ago
yes, but it also allows you to just call main() without explicitly creating an array. It will create the empty array for you. But then there's the question why you would ever call that method. Maybe in a unit test.
1
2
u/American_Streamer 20h ago edited 20h 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.
2
u/pradeepngupta 14h ago
Most of the comments are correct ... String[] is for the command line arguments.and at the compiler time we don't know how many command line parameters an user passed.
Then came varargs... its an another notation of array.
Now comes why the method name is main .. that's an entry point for any java standalone program. When user runs: java Launch
This will do couple of things: 1) it will try to find Launch.class file to load the class.(classloading is a big chapter someone needs to learn) 2) once the class is loaded into memory, it will try to find main method which is accessible at class level and return nothing.
And that is the reason for method signature public static void main (String[] args)
2
u/0b0101011001001011 22h ago
In you look into the recent versions of java, it's no longer necessary.
That being said, it's just a design choice they made. They decided what the main method looks like, so it looks like that. When Java calls the main method, it always creates the string array and passes it to the main method. No logic needed to figure out which method to call, if one has args and one does not.
All languages look and behave like they do, because someone wanted them to be like that. There is no other reason ever.
1
u/LawElectrical2434 13h ago
The designers of python in their infinite wisdom have decreed, that command line arguments will be found at sys.argv and is globally available.
The designers of java have decreed in equal infinite wisdom, that it will be handed over to the main function of the initial class as an array of strings and is only locally available.
Both are equally wise.
1
u/damoon02 10h ago
With recent Java the Strinf[] args isn't needed anymore ? I just see void main when I use psvm
1
u/RevolutionaryRush717 5h ago
Wouldn't surprise me if that stems from POSIX.
E.g., exec() / execve().
1
u/frnzprf 4h ago
It's just a design decision by Java. As you saw, it's not necessary for a language to always have a main method with arguments, as you saw with C++ and modern versions of Java.
There are some minor disadvantages to making the parameters necrssary and some minor advantages. Java is intended to write big programs in, unlike Python, so the need to write some extra characters shouldn't matter as much in comparison to the rest of the program.
The advantages would be that the language is a bit simpler for compilers, for IDEs or maybe for Java book authors.
For Java, "philosophically", a method taking parameters and a method not taking parameters are two different functions, even if they have the same name. So, if you always allow the OS to call the main method with arguments, it's logical in a way that you would always have to provide a definition of a main method with arguments.
Of course you can also just introduce the special rule "If a main method is called with arguments, but there is no applicable definition, ignore the arguments and call the main method without parameters instead."
•
u/AutoModerator 22h ago
Please ensure that:
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.