C语言有值传递与地址传递之分,java的参数传递实际上都应该是值传递。(当一个对象实例作为一个参数被传递到方法中时,参数的值就是该对象的引用一个副本。指向同一个对象,对象的内容可以在被调用的方法中改变,但对象的引用(不是引用的副本)是永远不会改变的。)
C:
#include<stdio.h>
void exchange1(int x,int y);
void exchange2(int *x,int *y);
int main()
{
int x=5;
int y=10;
exchange1(x,y);
printf("x=%d y=%d\n",x,y);
exchange2(&x,&y);
printf("x=%d y=%d\n",x,y);
return 0;
}
void exchange1(int x,int y)
{
x+=y;
y=x-y;
x-=y;
}
void exchange2(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
output:
x=5 y=10
x=10 y=5
java:
public class Employee {
String name;
public Employee(String name) {
this.name=name;
}
public void setName(String name) {
this.name=name;
}
public String toString() {
return "Employee:"+name;
}
}
public class Test {
public static void main(String[] args) {
int x=5;
int y=10;
Employee e1=new Employee("tom");
Employee e2=new Employee("jack");
change1(x,y);
System.out.println("x="+x+" "+"y="+y);
change2(e1,e2);
System.out.println(e1+" "+e2);
change3(e1,e2);
System.out.println(e1+" "+e2);
}
public static void change1(int x,int y) {
int temp;
temp=y;
y=x;
x=temp;
}
public static void change2(Employee e1,Employee e2) {
Employee e;
e=e1;
e1=e2;
e2=e;
}
public static void change3(Employee e1,Employee e2) {
e1.setName("jack");
e2.setName("tom");
}
}
output:
x=5 y=10
Employee:tom Employee:jack
Employee:jack Employee:tom