JAVA中的主函数是我们再熟悉不过的了,它是一个很特殊的函数,那它为什么这么写,其中的每个关键字分别是什么意思呢?
main函数详解
public static void main(String args[])
main函数,是主函数,被jvm调用,是程序运行的入口。Java虚拟机不会调用你自己写的普通的函数。
String args[]是什么东西?
这个参数是jvm传给main函数的参数,或者程序使用者也可以在命令行状态下与程序交互给main传递参数。例如:java HelloWorld ceshi,意思就是给HelloWorld这个类的main函数传递参数ceshi。多个的话用空格隔开,比如java HelloWorld ceshi ceshi1 ceshi2。此外在其他类中直接使用main()函数,并传递参数也是可行的,虽然这种方法不太常用,但毕竟为我们提供了一种选择。
例子:
class Test
{
public static void main(String[] args)
{
String foo=args[1]; //Green
String bar=args[2]; //Blue
String baz=args[3]; //越界
}
}
d:\>java Test Red Green Blue
what is the value of baz?
A. baz has value of ""
B. baz has value of null
C. baz has value of "Red"
D. baz has value of "Blue"
E. baz has value of "Green"
F. the code does not compile
G. the program throw an exception
答案是G
类的初始化执行流程