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常用方法:
这里写图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值