我有一个创建String
的方法和另一个更改字符串的方法
void create(){
String s;
edit(s);
System.out.println(s);
}
void edit(String str){
str = "hallo";
}
我的编译器说它"可能尚未初始化"。
有人可以解释一下吗?
变量可能尚未初始化
当你在方法中定义s
时,你必须在其中的某个地方初始化s
程序中的每个变量在使用其值之前都必须有一个值。
另一件事同样重要,你的代码永远不会像你预期的那样工作,因为java 中的字符串是不可变的,因此您无法编辑字符串,因此您应该更改方法edit(Str s)
。
我将您的代码更改为类似的东西,但我认为您的编辑方法应该做另一件事而不是返回"hallo"。
void create(){
String s=null;
s =edit(); // passing a string to edit now have no sense
System.out.println(s);
}
// calling edit to this method have no sense anymore
String edit(){
return "hallo";
}
在这个著名的问题中阅读更多关于java是按值传递的信息:Java是"通过引用传递"吗?
请参阅这个简单的示例,其中显示了 java 是按值传递的。我不能只用字符串做一个例子,因为字符串是不可变的。所以我创建了一个包装类,其中包含一个可变的字符串以查看差异。
public class Test{
static class A{
String s = "hello";
@Override
public String toString(){
return s;
}
}
public static void referenceChange(A a){
a = new A(); // here a is pointing to a new object just like your example
a.s = "bye-bye";
}
public static void modifyValue(A a){
a.s ="bye-bye";// here you are modifying your object cuase this object is modificable not like Strings that you can't modify any property
}
public static void main(String args[]){
A a = new A();
referenceChange(a);
System.out.println(a);//prints hello, so here you realize that a doesn't change cause pass by value!!
modifyValue(a);
System.out.println(a); // prints bye-bye
}
}
在方法 create
中声明局部变量s
,因此您需要在使用它之前对其进行初始化。请记住,java 没有局部变量的默认值。Init String s = ""
或任何比您的代码更值的值将正常运行。
字符串"s"初始化为空值,因为您已经声明了一个变量"s",但它尚未初始化。因此,它在用作参数时无法传递该变量的引用。
String s = null;
希望这有帮助
给你的变量 S 一个值,或者像 Jeroen Vanneve 所说的那样"把它改成字符串 s = null;"