如果我写
String s= new String("how many object b created by this method ");
Run Code Online (Sandbox Code Playgroud)
与这样做相比,将创建多少个参考对象和对象:
Sting s1="Is this method is good as compare to upper";
Run Code Online (Sandbox Code Playgroud)
使用String s= new String("how many object b created by this method ");创建String对象的新对象,并将字符串"由此方法创建的对象b的数量"传递给其构造函数.
在String s1="Is this method is good as compare to upper";'s1'中是一个字符串文字.在字符串文字:
每次代码创建字符串文字时,JVM首先检查字符串文字池.如果池中已存在该字符串,则返回对池化实例的引用.如果池中不存在该字符串,则新的String对象将实例化,然后放入池中.Java可以进行此优化,因为字符串是不可变的,可以共享而不用担心数据损坏.
上述概念与字符串实习有关 ; 所有文字字符串和字符串值常量表达式都在Java [source]中实现.所以基本上,String s1="Is this method is good as compare to upper";只有"Is this method is good as compare to upper"在池中尚未创建新对象时才使用它.