java中字符串连接池的笔试题小结

来源:互联网 发布:程序员会几种语言 编辑:程序博客网 时间:2024/06/05 15:22

题目:

import java.util.*; 
class StringTest{
public String hello ="Hello";
public String hel ="Hel";
public String lo ="lo"; 
}
class MyTest{ 
public MyTest(){}
public static void main(String[] args){
StringTest st = new StringTest();
String str1 ="Hello";
String str2 ="Hel";
String str3 ="lo";
String str4 ="Hel"+"lo";
String str5 =str2+str3;
String str6 =st.hel+st.lo;

(1)System.out.println(str1==str4);
(2)System.out.println(str1==str5);
(3)System.out.println(str1==st.hello);
(4)System.out.println(str1==str6);

}

输出的结果是true false true false 。分析 :String str5 =str2+str3; //相当于new("Hello")、相当于new("Hel"+"lo")。
(1)中,str4是字符串常量和常量的拼接,也是常量,在字符串常量池中,str4会重用str1指向的“Hello”字符串。所以为true;
(2)中,str5是包含变量的字符串连接符“+”,str5在程序运行时创建的对象,存在内存中的堆中,所以str1!==str5。
(3)中,st.hello是字符串字面量,即字符串常量,是存在方法区的字符串常量池中,(3)结果是true。
(4)中,str6是包含变量的字符串连接符“+”,所以str6是运行时创建的对象,在堆中,str1在字符串常量池中,所以为false。。

阅读全文
0 0
原创粉丝点击