java String type传值

一般大家都清楚primitive type传值的话,不会改变原有值。
For example:
public class TestPrimitiveType {
int original = 9;

int[] arr = {1, 2, 3};

public static void main(String args[]) {
TestPrimitiveType ti = new TestPrimitiveType();
ti.change(ti.original, ti.arr);
System.out.print(ti.original + " and ");
System.out.println(ti.arr[0] + " " + ti.arr[1] + " " + ti.arr[2]);
}

public void change(int original, int[] arr) {
original = 100;
arr[0] = -1;
}
}

输出: 9 and -1 2 3

再测试一下它的wrapper类:
public class TestInteger {
Integer obj = new Integer(9);

Integer[] arr = {1, 2, 3};

public static void main(String args[]) {
TestInteger ti = new TestInteger();
ti.change(ti.obj, ti.arr);
System.out.print(ti.obj + " and ");
System.out.println(ti.arr[0] + " " + ti.arr[1] + " " + ti.arr[2]);
}

public void change(Integer obj, Integer[] arr) {
obj = 100;
arr[0] = -1;
}
}

输出: 9 and -1 2 3,跟它的primitive type一样,并没有在调用change方法后改变其值。

测试一下String类也一样。
public class TestString {
String obj = new String("not changed");

char[] arr = {'a', 'b', 'c'};

public static void main(String args[]) {
TestString ts = new TestString();
ts.change(ts.obj, ts.arr);
System.out.print(ts.obj + " and ");
System.out.println(ts.arr);
}

public void change(String obj, char[] arr) {
obj = "changed";
arr[0] = 'w';
}
}

输出: not changed and wbc,因为String是final class,而且在java方法中String类的调用占80%,因此java对String类做了特殊处理,当String值传递到change方法时,你可以理解为其实是传递了一个拷贝过去,拷贝的obj指向新创建的字符串"changed",但并不改变原有obj的指向。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值