String類應該是封裝的char數組,但它只提供了char charAt(int)方法來獲得指定位置的字符,而沒有相應的setter方法來設置特定位置的字符,所以String對象一旦初始化,其內容不可變更。String類中String concat(String)方法就是返回了一個新的String對象的引用。
- package htgy;
- import java.util.Arrays;
- public class ReferenceDemo {
- /**
- * @param args
- */
- public static void main(String[] args) {
- String s = "abc";
- System.out.println("1:" + s);
- f(s);
- System.out.println("2:" + s);
- s = g(s);
- System.out.println("3:" + s);
- // 因爲String不可變,所以要編輯字符串的內容,採用String g(String) 的方式。
- int[] a = {1, 2, 3};
- System.out.println("4:" + Arrays.toString(a));
- f1(a);
- System.out.println("5:" + Arrays.toString(a));
- f(a);
- System.out.println("6:" + Arrays.toString(a));
- a = g(a);
- System.out.println("7:" + Arrays.toString(a));
- // void f(int[]) 和 int[] g(int[])的效果相同。
- // 要改變數組的內容,一般採用 f(int[]) 的方式。
- }
- static void f(String s) {
- s = s + "123"; // String內容不可改變,s指向了另一個String對象
- System.out.println("方法void f(String)中:" + s);
- }
- static String g(String s) {
- s += "123"; // String內容不可改變,s指向了另一個String對象
- System.out.println("方法String g(String)中:" + s);
- return s; // 將新對象的引用返回
- }
- static void f(int[] a) {
- a[1] = 7; // 數組內容可以改變
- System.out.println("方法void f(int[])中:" + Arrays.toString(a));
- }
- static int[] g(int[] a) {
- a[1] = 7; // 數組內容可以改變
- System.out.println("方法int[] g(int[])中:" + Arrays.toString(a));
- return a; // 返回原對象的引用
- }
- static void f1(int[] a) {
- a = new int[]{4, 5, 6}; // a指向了另一個數組對象
- System.out.println("方法void f1(int[])中:" + Arrays.toString(a));
- }
- }
- //~ Output:
- /*
- * 1:abc
- * 方法void f(String)中:abc123
- * 2:abc
- * 方法String g(String)中:abc123
- * 3:abc123
- * 4:[1, 2, 3]
- * 方法void f1(int[])中:[4, 5, 6]
- * 5:[1, 2, 3]
- * 方法void f(int[])中:[1, 7, 3]
- * 6:[1, 7, 3]
- * 方法int[] g(int[])中:[1, 7, 3]
- * 7:[1, 7, 3]
- */