我有一个很愚蠢的问题。如果我在主方法中声明String并尝试提取这些String并为它们设置新值主方法中调用的方法。我为什么不能将它们初始化为预期?
public static void main(String[] args) {
//String initialization
String a = null;
String b = null;
String c = null;
String d = null;
//Int initialization
int e = 1;
int f = 2;
int g = 3;
int h = 4;
//List initialization
List<String> list = new ArrayList<String>();
//set different values for the string
setStringValues(a,b,c,d);
//set different values for the int
setIntValues(e,f,g,h);
//adding values to a list
addToList(list);
System.out.println(a + "\n" + b + "\n" + c + "\n" + d);
System.out.println(list);
System.out.println(e + f + g + h);
}
private static void setStringValues(String a, String b, String c, String d){
a = new String("A");
b = "B";
c = "C";
d = "D";
System.out.println(a + "\n" + b + "\n" + c + "\n" + d);
}
private static void setIntValues(int e, int f, int g, int h){
e=10;
f=20;
g=30;
h=40;
System.out.println(e + f + g + h);
}
private static void addToList(List<String> list){
list.add("A");
list.add("B");
list.add(“ C”);}
结果是一个乙Cd100空值空值空值空值[A,B,C]10
使用ClassName.VariableName,即MyClass.a访问类变量,是的,不要忘记将a,b,c,d设为静态。