java学习----基础类型与引用

来源:互联网 发布:舞台交互制作软件 编辑:程序博客网 时间:2024/06/05 11:44

首先来看一个例子:

public class B   
    String str = new String("good");    char[] ch = {'a','b','c'};    int i = 123;    public static void main(String[] args) {        B ex = new B();        ex.change(ex.str, ex.ch,ex.i, ex);        System.out.print(ex.str +" and " );        System.out.print(ex.ch);        System.out.print(" and "+ex.i);    }    public void change(String str, char chx[], int i,B b){        str= "test ok";//str= new String("test ok"),结果一样        chx[0] = 'g';        i = 111;        b = new B();//语句1        b.i = 100;    }
}
结果是:good and gbc and 123

传递的参数,

对一般的基础类型:byte、short、int、long、float、double、char、boolean,传递的是基本类型的字面值得拷贝

引用类型:对象、数组、接口,传递的是所引用的对象在堆中地址值得拷贝。

特殊,对于String,尽管是对象,它是不可变的,每一次赋值都会创建新的空间

假如是类似语句1中这种方式,会给b重新创新一个空间,不再是ex的地址

0 0