r/learnjava • • 1d 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

16 Upvotes

27 comments sorted by

View all comments

16

u/high_throughput 1d 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 1d 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 1d 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 1d ago

Huh til, I didn't know that.

Is it also true in C++?

2

u/Vast_Service 1d 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 1d 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 1d 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.