zoukankan      html  css  js  c++  java
  • 【面试题】String类、包装类的不可变性

    不可变类的意思是创建该类的实例后,该实例的实例变量是不可改变的。Java提供的8个包装类和String类都是不可变类。因此String和8个包装类都具有不可变性。

      就拿String类来说,通过阅读String类的源码我们可以发现其实整个String类是被final所修饰,而其用来存储值的底层实际上是一个私有final类型的字符数组,因此在JVM运行的时候是把“hello”当成常量存储在运行时常量池内部。

    public class UnChange {
        public static void main(String[] args) {
            String s1 = "hello";
            String s2 = "hello";
            System.out.println(s1 == s2);
        }
    }
    输出结果:
    true

      上述代码在JVM当中其实是这样子的,其实只有一个“hello”常量,而变量s1和s2都指向同一个“hello”常量。

      常有以此作为考点:

    public class UnChange {
        public static void main(String[] args) {
            String s1 = "hello";
            String s2 = "hello";
            Integer n1 = 100;
            Integer n2 = 100;
            s2+=" world";
            n2+=2;
            System.out.println("s1="+s1);
            System.out.println("s2="+s2);
            System.out.println("n1="+n1);
            System.out.println("n2="+n2);
        }
    }
    输出结果:
    s1=hello
    s2=hello world
    n1=100
    n2=102

      在JVM当中如图所示:s1和s2一开始指向的都是“hello”,n1和n2一开始指向的都是100

      后来通过s2+=" world"; n2+=2;又分别在常量池和堆当中创建了“hello world”和102实例,并且重新改变了变量s2和n2的指向。

  • 相关阅读:
    html_Dom
    html_javascript
    html_之css
    协程
    进程和线程的总结
    html_基础标签
    html_头部<meta>设置
    Python_queue单项队列
    Python_paramiko模块
    Python_多进程multiprocessing
  • 原文地址:https://www.cnblogs.com/SherLocked/p/12838195.html
Copyright © 2011-2022 走看看