Java中的String(1)

String不可变

摘自JDK1.8 API文档

Strings are constant; their values cannot be changed after they are created.

这玩意被创造出来之后就是不可变的了。

如下代码:

public class String_01 {
    public static void main(String[] args) {
        // 1 String是不可变的
        String a = "abc";
    }
}

图1


重新创建了一个新的abc123,而不是直接在原有的abc后面直接加

public class String_01 {
    public static void main(String[] args) {
        // 1 String是不可变的
        String a = "abc";
        a = a + "123";
    }
}

在这里插入图片描述


一个例子

是字符串常量的情况下

这种情况下,字符串常量都在数据栈中。常量是被共享的。

public class String_02 {
    public static void main(String[] args) {
        String s1 = "oh";
        String s2 = "oh";
        System.out.println(s1 == s2);
    }
}

如图:
在这里插入图片描述


是对象的情况下

public class String_02 {
    public static void main(String[] args) {
        String s1 = new String("oh");
        String s2 = new String("oh");
        System.out.println(s1 == s2); // flase
        System.out.println(s1.equals(s2)); // true
    }
}

在这里插入图片描述


String中对equals方法的说明:

  • Compares this string to the specified object.
  • The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

总结一下就是:
要返回true的话

  • equals方法的参数不能为空
  • 和被比较的是相同的字符序列

所以,第一个为false,可以看图理解一下。
第二个为true,因为满足我们上面两个规则。

常用的方法

具体可查看API文档,本处不再赘述。
学习查看API也是一种非常重要的能力。

注意
一般情况下,工作中用的比较多的就是截取字符串。
但有时候会忘记这里的截取究竟从1开始,还是从0开始。
亦或者两者都行。

其实,很容易记住:
看官方文档中String类的一个构造方法:

public String(char[] value)

char data[] = {'a', 'b', 'c'};
String str = new String(data);

也就是说,String可以由字符数组构造出来。
那么既然是数组。
所以必须是从
0
开始

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值