还记得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