栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java String 类型参数传递理解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java String 类型参数传递理解

Java String 类型参数传递理解

String里面除了hash这个参数不是final类型的之外,其余参数都是final类型的,String本质上是char[]数组的包装类,所以牵扯到内容变化的函数最后返回String类型的时候都是重新new了一个新的String类型出来,这跟原来传入的String参数就没什么关系了。
因此,我认为,当String作为参数传递时,确实是以地址传递过去的,但是在对String类型的变量的值进行改变时,由于String类的值是常量,在创建后不能更改,所以对String参数进行操作,相当于new String(),已经改变了String对象的地址了,所以实参不会改变。

public class TestString {

    public static void main(String[] args) {
        String s1 = new String("abc");
        System.out.println("在main方法中s1的地址:" + String.class.getName() + 
                "@" + Integer.toHexString(System.identityHashCode(s1)));
        String s2 = new String("xyz");
        System.out.println("在main方法中s2的地址:" + String.class.getName() + 
                "@" + Integer.toHexString(System.identityHashCode(s2)));
        show(s1, s2);
        System.out.println(s1 + "-----" + s2);
        System.out.println("在main方法中运行过show方法后s1的地址:" + String.class.getName() + 
                "@" + Integer.toHexString(System.identityHashCode(s1)));
        System.out.println("在main方法中运行过show方法后s2的地址:" + String.class.getName() + 
                "@" + Integer.toHexString(System.identityHashCode(s2)));
    }

    static void show(String s1, String s2) {
        s1 = s2 + s1 + "Q";
        System.out.println("在show方法中s1的地址:" + String.class.getName() + 
                "@" + Integer.toHexString(System.identityHashCode(s1)));
        s2 = "W"+s1;
        System.out.println("在show方法中s2的地址:" + String.class.getName() + 
                "@" + Integer.toHexString(System.identityHashCode(s2)));
    }
}

运行结果:
在main方法中s1的地址:java.lang.String@1b6d3586
在main方法中s2的地址:java.lang.String@4554617c
在show方法中s1的地址:java.lang.String@74a14482
在show方法中s2的地址:java.lang.String@1540e19d
abc-----xyz
在main方法中运行过show方法后s1的地址:java.lang.String@1b6d3586
在main方法中运行过show方法后s2的地址:java.lang.String@4554617c

run可以发现,在show方法中,新new了s1和s2对象,和实参的地址已经不一样了。
Java打印String对象的地址参考自:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/874134.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号