zoukankan      html  css  js  c++  java
  • String

    原文:http://blog.csdn.net/pwair/article/details/654284

    常量池(constant pool):指的是在编译期被确定,并被保存在已编译的.class文件中的一些数据。它包括了关于类、方法、接口等中的常量,也包括字符串常量。 

    Java确保一个字符串常量只有一个拷贝。因此:

    public static void main(String[] args) {
      String a = "Hello";
      String b = "Hello";
      System.out.println(a == b);
    }
    结果: true

    同理:
    public static void main(String[] args) {
      String a = "Hello";
      String b = "He" + "llo";
      System.out.println(a == b);
    }
    结果: true

    例1中的a和b中的”Hello”都是字符串常量,它们在编译期就被确定了,所以a == b结果为true;
    例2中的”He”和”llo”也都是字符串常量,当一个字符串由多个字符串常量连接而成时,它自己也是字符串常量,所以b也同样在编译期就被解析为一个字符串常,所以b也是常量池中”Hello”的一个引用。  


    public static void main(String[] args) {
      String a = "Hello";
      String b = new String("Hello");
      String c = "He" + new String("llo");
      System.out.println(a == b);
      System.out.println(a == c);
      System.out.println(c == b);
    }
    结果:
    false
    false
    false

    例3中的a仍旧是常量池中的常量“Hello”的引用。b因为无法在编译期确定,所以是运行时创建的新对象"Hello“的引用。c也因为new String("llo")而无法在编译期被确定。

    =================================================================================

    String.intern():  
      存在于.class文件中的常量池,在运行时被JVM装载,并且可以扩充。String的intern()方法就是扩充常量池的一个方法;当一个String实例str调用intern()方法时,Java查找常量池中是否有相同Unicode的字符串常量,如果有,则返回其的引用,如果没有,则在常量池中增加一个Unicode等于str的字符串常量并返回它的引用;

    public static void main(String[] args) {
      String a = "Hello";
      String b = new String("Hello");
      System.out.println(a == b);
      System.out.println(a == b.intern());
    }
    结果:
    false
    true

  • 相关阅读:
    机器学习中常见的优化算法
    linux端安装Anaconda,方便远端访问jupyter
    核心③自动分号插入
    setTimeout 和 setInterval
    核心②undefined 和 null
    类型④类型转换
    核心①为什么不要使用 eval
    类型③instanceof 操作符
    类型①相等与比较
    类型②typeof 操作符
  • 原文地址:https://www.cnblogs.com/shindo/p/5284533.html
Copyright © 2011-2022 走看看