java基础回顾之String对象是不可变的

package com.bjpowernode.demo01;
/**
 * String字符串对象是不可变的
 * @author Administrator
 *
 */
public class Test04 {

	public static void main(String[] args) {
		
		String s1 = "hello";
		s1 = "world";
		
		byte[] bytes = {65,66,67,97,98,99};
		String s2 = new String(bytes);
		s2 = s2 + "hehe";
		/*
		 * 在字符串连接时, 会使用StringBuilder类创建对象,进行字符串的连接,
		 * 最后生成一个新的String对象赋值给s2变量
		 */
	}

}

内存分析图:

在这里插入图片描述

package com.bjpowernode.demo01;
/**
 * String对象不可变的,每次进行字符串连接都会生成新的字符串对象
 * @author Administrator
 *
 */
public class Test05 {

	public static void main(String[] args) {
		//以下两行共创建了多少个String对象? 3个:  "abc"是一个, 堆区中创建了两个
		String  s1 = new String("abc");
		String  s2 = new String("abc");
		
		//在创建s1对象时, 使用到"abc"字面量, 保存到字符串常量池中
		//以后再使用"abc"字面量时, 就直接把常量池中的"abc"对象的引用给返回
		String s3 = "abc";
		String s4 = "abc";
		//s3和s4都是引用了常量池中的同一个"abc"常量 
		System.out.println( s3 == s4 ); 		// true
		
		//以下两行共创建了多少个String对象?  两个 :  "hello"字面量,  "hellohello"连接生成一个新的
		String s5 = "hello";
		String s6 = s5 + "hello";
		
		//以下两行共创建了多少个String对象? 三个: "hehe", "he",  "hehehehe"
		String  s7 = "hehe";
		String  s8 = s7 + "he" + "he";
		
		//以下两行共创建了多少个String对象?  两个: "haha" , "hahahaha"
		String s9 = "haha";
		String s10 = "ha" + "ha" + s9;	//当前编译器会进行优化, 把"ha" + "ha"优化为"haha"
		
	}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章