Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String[] args in main

Tags:

java

arguments

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.

like image 847
SimpleCoder Avatar asked Sep 15 '26 02:09

SimpleCoder


2 Answers

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.

like image 70
Andrew Tobilko Avatar answered Sep 17 '26 16:09

Andrew Tobilko


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)
like image 43
androholic Avatar answered Sep 17 '26 15:09

androholic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!