r/learnjava • u/Fine_Potential_7976 • 10d 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
21
u/high_throughput 10d ago
or c++
In C++ you use int main(int argc, char** argv) and that's the same as String[]
10
u/Ulrich_de_Vries 10d 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 :).
2
u/Vast_Service 10d 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 10d ago
Huh til, I didn't know that.
Is it also true in C++?
2
u/Vast_Service 10d 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 10d 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 10d 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.
1
u/Underhill42 6d ago
C++ does not have a string class, the STL recently added a std:string class to that library, and countless unrelated versions exist in other libraries predating the STL's existence. And many others that still exist that make different compromises, or as part of much larger libraries that couldn't be bothered to completely re-write everything string related for no benefit.
But the core C++ language has no idea what a string is, it only deals with character arrays, just like C.
1
u/Vast_Service 5d ago
I am not sure what your post was in response to but it is factually incorrect in so many ways.
C++ does have a string class. The standard library (it is no longer called STL btw. The days of Alexander Stepanov are over) is a part of the C++ standard and hence std::string is also a part of the standard and hence it is incorrect to say that C++ does not have a string class.
I never said that std::string is a built in.
What do you mean by Core C++, now that the standard library is also a part of the C++ standard? Did you again just mean that std::string is not a builtin? It is not, but, why is that in any way related to my previous post?
41
u/shauntmw2 10d 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.
1
u/cainhurstcat 10d ago
How/where does one learn something like that?
28
u/0zeronegative 10d ago
It’s not even java-specific. All languages follow this convention because it is one of the earliest unix conventions and it stuck.
6
2
u/jlanawalt 10d 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
0
u/duane11583 8d ago
and the basic os has no idea what the variable types of the language are.
what it does know is the opcodes and start function.
that function is not main() it is something else.
often found in the file crt0.s sometimes the symbol is called start or _main it varies
that files job is to initialize any language specific things and call the language specific entry function. in C those things are the malloc() library and stdin, stdout etc. when done it calls the function main()
you can replace the etire crt0.s file if you want
just know that many language nerds do not do that why bother… and often their bottom level runtime code things that open/close files are often wrappers into the standard c library functions so they must in the end use the standard c library and it must be initialized.
but they are lazy and just let the standard c library go through its start up code and then call main() in their main function they create the interpreter and call the language specific entry function. in the language specific way.
but yea they could replace all of that… good luck it is a hell of a lot of work they just avoid
3
u/vegan_antitheist 10d ago
They are not necessary in the latest version and you could always just use String... Instead of String[].
2
u/ITCoder 10d ago
varargs in String ... are synthetic sugars and create array behind the scene
1
u/vegan_antitheist 10d 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
6
u/0b0101011001001011 10d 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.
2
u/American_Streamer 10d ago edited 10d 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 10d 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)
1
u/LawElectrical2434 10d 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 10d ago
With recent Java the Strinf[] args isn't needed anymore ? I just see void main when I use psvm
1
u/RevolutionaryRush717 10d ago
Wouldn't surprise me if that stems from POSIX.
E.g., exec() / execve().
1
u/frnzprf 10d 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."
1
•
u/AutoModerator 10d 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.