笔试题--“good and abc”

今天看了一个笔试题,代码如下:
public class Example{ 
  String str=new String("good"); 
  char[]ch={'a','b','c'}; 
  public static void main(String args[]){ 
    Example ex=new Example(); 
    ex.change(ex.str,ex.ch); 
    System.out.print(ex.str+" and "); 
    Sytem.out.print(ex.ch); 
  } 
  public void change(String str,char ch[]){ 
    str="test ok"; 
    ch[0]='g'; 
  } 
} 

其结果是 good and gbc ,为啥 string 没改变而char 改变了呢??

原来是因为:

str是按值传递,所以在函数中对它的操作只生效于它的副本,与原字符串无关。
ch是按址传递,在函数中根据地址,可以直接对字符串进行操作。

str指向的是String类的引用,保存的是地址。当新的“test good ”产生的时候,会在内存中新建String对象,将地址复制给changes方法的str。而ch不会产生新的char数组,直接对原来的数组进行更改。


然后,当原来的程序改下后:

public class StringArrTest {
	String str = new String("good");
	char[] ch = { 'a', 'b', 'c' };
	int[] arr = new int[] { 1, 2, 3 };

	public static void main(String[] args) {
		StringArrTest ex = new StringArrTest();
		ex.changes(ex.str, ex.ch, ex.arr);
		System.out.print(ex.str + "  and  ");
		System.out.print(ex.ch);
		System.out.print(ex.arr[0]);
		// System.out.println(ex.arr);
	}

	public void changes(String str, char ch[], int[] arr) {
		str = "test ok";
		System.out.println("chagne str:" + str);
		ch[0] = 'g';
		System.out.print("change ch :");
		System.out.println(ch);
		arr[0] = 4;
		System.out.print("change arr :");
		System.out.println(arr[0]);
	}
}

打印的结果:

可以看到,输出字符数组和整形数组是不一样的,字符数组会把所有字符输出来,那是因为System.out.print(a);此方法会自动给你解析你的数组,然后打印出来的。而当是整形数组的时候,就会打印出该数组的地址(当然是首地址)。

如果在将

System.out.print(ex.str + "  and  " +ex.ch);

ch也会打印出字符数组的地址,而不会解析数组,依次打印每个字符了。

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值