String的不变性

String对象创建后则不能被修改,是不可变的。

public class Test1 {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "hello";
        String s3 = new String("hello");
        String s4 = new String("hello");
        //相同的字符串常量,java编译器只创建一个,所以返回true
        System.out.println(s1 == s2);
        //s1和s3是不同的对象所以返回false
        System.out.println(s1 == s3);
        //s3和s4是不同的对象所以返回false
        System.out.println(s3 == s4);
        s1 = s1 + "world";
        //输出helloworld,但是已经不是原来的对象了,s1指向新的内存空间
        System.out.println(s1);
    }
}

这里写图片描述

public class Test {
        public static void main(String[] args)  {
            String a = "hello2";
            final String b = "hello";
            String d = "hello";
            String c = b + 2;
            String e = d + 2;
            System.out.println((a == c));
            System.out.println((a == e));
            System.out.println(e);
        }
}

这里写图片描述
final变量是基本数据类型以及String类型时,如果在编译期间能知道它的确切值,则编译器会把它当做编译器常量使用。

“==”判断是否是同一字符串对象,也就是比较内存地址是否一致;
equals()比较的是字符串的内容。
String类的常用方法:
这里写图片描述
其中使用 substring(beginIndex , endIndex) 进行字符串截取时,包括 beginIndex 位置的字符,不包括 endIndex 位置的字符。
String类具有不可变性,因此也可使用StringBuilder和StringBuffer来存储字符串。其中StringBuilder虽然线程不安全,但是性能高,因此也更为常用。
StringBuilder常用方法:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/coder_16/article/details/80676930
今日推荐