Can someone imagine when this code:
public static void main(final String[] args) {
// do something
}
should become this:
public static void main(final String[] args) {
String[] argsCopy = doCopy(args);
// do something
}
(In our company we have a Sonar rule that forces such coping or arguments for all methods.) I can imagine why it can be important for standard methods, but I cannot find any benefit of having it done at a start of tools main method. Am I missing something?
Command-line arguments in Java are used to pass arguments to the main program. If you look at the Java main method syntax, it accepts String array as an argument. When we pass command-line arguments, they are treated as strings and passed to the main function in the string array argument.
It stores Java command-line arguments and is an array of type java. lang. String class. Here, the name of the String array is args but it is not fixed and the user can use any name in place of it.
You can write the public static void main() method with arguments other than String the program gets compiled. Since the main method is the entry point of the Java program, whenever you execute one the JVM searches for the main method, which is public, static, with return type void, and a String array as an argument.
It won't execute since that's what the language's designers decided.
I can imagine quite a bit, the two most obvious (to me) are:
main
as a "normal" method, e.g., not just called from the command lineIn general, though, it's not super-useful in this case.
The reason you copy array parameters is to avoid a possibility of someone modifying the array once you have validated its elements. This is a very good defensive technique, which protects you from malicious calls in a caller.
However, in this case the caller is JVM itself. If you do not trust JVM to be free of malicious code, you have a much larger problem than something that could be solved by copying an array.
The only exception is when you pass args
to some of your functions. In this case, making a copy is a very good idea, in case some method decides to change the content of the args
. That's the only case when I would recommend making a copy. If main
is the only place where args
is used, making a copy is not necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With