关于JAVA引用传递和值传递的题

来源:百度知道 编辑:UC知道 时间:2024/05/20 11:29:22
public class passingDemo{
public void fist(){
xObject o=new xObject();
o.x=5;
int x=5;
changeThem(x,o);
System.out.println();
System.out.println("Back in the original method");
System.out.println("The value of o.x is " + o.x);
System.out.println("But.The value of x is now " + x);

}
public void changeThem(int x,xObject o){
x=9;
o.x=9;
System.out.println("In the changThem method");
System.out.println("The value of o.x is " + o.x);
System.out.println("The value of x is now " + x);

}
public static void main(String args[]){
passingDemo myDemo=new passingDemo();
myDemo.fist();
}
class xObject{
public int x=5;
}
}
输出结果
In the changThem method
The value of o.x is 9
The value of x is now 9

Back in the original method
The v

1. 简单类型是按值传递的

Java 方法的参数是简单类型的时候,是按值传递的 (pass by value)。这一点我们可以通过一个简单的例子来说明:

/* 例 1 */

/**

* @(#) Test.java

* @author fancy

*/

public class Test {

public static void test(boolean test) {

test = ! test;

System.out.println("In test(boolean) : test = " + test);

}

public static void main(String[] args) {

boolean test = true;

System.out.println("Before test(boolean) : test = " + test);

test(test);

System.out.println("After test(boolean) : test = " + test);

}

}

运行结果:

Before test(boolean) : test = true
In test(boolean) : test = false
After test(boolean) : test = true

不难看出,虽然在 test(boolean) 方法中改变了传进来的参数的值,但对这个参数源变量本身并没有影响,即对 main(String[]) 方法里的 test 变量没