错误

% javac  StringTest.java 
StringTest.java:4: variable errorSoon might not have been initialized
        errorSoon[0] = "Error, why?";

Code

public class StringTest {
        public static void main(String[] args) {
                String[] errorSoon;
                errorSoon[0] = "Error, why?";
        }
}

当前回答

String[] arr = {"foo", "bar"};

如果你将一个字符串数组传递给一个方法,执行以下操作:

myFunc(arr);

或做的事:

myFunc(new String[] {"foo", "bar"});

其他回答

String[] errorSoon = { "foo", "bar" };

——或——

String[] errorSoon = new String[2];
errorSoon[0] = "foo";
errorSoon[1] = "bar";

您需要初始化errorSoon,正如错误消息所示,您只声明了它。

String[] errorSoon;                   // <--declared statement
String[] errorSoon = new String[100]; // <--initialized statement

在开始设置索引之前,需要初始化数组,以便为String元素分配正确的内存存储空间。

如果你只声明数组(就像你做的那样),没有分配给String元素的内存,只有一个引用句柄给errorSoon,并且当你试图在任何索引处初始化一个变量时将抛出一个错误。

顺便说一句,你也可以在括号内初始化String数组{},

String[] errorSoon = {"Hello", "World"};

这相当于

String[] errorSoon = new String[2];
errorSoon[0] = "Hello";
errorSoon[1] = "World";
String[] args = new String[]{"firstarg", "secondarg", "thirdarg"};

你可以这样写

String[] errorSoon = {"Hello","World"};

For (int x=0;x<errorSoon.length;x++) // in this way u create a for     loop that would like display the elements which are inside the array     errorSoon.oh errorSoon.length is the same as errorSoon<2 

{
   System.out.println(" "+errorSoon[x]); // this will output those two     words, at the top hello and world at the bottom of hello.  
}
String[] string=new String[60];
System.out.println(string.length);

对于初学者来说,这是初始化和获取STRING LENGTH代码的非常简单的方式