简体   繁体   中英

Java public static main()

I am learning Java, theres one thing I do not understand..

in the main routine:

public static void main(String[] args) {

I think I pretty much understand this, in the language I know, I think it would be like this:

public static function main(args:String):void {

The first thing I do not understand is what are the 2 brackets [] for in String[]? Also the second thing I am wondering, is if this is the first function that will be called (and called by something outside the program), will there ever actually be a parameter passed?

Thanks.

The arguments to main are the options you pass into Java from the command line, passed in as an array. So for example :

java MyProgram foo bar zoo

takes three arguments, namely, foo, bar, and zoo

foo is args[0], bar is args[1], and zoo is args[2].

Brackets mean array . Eg String[] is an array of strings. The main() -function is the first function called in your program. It gets called by the JVM .

The values in String[] args are the parameters passed on the command line.

If you call a Java program (main class: FooBar in package foo.bar ) like that:

java foo.bar.FooBar foo bar buz

then, args will like if you built it like that:

String[] args = new String[3];
args[0] = "foo";
args[1] = "bar";
args[2] = "buz";

That is possibly worth reading: A Closer Look at the "Hello World" Application

The brackets mean that it's an array of Strings. And there can be parameters, eg from the command line when your start your application.

It means that you'll get an array of strings. They may be passed via command line

[] stands for array for example String x = "some value"; String[] x = {"value 1","value 2","value 3"};

so in second case x[0] gives "value 1". It is basically an array of strings. Second part is who will call the function? Well this method signature is entry signature and whenever you try to invoke a class with java program, it'll search for this function to start execution; if it doesn;t find it; it'll just give out an error.

Who will pass the vales to String[] array? java someprogram value1 value2 value3

will automatically populate the array with respective three values. So basically the values are populated when it is run from command prompt and values are passed as parameters against the call.

Hope that clears it up

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