Java中的String和StringBuffer

如下面的代码

 

public class Test
{
	public static void main(String[] args)
	{
		//1
		StringBuffer sb = new StringBuffer(20);
		sb.append("hello").append(" world");
		
		System.out.println(sb);
		System.out.println(sb.length());
		
		//2
		String str1 = new String("abc");
		String str2 = new String("abc");
		System.out.println(str1.equals(str2));
		
		StringBuffer sb1 = new StringBuffer("abc");
		StringBuffer sb2 = new StringBuffer("abc");
		System.out.println(sb1.equals(sb2));
		
		//3
		System.out.println(str1 == str1.toString());
		System.out.println("abc" == sb1.toString());
	}
}

 

 

输出为:

 

hello world
11
true
false
true
false

 

 

解释下:

 

1. String类覆盖了Object类的equals()方法,而StringBuffer没有覆盖Object类的equals()方法。

 

2. String和StringBuffer都覆盖了Object类的toString()方法,但各自的实现方式不一样:String类的toString()方法返回当前String实例本身的引用,而StringBuffer类的toString()方法返回一个以当前StringBuffer的缓冲区中的所有字符串为内容的新的String对象的引用。

 

 

 

补充个Boolean类型的测试。

 

public class BooleanTest 
{
	public static void main(String[] args)
	{
		System.out.println(new Boolean("FalSe"));
		System.out.println(new Boolean("true"));
		System.out.println(new Boolean("TrUe"));
		System.out.println(new Boolean("TRUE"));
		System.out.println(new Boolean("1234"));
		System.out.println(new Boolean("abcd"));
		System.out.println(new Boolean(true));
		System.out.println(new Boolean(false));
	}
}

 

输出为:

 

false
true
true
true
false
false
true
false

 

 

你可能感兴趣的:(Java)