String_Equals_小知識點

class Equals_String
{
	public static void show(Object c)
	{
	System.out.println(c);
	}
	public static void main(String []args)
	{
		String a = "hello";
		String b = "hello";
		show(a==b);//true
		show("a==b?"+a==b);// a==b?true 錯誤 爲false 計算順序爲(("a==b"+a)==b)->fasle
		//加號的計算順序是從左往右遇到字符串則開始拼接字符串 否則都爲其他運算 比如數學運算
		//詳見備註
		String c = new String("hello");
		show(a==c); //flase
		String e = "hell"+"o";
		show(a==e); //false  錯誤 爲true
		
		
		
		
		show("---數字---");
		String d = "hello5";
		String f = "hello"+new Integer(a.length()).toString(); //裏面有new
		String h = "hello"+"5";
		String g= "hello"+5;
		show(f);
		show(d==g);//true 同上
		show(d==h); //true 同上
		show(d==f); //false 理由下	
		show(new Integer(a.length()).toString()=="5");//裏面有new

		//  另外常規的判斷兩個字符串是否相等呢是用equals方法
		show("---equals---");
		show(a.equals(b)) ;//true

		//備註:
		/*
			show(""+1+2);
			show(1+2);
			show(1+""+2);
			show(1+2+"");
			結果爲:
				12 3 12 3
				自左向右,遇到字符就轉字符類型了
		*/
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章