java面试宝典-传值和传引用

来源:互联网 发布:商机助理怎么传淘宝 编辑:程序博客网 时间:2024/06/10 09:26

      对于基本类型变量,java是传值的副本,对与一切对象型变量,java都是传引用的副本。

      参数类型是简单类型的时候,是按值传递,实际上是将参数的值作为一个副本传进方法函数的,那么在方法函数中不管怎么改变其值,其结果都是只改变了副本的值,而不是源值。

      java方法参数传对象,传的是对这个对象引用的一份副本,即地址值,跟原来的引入都是指向同一个对象。

      下面例子是学习java面试宝典里面的小例子,拿来记录参考。

      简单类型的值传递:

public class Test1 {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 test)方法中改变了传进来的参数值,但对这个参数源变量本身并没有影响,即对main方法里面的test变量没有影响,说明参数类型是简单类型的时候,

是按值传递的。实际上是将参数的值作为一个副本传进方法函数的,那么在方法函数中不管怎么改变其值,其结果都是只改变了副本的值,而不是源值。


引用对象传递:

//引用对象传递public static void test(StringBuffer str) {str.append(",world");}public static void main(String[] args) {StringBuffer string  = new StringBuffer("Hello");test(string);System.out.println(string);}

分析:test(String)调用了test(StringBuffer str)方法,并将string作为参数传递了进去。这里的string是一个引用,java对于引用形式传递对象类型的变量时,实际上是将引用作为一个副本传进方法函数的。那么这个函数里面的引用副本所指向的是什么呢?是对象的地址。通过引用副本(复制的钥匙)找到地址(仓库)并修改地址中的值,也就是修改了对象。

对比简单类型值传递:

//简单类型值传递public static void test(String str) {str = str +",world";}public static void main(String[] args) {String string  = new String("Hello");test(string);System.out.println(string);}

案例题:

class Value {public int i = 15;}public class Test {public static void main(String[] args) {Test t = new Test();t.first();}private void first() {        int i = 5;        Value v = new Value();        v.i = 25;        second(v,i);        System.out.println(v.i);}private void second(Value v, int i) {i = 0;v.i = 20;Value val = new Value();v = val;System.out.println(v.i + "  " + i);}}

输出:

15  0
20


0 0
原创粉丝点击