---
title: "Java源码-String"
author: "DanielHan"
date: "2014-02-17T13:46:40Z"
tags: []
categories: ["编程语言"]
slug: "java-string"
draft: false
lastmod: "2014-02-15T15:08:56Z"
id: 2009352
url: "https://danielhan.iteye.com/blog/2009352"
---

```java

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence

```


Serializable
序列化接口：主要用于io传输，暂不做研究。

Comparable
详情请看博文<http://danielhan.iteye.com/blog/2015449>

CharSequence
字符序列接口


```java

    /**
     * Allocates a new {@code String} so that it represents the sequence of
     * characters currently contained in the character array argument. The
     * contents of the character array are copied; subsequent modification of
     * the character array does not affect the newly created string.
     * @param  value
     *         The initial value of the string
     */
    public String(char value[]) {
        this.value = Arrays.copyOf(value, value.length);
    }

```

这属于String类的其中一个构造方法，作用是将参数char数组复制一份作为String的value属性，这样一旦参数char数组改变，此方法生成的String对象的值不变。设想：如果此方法如下：

```java

public String(char value[]) {
    this.value = value;
}

```

这样String类的value属性指向参数，参数一旦改变，它也跟着变。

<span style="color:red">补充</span>
类定义时修饰符是final，表示String对象不可改变
说的String类型不能修改是因为String存在于heap区，是一个常量
只要是new 出来的都会放在这个区域里的
str="fdfds";
str+="hghg";
这样的话就生成了三个字符串了，知道吗？其实在堆栈中"fdfds"这个字符串现在并没有改变
只是str的指向改变了。
现在存在的三个字符串是："fdfds"  "hghg" "fdfdshghg"这三个。这样来说就比较占用内存了