String&StringBuffer&StringBuilder

String

public final class String  //被final修饰,不能被继承
    implements java.io.Serializable, Comparable<String>, CharSequence
{
    /** The value is used for character storage. */
    private final char value[];//维护了一个字符数组,用来存储字符,且用final修饰
 
    /** The offset is the first index of the storage that is used. */
    private final int offset;
 
    /** The count is the number of characters in the String. */
    private final int count;
 
    /** Cache the hash code for the string */
    private int hash; // Default to 0
 
    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = -6849794470754667710L;
 
    ......
    public String substring(int beginIndex, int endIndex) {
    if (beginIndex < 0) {
        throw new StringIndexOutOfBoundsException(beginIndex);
    }
    if (endIndex > count) {
        throw new StringIndexOutOfBoundsException(endIndex);
    }
    if (beginIndex > endIndex) {
        throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
    }
    return ((beginIndex == 0) && (endIndex == count)) ? this :
        new String(offset + beginIndex, endIndex - beginIndex, value);
    }
 
}

(1)String类是一个final类,因此其不能被继承。
(2)String维护了一个char[]数组,用来存储字符。且用final修饰,即不能被更改。
(3)String类中涉及对字符串修改的操作,都不是在原字符串上进行的,而是重新生成了一个新的String字符串即对原字符串没有影响。

StringBuffer & StringBuilder-----可变的字符串

(1)因为每次对String的修改操作都会重新生成一个String对象,因此非常浪费空间。这样就引入了StringBuffer和StringBuilder来处理这种变化的字符串。
(2)StringBuffer和StringBuilder是在原来字符串上进行修改,不会新产生对象。
(3)StringBuffer与StringBuilder的区别是,StringBuffer的方法用synchronized修饰了,是线程安全的。

String str = “abc”;String str = new String(“abc”)创建了几个对象

(1)String str = "abc"创建0个或者1个对象。—“abc”是字面量,存在于class文件中的常量池中。当类加载时存在与运行时常量池中。如果常量池中已经有这个字符串的字面量了,就不用再创建了。没有才创建。
在这里插入图片描述
(2)String str = new String(“abc”); new关键字,无论如何都会在堆中开辟空间,创建一个对象,然后返回地址给引用。因此肯定会在堆中创建一个对象。然后又有一个“abc”字面量,在类加载时需要在运行时常量池中构建这个字面量的(如果运行池常量池中没有),注意关于这个字面量,如果运行时常量池中已经存在,那么就不用创建了,如果没有才在运行时常量池中创建。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值