Thursday 4 May 2017

Why String[] args in main() method in JAVA?

The main objective is designed very intelligently by developers. Actual thinking is very deep. Which is basically developed under consideration of C & C++ based on Command line argument but nowadays nobody uses it more.
Thing 1- User can enter any type of data from the command line can be Number or String & necessary to accept it by the compiler which datatype we should have to use?
Thing 2- String is the datatype which supports all of the primitive datatypes like int, long, float, double, byte, shot, char in Java. You can easily parse it in any primitive datatype.
let's see the following example, 
If input is -> 1 1
// one class needs to have a main() method
public class HelloSilan
{
  // arguments are passed using the text field below this editor
  public static void main(String[] x)
  {   
System.out.println(x[0] + x[1]); // Output is 11

//Comment out below code in case of String
    System.out.println(Integer.parseInt(parameter[0]) + Integer.parseInt(parameter[1])); //Output is 2
    System.out.println(Float.parseFloat(parameter[0]) + Float.parseFloat(parameter[1])); //Output is 2.0   
    System.out.println(Long.parseLong(parameter[0]) + Long.parseLong(parameter[1])); //Output is 2   
    System.out.println(Double.parseDouble(parameter[0]) + Double.parseDouble(parameter[1])); //Output is 2.0   

  }

}

No comments:

Post a Comment