简体   繁体   中英

String[] args in main

Can some one tell , why args in main method are of String type . in

public static void main(String args[]){
}

I mean, why it is not int or float or something else. I was asked the same but could not find appropriate answer.

You might run your java program with parameters through console like this:

java YourClass first second third

In the java program you may use it through String args[] .

public static void main(String[] args) {
    Arrays.asList(args).forEach(System.out::println);
}

Output:

first
second
third

But it is not necessary to use such name. There are few ways to declare signature of the main method:

public static void main(String... args)
public static void main(String[] strings)
public static void main(String [] args)

Why it is not int or float or something else? At the command prompt the command is considered to be a string .

I will give you my inputs.

  1. Command line arguments are Strings which is why that is the data type.
  2. You can get other datatypes easily from Strings.
  3. Most of Java's syntax is based on C, and since C used String args, maybe the creators did the same for java. (Just a possibility)

when we write java filename.java that means you giving your filename to java compiler whose main method is to be called it is obvious that the file name you are giving will be a string.

on the other end if you want to give any parameter to compiler at the same time it will also be in string not an integer or any other data type.

Because String can be converted to any type easily. If it were int and you want to take double as input, how would this happen? But with String, you can convert to whatever you expect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM