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, 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.

1 comment:

  1. Play Blackjack on the internet: how to play the casino and - DrMCD
    Blackjack 대구광역 출장샵 is not the only card game 광양 출장안마 that you have to 대전광역 출장안마 play. 경산 출장샵 Learn the rules of Blackjack, 서귀포 출장마사지 and try different table variants like Bridge, Stud Poker,