zoukankan      html  css  js  c++  java
  • 值传递 & 引用传递

    以下程序的输出结果是?

     1 public class Example {
     2     String str = new String("good");
     3     char[] ch = { 'a', 'b', 'c' };
     4  
     5     public static void main(String args[]) {
     6         Example ex = new Example();
     7         ex.change(ex.str, ex.ch);
     8         System.out.print(ex.str + " and ");
     9         System.out.print(ex.ch);
    10     }
    11  
    12    public void change(String str, char ch[])      
    13    {
    14         str = "test ok";
    15         ch[0] = 'g';
    16     }
    17 }

    正确答案: B   

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

    解析:
    考察值传递和引用传递。对于值传递,拷贝的值用完之后就会被释放,对原值没有任何影响,但是对于引用传递,拷贝的是对象的引用,和原值指向的同一块地址,即操作的是同一个对象,所以操作之间会相互影响
    所以对于String str是值传递,操作之间互不影响,原值保持不变。而ch是数组,拷贝的是对象的引用,值发生了改变,因此选择B
  • 相关阅读:
    《架构真经》读后感2
    css的引入
    交流会发言
    css学习
    数据结构-哈希表、二叉排序数
    软工人学习日常
    Java包、类、方法、变量、常量命名规范
    数据库命名规范
    学生信息系统jsp界面
    学生信息系统servlet层
  • 原文地址:https://www.cnblogs.com/UniqueColor/p/5452958.html
Copyright © 2011-2022 走看看