您是否需要=数组中的new String []?

时间:2018-11-01 10:33:37

标签: java arrays

Label3

String[] months = {"January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

System.out.println(Arrays.toString(months));

这两个代码给出了相同的结果。所以我想知道哪种写法是合适的。

1 个答案:

答案 0 :(得分:4)

String[] arr = { "Alpha", "Beta" };

String[] arr = new String[] { "Alpha", "Beta" };

做完全一样的事情。第一个是快捷方式,当您声明数组变量并将其初始化在同一行中时,可以使用该快捷方式。

但是,在其他情况下,必须使用new String[]声明要创建的数组的类型。

String[] arr;
arr = { "Alpha", "Beta" }; // this will not compile
arr = new String[] { "Alpha", "Beta" }; // this will compile
相关问题