In java, as per the Java Language Specification 12.1.4 the main method should be declared as follows:
public static void main(String[] args){
//code of program
}
With the use of String[] args we can get command-line arguments. Sometime those command-line arguments needs to be converted to appropriate type. suppose if you have supplied any number 123 as an argument and you want to convert it to int then we can use one of the following conversion methods:
int n1=Integer.valueOf(args[0]);
//or
int n2=Integer.parseInt(args[0]);
But, if java could have provided use of Objects[] args instead String[] args then we can easily convert from one type to another, for this example conversion would take place as follows:
public static void main(Object[] args){
int n1=(Integer)args[0];
}
I'm not getting this why java have used String[] args and not Object[] args?
Java is designed with portability in mind, so that Java programs would be invoked by diverse operating environments. Having the environments pass Java objects to main would put too much restrictions on the caller system, because that system would have a task of "understanding" the input and converting it to Java objects.
Strings, on the other hand, are universal: all operating environments have them. Therefore, Java specification required strings, knowing that your Java program would be able to process and understand them better than an external environment.
This is simple because the args came from outside java environment, it is from the Operating System and as such it can't create Java Objects it can only pass Strings
To call a java program from a console it would be something like:
c:\java MyProgram 123
There is no way to java know that the OS is passing an object it is just a string.
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