JAva文字列面接問題

3320 ワード

1.
package com.gavin.convert;

public class Test3 {

	public static void main(String[] args) {
		String str1 = new String("abc");
		StringBuffer buffer = new StringBuffer("abc");
		joinChar(str1);
		appendChar(buffer);
		
		System.out.println(str1);
		System.out.println(buffer);
		
	}
	
	public static void joinChar(String string){
		string = string +'d';
	}
	
	public static void appendChar(StringBuffer buffer){
		buffer = buffer.append('d');
	}

}

結果:
abc abcd
2.
参照先:http://www.360doc.com/content/11/0310/12/3446769_99823666.shtml 
package com.gavin.convert;

public class Test4 {

	public static void main(String[] args) {
		String aString = "a1";
		String bString = "a"+1;
		System.out.println(aString == bString);
	}

}

結果:true
3.
package com.gavin.convert;

public class Test5 {
	public static void main(String[] args) {
		String aString2 = "b1";
		String cString2 = "1";
		String bString2 = "b"+cString2;
		System.out.println(aString2 == bString2);
	}
}

結果:false
4.
package com.gavin.convert;

public class Test6 {

	public static void main(String[] args) {
		String aString2 = "b1";
		final String cString2 = "1";
		String bString2 = "b"+cString2;
		System.out.println(aString2 == bString2);
		
	}
}

 
結果:true
5.
package com.gavin.convert;

public class Test7 {

	public static void main(String[] args) {
		String aString2 = "ab";
		final String cString2 = getB();
		String bString2 = "a"+cString2;
		System.out.println(aString2 == bString2);
		
	}
	
	private static String getB() {
		return "b";
	}

}

 
結果:false
6.
 
package com.gavin.convert;

public class Test8 {
	private static String aString = "ab";
	public static void main(String[] args) {
		String aString2 = "a";
		String bString2 = "b";
		String string = aString2 + bString2;
		System.out.println(aString == string);
		System.out.println(aString == string.intern());
	}
}

 
結果:false true
7.
package com.gavin.convert;

public class Test9 {

	private static String aString = new String("ab");
	public static void main(String[] args) {
		String aString2 = "a";
		String bString2 = "b";
		String string = aString2 + bString2;
		System.out.println(aString == string);
		System.out.println(aString == string.intern());
		System.out.println(aString.intern() == string.intern());
	}

}

結果:
false false true
 
8.String aStr = new String("abc");いくつのオブジェクトが作成されましたか?
答え:2つ;
9.String aStr = “abc”;いくつのオブジェクトが作成されましたか?
答え:1つ;
10.String aStr = "abc"; String bStr = "abc";いくつのオブジェクトが作成されましたか?
答え:1つ;
11.String a = “ab” + "cd";いくつのオブジェクトが作成されましたか?
3つです.
12.String aString = new String("ab"+ "cd");いくつのオブジェクトが作成されましたか?
答え:2つ;
package com.gavin.convert;

public class Test10 {
	public static void main(String[] args) {
		System.out.println("ab" == ("a" + "b"));
	}
}