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的原因,因为两者地址不同。