Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

should MAIN method copy input arguments?

Tags:

java

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?

like image 375
dantuch Avatar asked Sep 23 '14 17:09

dantuch


People also ask

Can we pass arguments to the main method?

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.

Why do we pass String args in main method?

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.

Can we have main () method defined without String args [] parameter?

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.

Will the program run if we write main String [] args instead of main String [] args?

It won't execute since that's what the language's designers decided.


2 Answers

I can imagine quite a bit, the two most obvious (to me) are:

  • If you modify them but still need to refer to the original values
  • If you use main as a "normal" method, e.g., not just called from the command line

In general, though, it's not super-useful in this case.

like image 31
Dave Newton Avatar answered Oct 17 '22 11:10

Dave Newton


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.

like image 189
Sergey Kalinichenko Avatar answered Oct 17 '22 12:10

Sergey Kalinichenko