還記得java.lang.String么,如果現在給你一個小程序,你能說出它的結果么
1 public static String ab(String a){ 2 return a + "b"; 3 } 4 5 public static void testAb(){ 6 String x = "a"; 7 ab(x); 8 System.out.println(x); 9 } 10 11 public static void main(String[] args) { 12 testAb(); 13 }
以上執行了main方法后會輸出什么結果呢?現自己想一想,再給出答案
?
?
?
結果是a。 為什么會是a呢, 因為我們都知道String表示字符串,是一個對象,但是卻是一個不可變的對象,也就是說字符串是一個常量,在創建后就是不可變的了。所以我們在上面看到的x="a",實際是不會變化的。查看java.lang.String 的源碼也可以得出結論,final的作用就不用說了吧。截取一段
1 public final class String 2 implements java.io.Serializable, Comparable<String>, CharSequence { 3 /** The value is used for character storage. */ 4 private final char value[]; 5 6 /** Cache the hash code for the string */ 7 private int hash; // Default to 0
?