1、字符串拼接操作
- 常量與常量的拼接結(jié)果在常量池,原理是編譯期優(yōu)化。String? s1="a"+"b"+"c";
- 常量池中不會存在相同內(nèi)容的常量。
- 只要其中有一個是變量,結(jié)果就在 堆 中。變量拼接的原理是StringBuilder。
- 如果拼接符號的前后出現(xiàn)了變量,則相當于在堆空間中new String(),具體的內(nèi)容為拼接的結(jié)果。
- 如果拼接的結(jié)果調(diào)用intern()方法,則主動將常量池中還沒有的字符串對象放入池中,并返回此對象地址。
- intern():判斷字符串常量池中是否存在值,如果存在,則返回常量池中的值的地址。如果字符串常量池中不存在值,則在常量池中加載一份,并返回此對象的地址。
2、為什么字符串拼接的值不在常量池中?
- 因為字符串是不可變的,若要進行字符串拼接,必須創(chuàng)建一個新的字符串對象來存儲拼接后的結(jié)果。由于在運行時需要動態(tài)創(chuàng)建新的對象,因此該字符串對象不會被保存在常量池中。只有在編譯時已經(jīng)確定的字符串常量才會被保存在常量池中,因為它們是可以在編譯時就確定的,不需要在運動時動態(tài)創(chuàng)建。
- 字符串拼接操作通常會產(chǎn)生新的字符串對象,這個新的字符串對象通常不會被放入常量池中,而是放在堆內(nèi)存中的一個新的內(nèi)存位置。這個因為字符串是不可變的,所以為了避免在常量池中創(chuàng)建過多的字符串對象,Java虛擬機規(guī)范不會對字符串拼接進行優(yōu)化。因此,每次進行字符串拼接操作時,都會創(chuàng)建一個新的字符串對象,即使兩個字符串的值相同,也會產(chǎn)生新的對象。如果想讓字符串拼接的值在常量池中,可以使用字符串常量拼接或者使用StringBuilder類的append方法。
package string; import org.junit.Test; public class StringTest5 { @Test public void test1() { String s1 = "a" + "b" + "c"; String s2 = "abc"; System.out.println(s1 == s2);//true System.out.println(s1.equals(s2));//true } @Test public void test2() { String s1 = "javaEE"; String s2 = "hadoop"; String s3 = "javaEEhadoop"; String s4 = "javaEE" + "hadoop"; String s5 = s1 + "hadoop"; String s6 = "javaEE" + s2; String s7 = s1 + s2; System.out.println(s3 == s4);//true System.out.println(s3 == s5);//false System.out.println(s3 == s6);//false System.out.println(s3 == s7);//false System.out.println(s5 == s6);//false System.out.println(s5 == s7);//false System.out.println(s6 == s7);//false String s8 = s6.intern(); System.out.println(s3 == s8);//true } }
文章來源地址http://www.zghlxwxcb.cn/news/detail-663319.html
文章來源:http://www.zghlxwxcb.cn/news/detail-663319.html
到了這里,關(guān)于字符串拼接操作的面試題講解的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!