值传递与引用传递 --------- 错题分析

//given the following code,what will be the output?  A

class Value{
    public int i=15;
}
public class Test{
    public static void main(String argv[]){
        Test t=new Test( );
        t.first( );
    }

   public void first( ){
      int i=5;//局部变量i = 5;注意这个i是局部变量
      Value v=new Value( );
      v.i=25;//创建了一个value对象,并把这个对象i的值赋值为25
      second(v,i);//v(v中的属性值为25)和局部变量i=5传进second方法
      System.out.println(v.i);//v的属性i在second函数中被改为了20
   }


   public void second(Value v,int i){
     i = 0;//second方法的局部变量,与之前的i没有关系
     v.i = 20;//将传进来的V中的属性i的值改为20
     Value val = new Value( );
     v = val;//新创建的Value对象val,属性i值为15,并将v指向val对象,
             //v已经和之前传进来的对象没关系了
     System.out.println(v.i+" "+i);//此时v的属性i为15,先输出 15(v.i) 0(i)
   }
}
A15 0 20
B15 0 15
C20 0 20
D0 15 20

//给出以下代码,请给出结果. B
class Two{
    Byte x;
}
class PassO{
    public static void main(String[] args){
        PassO p=new PassO();
        p.start();
    }
    void start(){
        Two t=new Two();
        System.out.print(t.x+””);
        Two t2=fix(t);
        System.out.print(t.x+” ” +t2.x);
    }
    Two fix(Two tt){
        tt.x=42;
        return tt;
    }
}
Anull null 42
Bnull 42 42
C0 0 42
D0 42 42
EAn exception is thrown at runtime
FCompilation

在这里插入图片描述

//指出下列程序运行的结果 ()

public class Example {
    String str = new String("good");
    char[] ch = { 'a', 'b', 'c' };
    public static void main(String args[]) {
        Example ex = new Example();
// ex.str叫实参
        ex.change(ex.str, ex.ch);
        System.out.print(ex.str + " and ");
        System.out.print(ex.ch);

    }

     // str叫形参
    public void change(String str1, char[] ch1) {
        str1 = "test ok";
        ch1[0] = 'g';
    }
}

A、 good and abc
B、 good and gbc
C、 test ok and abc
D、 test ok and gbc 

答案:B

在这里插入图片描述
在这里插入图片描述
解析:大家可能以为Java中String和数组都是对象所以肯定是对象引用,然后就会选D,其实这是个很大的误区:因为在java里没有引用传递,只有值传递,引用数据类型传递的是地址值,
把实参的地址值赋值给形参,实参和形参通过地址值指向同一个对象,你可以通过它修改这个地址的内容(引用不变),因为此时这个内容的地址和原地址是同一地址

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值