为什么我有The local variable arcType may not have been initialized错误?
第一宗案件:
String arcType;
if (//somecondition) {
arcType += "Test"; // Here it show the error
System.out.println(arcType);
}但低于正常工作状态。
第二宗案件:
String arcType = null;
if (//somecondition) {
arcType += "Test"; // It's working fine
System.out.println(arcType);
}
Output of the above program : nullTest如果我用space初始化我的space,那么space就会与Test连接。使用修剪空间将删除,但我不想使用修剪。
我的问题是:
The local variable arcType may not have been initialized错误?null初始化字符串时,为什么得到输出nullTest我只想输出Test。
发布于 2016-01-29 09:52:28
默认情况下,只初始化成员和类变量。本地变量不是。
2-只有当传递的对象不是toString()时才隐式调用null。如果是,则打印文字"null"。因此,为了获得"Test"作为输出,需要将字符串初始化为空字符串。
来自文档:Objects#toString()
返回对非空参数调用toString和对空参数调用" null“的结果。
发布于 2016-01-29 09:51:29
然后,您应该插入空:
String arcType = "";在方法内部,所有声明的变量在使用之前都必须初始化。
Null也是一个值,所以当您将字符串引用为null并将其连接时,它将使用null + concate值。
发布于 2016-01-29 09:57:45
+=运算符是s = s + "test"的语法糖。因为最初的s是空的,所以你会得到‘null +’test‘。应该将s初始化为空字符串`
https://stackoverflow.com/questions/35081388
复制相似问题