zoukankan      html  css  js  c++  java
  • Java中创建String的两种方式

    1、在Java中,创建一个字符串有两种方式

    String x = "abc";
    String y = new String("abc");

    这两种方式有什么区别呢?

    2、双引号("")和构造器

    第一个案例:

    String a = "abcd";
    String b = "abcd";
    System.out.println(a == b); // True
    System.out.println(a.equals(b)); // True

    a==b为真,是因为a和b都指向了方法区里面的同一个字符串,引用值相等;

    当相同的字符串被创建多次,内存中只保存一份字符串常量值,这就是字符串的"驻留"

    第二个案例:

    String c = new String("abcd");
    String d = new String("abcd");
    System.out.println(c == d); // False
    System.out.println(c.equals(d)); // True

    c==d 为假,是因为c和d引用了对内存中的两个不同的对象,不同的对象,引用值肯定不同

    3、运行时字符串的驻留

    字符串同样可以在运行时"驻留"

    String c = new String("abcd").intern();
    String d = new String("abcd").intern();
    System.out.println(c == d); // Now true
    System.out.println(c.equals(d)); // True

    4、选择哪一种方式来创建字符串呢?

    因为"abcdef"也是String类型,使用构造器会创建额外的不需要的对象,因此,如果你只想创建一个字符串,就是用双引号("")方式;

    如果你在对内存还想创建一个字符串对象,就是用构造器的方式

  • 相关阅读:
    deepin/uos和局域网其他机器无法ping通
    Ubuntu18.04完全卸载vscode
    批量拉取github组织或者用户的仓库
    vmware uos挂载windows共享目录
    清空容器另类方式
    time_t 时间格式化字符串
    条件变量condition_variable
    C++多维堆数组定义
    arm64 ubuntu18.04 bionic安装bcc tools
    win10下载编译chromium
  • 原文地址:https://www.cnblogs.com/lianliang/p/5326294.html
Copyright © 2011-2022 走看看