java中的String要点解析

String类使我们经常使用的一个类,经常用来表示字符串常量。

字符串一旦被创建赋值,就不能被改变,因为String 底层是数组实现的,且被定义成final类型。我们可以看String源码。

/** String的属性值 */  
    private final char value[];

    /** 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. */
    /**String中元素的个数**/
    private final int count;

    /** Cache the hash code for the string */
   /**String类型的hash值**/
    private int hash; // Default to 0

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = -6849794470754667710L;
    /**
     * Class String is special cased within the Serialization Stream         Protocol.
     *
     * A String instance is written into an ObjectOutputStream according to
     * <a href="{@docRoot}/../platform/serialization/spec/output.html">
     * Object Serialization Specification, Section 6.2, "Stream Elements"</a>
     */

  private static final ObjectStreamField[] serialPersistentFields =
        new ObjectStreamField[0];

String的创建方式有多种,其中最常见的是直接创建和new创建

直接创建:String a=“佛挡杀佛”;字符串值是存放在方法区中的常量池中的。

new创建:String a=new String("fds");创建的变量存放在堆内存中。

这也是String a="123";

String b=new String("123");

两者进行==比较为false的原因,因为两者地址不同。

-----------------------------------------------------------------------------------------------------

不可变动的字符串:既然字符串不能被改变,那么使用+连接字符串是怎么实现的哪?

package day1;

public class Change {
  public static void main(String[] args) {
    
     String name="java";
     String name2=name+"jjj";
     
     System.out.println(name2);
              }
}

因为字符串不能改变,所以name2绝对不可能在name参考的对象后附加jjj内容。我们反编译这段程序,可以看到发生了什么。

String s="java";
String s1=(new StringBuilder()).append(s).append("jjj").toString();
System.out.println(s1);

我们看到如果使用了+,编译器会创建StringBulder对象,并调用其append()方法使字符串附加,并调用toString()方法返回字符串。

注意:不要将+在重复性的链接场合进行使用,那样会产生大量的对象,造成内存浪费。

StringBulder是jdk5后新增的类,该版本之前使用的是StringBuffer类,两者有相同的接口,StringBulder是线程不安全的,StringBuffer线程安全,能处理同步问题。

在多线程下建议使用StringBuffer。

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

String s1="java";
String s2="ja"+"va";
System.out.println(s1==s2);

结果是true;

我们反编译程序:

String s1="java";
String s2="java";
System.out.println(s1==s2);

因为编译程序认为你的使用+的目的就是“java”吗?所以直接将java赋值给对象实例s2;

关于【

 

---==--

原文地址:https://www.cnblogs.com/zzuli/p/9319434.html