点击(此处)折叠或打开
- package com.StringTest;
-
- public class StringTest {
-
- /**
- * @param args
- */
- public static void main(String[] args)
- {
- // TODO Auto-generated method stub
- String s1 = "hello"; //新常量对象
- String s2 = "world";//新常量对象
- String s3 = s1 + s2; //新String对象,返回的是堆(Heap)中的对象地址.
- String s4 = s1 + s2;
-
- /*常量对象情况
- * 字符串池(StringPool):s3指向了一个内容为"hello"的字符串常量对象。s2在赋值的时候,也是指向一个内容为
- * "hello"的字符串常量对象,那么java从StringPool里面找到了已经有这样的一个常量对象了,所以就把s3的对象的地址
- * 赋值给s2。即s3和s2的地址是一样的。
- */
- s3 = "Lhello";
- s2 = "Lhello";
- System.out.println(s3 == s2);
-
- /*new一个字符串对象的情况:
- * 首先还是在StringPool中找一下是否存在"hellopp"这个字符串对象:
- * 如果有,则不在StringPool里面创建
- * "hellopp"这个字符串对象了,直接在堆(Heap)中创建一个"hellopp"字符串对象。然后将堆中的"hellopp"对象
- * 的地址返回来,赋给s5引用,使s5指向了堆中创建的这个"hellopp"对象。
- *
- * 如果没有有,则在StringPool里面创建
- * "hellopp"这个字符串对象,然后也在堆(Heap)中创建一个"hellopp"字符串对象。然后将堆中的"hellopp"对象
- * 的地址返回来,赋给s6引用,使s6指向了堆中创建的这个"hellopp"对象。
- */
- String s5 = new String("hellopp");
- String s6 = new String("hellopp");
- System.out.println(s6 == s5);
-
- /*
- * intern方法是返回字符串池(StringPool)中的常量字符串所对应的对象地址
- * 只要str1.equlse(str2)为真,那么这两个字符串的intern方法返回的对象地址也就一样
- */
- String SsL = s5.intern();
- String SsK = s6.intern();
- System.out.println(SsL == SsK);
-
-
-
- /*
- * s3是使用+号拼接的字符串。这样java会新生成一个新的对象。返回的是堆(Heap)中的对象地址.
- * s4是使用+号拼接的字符串。这样java会新生成一个新的对象。返回的是堆(Heap)中的对象地址.
- */
- s3 = s1 + s2;
- s4 = s1 + s2; //"helloworld";
- //s3 = "helloworld";
- System.out.println("---------------------------------------------");
- System.out.println(s4.equals(s3));
- System.out.println(s3.intern() == s4.intern());
- System.out.println(s3 == s4);
-
- /*
- * 字符串池(StringPool):s3指向了一个内容为"hello"的字符串对象。s2在赋值的时候,也是指向一个内容为
- * "hello"的字符串对象,那么java从StringPool里面找到了已经有这样的一个对象了,所以就把s3的对象的地址
- * 赋值给s2。即s3和s2的地址是一样的。
- */
- s3 = "hello";
- s2 = "hello";
- System.out.println(s3 == s2);
- }
-
- }