Java中传值和传址的问题

来源:互联网 发布:淘宝网店开店培训班 编辑:程序博客网 时间:2024/05/22 02:06

Java中取消了指针,不可能像C一样直接操作内存,但是由于对象的动态联编性,复杂数据类型作参数相当于指针的使用,即地址传递,而基本数据类型作参数传递则相当于值传递.看下面程序:

class swapByValue
{
 int x,y;
 public swapByValue (int x, int y)
 { 
  this.x=x;
  this.y=y; 
 }
 public void swap(int x,int y)
 {
  int z;
  z=x; x=y; y=z;
  System.out.println(x);
  System.out.println(y);
  this.x=x;  //没有这两句,结果就不能成功,因为int是基本数据类型,传的是值
  this.y=y;
 }
 public static void main(String args[])
 {
  swapByValue s= new swapByValue (3,4);
  Transcript.println("Before swap: x= "+s.x+" y= "+s.y);
  s.swap(s.x,s.y);
  Transcript.println("After swap: x= "+s.x+" y= "+s.y);}
 }

原创粉丝点击