String
一、String的特性
- String类:代表字符串。
- String是一个final类,代表不可变的字符序列。
- 字符串是常量,用双引号引起来表示。它们的值在创建之后不能更改。
- String对象的字符内容是存储在一个字符数组value[]中的。
源码:
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是不可变字符序列的体现:
- 当对字符串重新赋值时,需要重写指定内存区域赋值,不能使原有的value进行赋值
- 当对现有的字符串进行连接操作时,也需要重新指定内存区域赋值,不能使用原有的value进行赋值
二、String的使用
String对象的创建
String str = "hello";
//本质上this.value = new char[0];
String s1 = new String();
//this.value = original.value;
String s2 = new String(String original);
//this.value = Arrays.copyOf(value, value.length);
String s3 = new String(char[] a);
String s4 = new String(char[] a,int startIndex,int count);
String str1 = “abc”;与String str2 = new String(“abc”);的区别?
- 字符串常量存储在字符串常量池,目的是共享
- 字符串非常量对象存储在堆中。
面试题:String s = new String(“abc”);方式创建对象,在内存中创建了几个对象?
- 两个:一个是堆空间中new的结构,另一个是char[]对应的常量池中的数据:“abc”
字符串对象是如何存储的
String s1 = "javaEE";
String s2 = "javaEE";
String s3 = new String("javaEE");
String s4 = new String("javaEE");
System.out.println(s1 == s2);//true
System.out.println(s1 == s3);//false
System.out.println(s1 == s4);//false
System.out.println(s3 == s4);//false
结论:
- 常量与常量的拼接结果在常量池。且常量池中不会存在相同内容的常量。
- 只要其中有一个是变量,结果就在堆中
- 如果拼接的结果调用intern()方法,返回值就在常量池中
String的实例化方式
方式一:通过字面量定义的方式
方式二:通过new + 构造器的方式