Java中字符串的不可变性

1.声明一个字符串

String s = "abcd";
s存储了字符串对象的引用。下面的箭头可以理解为“store reference of”。

2.将一个字符串变量赋给另一个字符串变量

String s2 = s;

s2存储了相同的引用值,它们指向相同的字符串对象。

3.连接字符串

s = s.concat("ef");

s现在存储一个新创建的字符串对象的引用。

总结

只要一个字符串在内存中(heap)创建,就不能被改变。我们需要注意有关字符串的所有方法都不会该变字符串本身,而会返回一个新字符串。
如果你需要可被改变的字符串,我们可以使用StringBuffer或者StringBuilder。否则,每创建一个新字符串,都会浪费大量时间在垃圾收集上。下面是StringBuilder使用的简单示例:
public static String readFileToString() throws IOException {
		File dirs = new File(".");
		String filePath = dirs.getCanonicalPath() + File.separator+"src"+File.separator+"TestRead.java";
 
		StringBuilder fileData = new StringBuilder(1000);//Constructs a string buffer with no characters in it and the specified initial capacity
		BufferedReader reader = new BufferedReader(new FileReader(filePath));
 
		char[] buf = new char[1024];
		int numRead = 0;
		while ((numRead = reader.read(buf)) != -1) {
			String readData = String.valueOf(buf, 0, numRead);
			fileData.append(readData);
			buf = new char[1024];
		}
 
		reader.close();
 
		String returnStr = fileData.toString();
		System.out.println(returnStr);
		return returnStr;
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值