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

574 篇文章 4 订阅
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"
		
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值