`

String类与StringBuffer类

阅读更多
1.书里说道:
用String类创建的对象在操作中不能变动和修改字符串的内容,因此也称为字符串常量.
用StringBuffer类创建的对象在操作中可以更改字符串的内容,因此也称字符串变量.
String类的对象只能进行查找和比较等操作,而StringBuffer类的对象可以进行添加,插入,修改之类的操作.

2.对String的常量理解,java会维护一个String的常量表.
package com.myfloat.test;

public class TestString {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String s1 = "love";
		String s2 = new String("love");
		String s3 = new String("love").intern();
		System.out.println(s1==s2);
		System.out.println(s1==s3);
		System.out.println(s2==s3);
		System.out.println();
		System.out.println(s1.equals(s2));
		System.out.println(s1.equals(s3));
		System.out.println(s2.equals(s2));
	}

}

false
true
false

true
true
true


3.'=='這個運算子會看看這兩個字串的references是不是指向同一個字串object。而
java.lang.String.equals()這個method則會比較這兩個字串的"值"是不是一樣的。換句話說,比較這兩個字串是不是有相同的字元序列。

4.以上程序中,String s1 = "love";会在字符串常量表中创建一"love"对象并把其引用赋值给s1变量.String s2 = new String("love");则会创建一内容为love的String类.String s3 = new String("love").intern();则会看常量表中有无"love"这字符串有就取引用赋予s3,无则在表中加入"love"并取引用赋予s3.所以s1与s3是相同的,s2和它们是不同的.

5.null或空值的判断处理
package com.myfloat.test;

public class TestNullOrEmpty {

	public static void main(String[] args) {
		String value = null;
		testNullOrEmpty(value);

		value = "";
		testNullOrEmpty(value);

		value = " ";
		testNullOrEmpty(value);

		value = "hello me!";
		testNullOrEmpty(value);
	}

	static void testNullOrEmpty(String value) {
		if (value == null) { // 正确的写法
			System.out.println("value is null.");
		} else if ("".equals(value)) { // 正确的写法
			System.out.println("value is blank but not null.");
		} else {
			System.out.println("value is \"" + value + "\"");
		}

		if (value == "") { // NG 错误的写法
			// 别用这种写法
		}
	}
}


value is null.
value is blank but not null.
value is " "
value is "hello me!"


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics