Java: how to initialize String[]?(Java:如何初始化 String[]?)
问题描述
错误
% javac StringTest.java
StringTest.java:4: variable errorSoon might not have been initialized
errorSoon[0] = "Error, why?";
代码
public class StringTest {
public static void main(String[] args) {
String[] errorSoon;
errorSoon[0] = "Error, why?";
}
}
推荐答案
你需要初始化 errorSoon
,如错误消息所示,您只有 声明了.
You need to initialize errorSoon
, as indicated by the error message, you have only declared it.
String[] errorSoon; // <--declared statement
String[] errorSoon = new String[100]; // <--initialized statement
您需要初始化数组,以便它可以为 String
元素分配正确的内存存储在您可以开始设置索引之前.
You need to initialize the array so it can allocate the correct memory storage for the String
elements before you can start setting the index.
如果您仅声明数组(如您所做的那样),则不会为 String
元素分配内存,而只有 errorSoon的引用句柄code>,并且当您尝试在任何索引处初始化变量时将引发错误.
If you only declare the array (as you did) there is no memory allocated for the String
elements, but only a reference handle to errorSoon
, and will throw an error when you try to initialize a variable at any index.
作为旁注,您还可以在大括号内初始化 String
数组,{ }
就是这样,
As a side note, you could also initialize the String
array inside braces, { }
as so,
String[] errorSoon = {"Hello", "World"};
相当于
String[] errorSoon = new String[2];
errorSoon[0] = "Hello";
errorSoon[1] = "World";
这篇关于Java:如何初始化 String[]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java:如何初始化 String[]?
基础教程推荐
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 降序排序:Java Map 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01