面试题之String str = new String("abc"); 创建了几个对象

今天去面试的时候碰到了这个问题:String str = new String("abc"); 创建了几个对象,回来自己研究并查阅资料才发现答错了。。
网上的争论不少,有的说是两个,答案应该是:两个或一个


理由解释如下:
都了解java 的字符串常量缓冲区(字符串池,字符串常量池),
如果代码是这样的:

[java] view plain copy

  1. String str2 = new String("abc");  


并且 abc 字符串之前没有用过,这毫无疑问创建了两个对象,一个是new  String 创建的一个新的对象,一个是常量“abc”对象的内容创建出的一个新的String对象,

但是如果代码是这样子的:

[java] view plain copy

  1. String str1 = "abc";  
  2.   
  3. String str2 = new String("abc");  


嗯,创建几个就不好说了,我们还是测试一下吧,首先我们打开cmd.exe, 通过javac *.java编译好该Java文件,然后通过命令javap -c *来查看java编译后的ByteCode字节码,

 

ldc的含义是:将常量值从常量池中取出来并且压入栈中。从上图中,我们可以看到第0行和第7行中的字符串引用是同一个,这说明了,在编译期间,该字符串变量的值已经确定了下来,并且将该字符串值缓存在缓冲区中,同时让该变量指向该字符串值,后面如果有使用相同的字符串值,则继续指向同一个字符串值

所以String str2 = new String("abc"); 此时就创建一个对象,而abc 则是从字符串常量缓冲区中取出来的。

ok。就是这个样子。

posted @ 2019-03-26 13:58  strawqqhat  阅读(175)  评论(0编辑  收藏  举报
#home h1{ font-size:45px; } body{ background-image: url("放你的背景图链接"); background-position: initial; background-size: cover; background-repeat: no-repeat; background-attachment: fixed; background-origin: initial; background-clip: initial; height:100%; width:100%; } #home{ opacity:0.7; } .wall{ position: fixed; top: 0; left: 0; bottom: 0; right: 0; } div#midground{ background: url("https://i.postimg.cc/PP5GtGtM/midground.png"); z-index: -1; -webkit-animation: cc 200s linear infinite; -moz-animation: cc 200s linear infinite; -o-animation: cc 200s linear infinite; animation: cc 200s linear infinite; } div#foreground{ background: url("https://i.postimg.cc/z3jZZD1B/foreground.png"); z-index: -2; -webkit-animation: cc 253s linear infinite; -o-animation: cc 253s linear infinite; -moz-animation: cc 253s linear infinite; animation: cc 253s linear infinite; } div#top{ background: url("https://i.postimg.cc/PP5GtGtM/midground.png"); z-index: -4; -webkit-animation: da 200s linear infinite; -o-animation: da 200s linear infinite; animation: da 200s linear infinite; } @-webkit-keyframes cc { from{ background-position: 0 0; transform: translateY(10px); } to{ background-position: 600% 0; } } @-o-keyframes cc { from{ background-position: 0 0; transform: translateY(10px); } to{ background-position: 600% 0; } } @-moz-keyframes cc { from{ background-position: 0 0; transform: translateY(10px); } to{ background-position: 600% 0; } } @keyframes cc { 0%{ background-position: 0 0; } 100%{ background-position: 600% 0; } } @keyframes da { 0%{ background-position: 0 0; } 100%{ background-position: 0 600%; } } @-webkit-keyframes da { 0%{ background-position: 0 0; } 100%{ background-position: 0 600%; } } @-moz-keyframes da { 0%{ background-position: 0 0; } 100%{ background-position: 0 600%; } } @-ms-keyframes da { 0%{ background-position: 0 0; } 100%{ background-position: 0 600%; } }