Java 基础之---String

String 在java中用于表示字符串。String 对象的值是不可变的.

我们在平时有些时候采用String的拼接或者给一个变量重复赋值,表面上还是一个变量,实际上内存地址已经变化.

实际的String 是final定义的,是一个字符数据,是不可变的.(对于一个final变量,如果是基本数据类型的变量,则其数值一旦在初始化之后便不能更改;如果是引用类型的变量,则在对其初始化之后便不能再让其指向另一个对象。)

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];

    /** Cache the hash code for the string */
    private int hash; // Default to 0

所以说,以下例子

String s="hell world";
s="java";
实际初始化变量s的时候,然后再对s进行赋值,实际是JVM重新创建了一个新的String对象.

假如对s变量一直不停的修改其对应的值,表面上只有一个变量,实际上JVM在不停的创建新对象,旧对象不断的回收死亡的过程,这样会使得JVM中产生大量的碎片,降低JVM的性能.

如果是在代码启动后,String对象不再修改重新赋值,那么可以考虑使用String,比如在代码中定义一些public static final String常量。如果需要在代码中频繁修改和赋值操作字符串对象具体内容,建议使用StringBuffer。

StringBuffer是字符串变量。StringBuffer不会产生String那样的问题:每一次修改就重新创建一个新的String对象。在某种程度上讲,StringBuffer内部维持一个可变长度的char数组来存放字符数据.


    /**
     * A cache of the last value returned by toString. Cleared
     * whenever the StringBuffer is modified.
     */
    private transient char[] toStringCache;

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    static final long serialVersionUID = 3388685877147921107L;

    /**
     * Constructs a string buffer with no characters in it and an
     * initial capacity of 16 characters.
     */
    public StringBuffer() {
        super(16);
    }

    /**
     * Constructs a string buffer with no characters in it and
     * the specified initial capacity.
     *
     * @param      capacity  the initial capacity.
     * @exception  NegativeArraySizeException  if the {@code capacity}
     *               argument is less than {@code 0}.
     */
    public StringBuffer(int capacity) {
        super(capacity);
    }

    /**
     * Constructs a string buffer initialized to the contents of the
     * specified string. The initial capacity of the string buffer is
     * {@code 16} plus the length of the string argument.
     *
     * @param   str   the initial contents of the buffer.
     */
    public StringBuffer(String str) {
        super(str.length() + 16);
        append(str);
    }


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值