1. 程式人生 > >java中String字串==的疑問?

java中String字串==的疑問?

java中String字串==的疑問?誰能幫忙解釋和理解一下!順便說一下底層的原理和執行規則?
直接po程式碼和截圖

public class TestString {

	/** 
	* 測試String
	*/
	public static void main(String[] args) {
		String a = "hello2";
		final String b = getStr2();
		String c = b + 2;
		String d = "hello2";
		String e = new String("hello2");
		String f = new String("hello2");
		String h = "hello";
		String j = h + 2;
		StringBuffer sb = new StringBuffer("hello2");
		StringBuilder sb2 = new StringBuilder("hello2");
		String k = getStr2();
		String m = k + 2;
		System.out.println("c結果" + (a == c));
		System.out.println("d結果" + (a == d));
		System.out.println("e結果" + (a == e));
		System.out.println("f結果" + (a == f));
		System.out.println("f.toString()結果" + (a == f.toString()));
		System.out.println("j結果" + (a == j));
		System.out.println("sb.toString()結果" + (a == sb.toString()));
		System.out.println("sb2.toString()結果" + (a == sb2.toString()));
		System.out.println("m結果" + (a == m));
	}
	
	public static String getStr() {
		String text = "hello";
		return text;
	}
	
	public static String getStr2() {
		return "hello";
	}

}

public static void main(String[] args) {
		String a = "hello2";
		final String b = "hello";
		String d = "hello";
		String c = b + 2;
		String e = d + 2;
		System.out.println((a == c));
		System.out.println((a == e));

	}