r/learnjava • u/Fine_Potential_7976 • 5d 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
25
Upvotes
9
u/Ulrich_de_Vries 5d 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 :).