一个有关静态方法的问题
package test4;
public class Test {
public static void data(int x , int y) {
x = 4;
y = 5;
}
public static void data(Integer x , Integer y) {
x = 8;
y = 9;
}
public static void data(String s) {
s = new String("world");
}
public static void main(String[] args) {
int a = 2;
int b = 3;
data(a,b);
System.out.println(a);
System.out.println(b);
Integer c = 2;
Integer d = 3;
data(c,d);
System.out.println(c);
System.out.println(d);
String s = "hello";
data(s);
System.out.println(s);
}
}
这个程序的输出是:
2
3
2
3
hello
这显然和我预料的输出:
2
3
8
9
world
不一样,求高手解答
[最优解释]
还是老问题。
方法内的是局部变量,局部变量的变化不会影响传入到方法的参数的值。
[其他解释]
这个跟java变量的传递类型有关系,java只有值传递这一种类型,不存在引用传递(好像c语言,有这个,不清楚)。通过希望通过方法改变变量的引用,显然是不可行的,也是错误的。
[其他解释]
你看一下这个代码:
public class TestStatic {
public static void data(int x , int y) {
x = 4;
y = 5;
System.out.println(x);
System.out.println(y);
}
public static void data(Integer x , Integer y) {
x = 8;
y = 9;
System.out.println(x);
System.out.println(y);
}
public static void data(String s) {
s = new String("world");
System.out.println(s);
}
public static void main(String[] args) {
int a = 2;
int b = 3;
data(a,b);
System.out.println(a);
System.out.println(b);
Integer c = 2;
Integer d = 3;
data(c,d);
System.out.println(c);
System.out.println(d);
String s = "hello";
data(s);
System.out.println(s);
}
}
这个代码可以实现你的要求:
public class TestStatic {
public static void data(int x , int y) {
x = 4;
y = 5;
System.out.println(x);
System.out.println(y);
}
public static void data(Integer x , Integer y) {
x = 8;
y = 9;
System.out.println(x);
System.out.println(y);
}
public static void data(String s) {
s = new String("world");
System.out.println(s);
}
public static void main(String[] args) {
int a = 2;
int b = 3;
data(a,b);
// System.out.println(a);
//System.out.println(b);
Integer c = 2;
Integer d = 3;
data(c,d);
// System.out.println(c);
//System.out.println(d);
String s = "hello";
data(s);
// System.out.println(s);
}
}
在你的代码中:在定义方法中中的局部变量,局部变量的变化不会受传入到方法的参数的值的影响,除非你在调用的方法中也有输出语句。
[其他解释]
java跟c语言一样都是值传递吗,不是引用传递?
[其他解释]
java也是值传递,你也可以返回这个值。。
[其他解释]
言简意赅
[其他解释]
在 C#中 有值传递 并且得使用ref关键字
