可变字符串基础学习笔记(一)

1、可变字符串(StringBuffer)概述

①StringBuffer:字符串缓冲区,是线程安全的,只是效率稍微慢一点。

②StringBuffer和String的比较:String一旦被创建后,值不能改变,如果参与了操作,引用发生了变化,不是在原有的字符串上操作,而是新产生了一个字符串;StringBuffer是在原有字符串上操作,不会新产生字符串。

public class StringBufferDemo {
	
	public static void main(String[] args) {
		//创建可变字符串
		StringBuffer sb = new StringBuffer();
		//把可变字符串做追加
		StringBuffer sb1 = sb.append(true);
		System.out.println(sb1);
		//判断追加后的字符串的地址
		System.out.println(sb == sb1);
		
		String str = "abc";
		//字符串加上任何类型返回的都是字符串
		String str1 = str + true;
		//System.out.println(str1);
		//String字符串的地址比较
		System.out.println(str == str1);	
	}
}

2、StringBuffer构造器


public class StringBufferDemo1 {
	
	public static void main(String[] args) {
		//创建可变字符串,开辟了一个默认是16个字符的空间
		StringBuffer sb = new StringBuffer();
		System.out.println("可变字符串的长度:"+sb.length()+"   容量:"+sb.capacity());
		
		sb.append("hellohellohellohello");
		System.out.println("可变字符串的长度:"+sb.length()+"   容量:"+sb.capacity());
		//创建一个10个容量的字符串
		StringBuffer sb1 = new StringBuffer(10);
		sb1.append("hellohellohellohello");
		System.out.println("可变字符串的长度:"+sb1.length()+"   容量:"+sb1.capacity());
		
		//创建一个带有字符串的参数的可变字符串对象
		StringBuffer sb2 = new StringBuffer("hellohellohellohello");
		System.out.println("可变字符串的长度:"+sb2.length()+"   容量:"+sb2.capacity());
	}

}

3、追加方法



public class StringBufferDemo2 {
	
	public static void main(String[] args) {
		//创建可变字符串,开辟了一个默认是16个字符的空间
		StringBuffer sb = new StringBuffer();
		sb.append(true)
		.append('a')
		.append(new char[]{'a','g','g'})
		.append("hello")
		.append(100d)
		.append(14.5f)
		.append(13)
		.append(900l);
		
		System.out.println(sb);		
	}
}

4、小结

①java.lang下的类不需要引用,可直接使用;

②字符串加上任何类型返回的都是字符串;

③StringBuffer是线程安全的,只是效率稍低;

④StringBuffer的追加方法append()是在原基础上相加的;

⑤StringBuffer默认构造器创建了一个默认的16个字符的空间。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值