還記得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