Monday, March 02, 2015

Why are the arguments for a Java main function a string type?

Why only String and not an Integer or a float?
The inputs from the console and the output to the console are always of the type String. 

Consider this example



When you compile a program from the console by executing the 'javac' (Java Compiler), followed by the program name, myProgram.java in this case, the name is paased to the javac application as a string. 
The compiler accepts the name of the program to be compiled as a string and creates a .class file post compilation.

Similarly, whenever you run the application from the console, it might be required that the main function needs some parameter to be passed by the user that would be required during execution.


  1. The situation might require that the user must pass some value to the program even before the execution of the main function starts.
    the example of a compiler I just gave justifies that such situations are possible.
  2. Any input taken from the console and any output printed to the console is ALWAYS of the type String.
  3. Hence, when  I write "stringParameterPassed" next to the program name, this is passed as a String to the main function.
    Therefore, to receive this String, there needs to be a String variable in the main function.

    But why do we a String array to receive that?
  4. There are also situations when the main function may require more than one parameter. 
    So, we use a String array instead of just a String  variable.

    public static void main(String[ ] args)
    {

    }
  5. In this case multiple parameters can be passed to the main function separated by a space in between them.
    Each of them will be stored as different elements of the string array.

Originally answered on Quora.

No comments:

Post a Comment