Chinaunix首页 | 论坛 | 博客
  • 博客访问: 711358
  • 博文数量: 134
  • 博客积分: 3207
  • 博客等级: 中校
  • 技术积分: 1995
  • 用 户 组: 普通用户
  • 注册时间: 2009-04-01 20:47
文章分类

全部博文(134)

文章存档

2022年(1)

2020年(7)

2018年(2)

2016年(5)

2015年(14)

2014年(21)

2013年(3)

2012年(1)

2011年(15)

2010年(30)

2009年(35)

分类: Java

2015-12-03 12:54:53


点击(此处)折叠或打开

  1. package com.StringTest;

  2. public class StringTest {

  3.     /**
  4.      * @param args
  5.      */
  6.     public static void main(String[] args)
  7.     {
  8.         // TODO Auto-generated method stub
  9.         String s1 = "hello"; //新常量对象
  10.         String s2 = "world";//新常量对象
  11.         String s3 = s1 + s2; //新String对象,返回的是堆(Heap)中的对象地址.
  12.         String s4 = s1 + s2;
  13.         
  14.         /*常量对象情况
  15.          * 字符串池(StringPool):s3指向了一个内容为"hello"的字符串常量对象。s2在赋值的时候,也是指向一个内容为
  16.          * "hello"的字符串常量对象,那么java从StringPool里面找到了已经有这样的一个常量对象了,所以就把s3的对象的地址
  17.          * 赋值给s2。即s3和s2的地址是一样的。
  18.          */
  19.         s3 = "Lhello";
  20.         s2 = "Lhello";
  21.         System.out.println(s3 == s2);
  22.         
  23.         /*new一个字符串对象的情况:
  24.          * 首先还是在StringPool中找一下是否存在"hellopp"这个字符串对象:
  25.          * 如果有,则不在StringPool里面创建
  26.          * "hellopp"这个字符串对象了,直接在堆(Heap)中创建一个"hellopp"字符串对象。然后将堆中的"hellopp"对象
  27.          * 的地址返回来,赋给s5引用,使s5指向了堆中创建的这个"hellopp"对象。
  28.          *
  29.          * 如果没有有,则在StringPool里面创建
  30.          * "hellopp"这个字符串对象,然后也在堆(Heap)中创建一个"hellopp"字符串对象。然后将堆中的"hellopp"对象
  31.          * 的地址返回来,赋给s6引用,使s6指向了堆中创建的这个"hellopp"对象。
  32.          */
  33.         String s5 = new String("hellopp");
  34.         String s6 = new String("hellopp");
  35.         System.out.println(s6 == s5);
  36.         
  37.         /*
  38.          * intern方法是返回字符串池(StringPool)中的常量字符串所对应的对象地址
  39.          * 只要str1.equlse(str2)为真,那么这两个字符串的intern方法返回的对象地址也就一样
  40.          */
  41.         String SsL = s5.intern();
  42.         String SsK = s6.intern();
  43.         System.out.println(SsL == SsK);
  44.         
  45.         
  46.         
  47.         /*
  48.          * s3是使用+号拼接的字符串。这样java会新生成一个新的对象。返回的是堆(Heap)中的对象地址.
  49.          * s4是使用+号拼接的字符串。这样java会新生成一个新的对象。返回的是堆(Heap)中的对象地址.
  50.          */
  51.         s3 = s1 + s2;
  52.         s4 = s1 + s2; //"helloworld";
  53.         //s3 = "helloworld";
  54.         System.out.println("---------------------------------------------");
  55.         System.out.println(s4.equals(s3));
  56.         System.out.println(s3.intern() == s4.intern());
  57.         System.out.println(s3 == s4);
  58.         
  59.         /*
  60.          * 字符串池(StringPool):s3指向了一个内容为"hello"的字符串对象。s2在赋值的时候,也是指向一个内容为
  61.          * "hello"的字符串对象,那么java从StringPool里面找到了已经有这样的一个对象了,所以就把s3的对象的地址
  62.          * 赋值给s2。即s3和s2的地址是一样的。
  63.          */
  64.         s3 = "hello";
  65.         s2 = "hello";
  66.         System.out.println(s3 == s2);
  67.     }

  68. }

阅读(2014) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~