String的特性
1 String类:代表字符串。Java 程序中的所有字符串字面值(如 “abc” )都作为此类的实例实现。
2 String是一个final类,代表不可变的字符序列。
3 字符串是常量,用双引号引起来表示。它们的值在创建之后不能更改。
4 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对象的创建
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类型的概述总结
package BaiYSExer1;
/**
* @author Bys
* @create StringTest-03-14-9:55
*/
/*
String的特性
String:字符串,使用一对""引起来表示
1.String声明为final的,不可以被继承
2.String实现了Serializable接口:表示字符串是支持序列化的。
实现了Comparable接口:表示String可以比较大小
3.String内部定义了final char[] value用于存储字符串数据
4.String:代表不可变的字符序列。简称:不可变性。
体现:1.当对字符串重新赋值时,需要重写指定内存区域赋值,不能使用原有的value进行赋值。
2.当对现有的字符串进行连接操作时,也需要重新指定内存区赋值,不能使用原有的value赋值。
3.当调用String的replace()方法修改指定字符或字符串时,也需要重新指定内存区赋值,不能使用原有的value赋值
5.通过字面量的方式(区别于new)给定一个字符串赋值,此时的字符串值声明在字符串常量池中
6.字符串常量池中是不会存储相同内容的字符串的。
*/
public class StringTest {
public static void main(String[] args) {
/*
String的实例化方式:
方式一:通过字面量定义的方式---->String s1 = "nbkelas";
方式二:通过new+构造器的方式---->String s3 = new String("nbkelas");
面试题:String s = new String("abc");方式创建对象,在内存中创建两个对象
一个是堆空间中的new结构,另一个是char[]对应的常量池中的数据"abc"
*/
//字符串常量存储在字符串常量池,目的是共享
//字符串非常量对象存储在堆中
String s2 = "nbkelas";
String s1 = "nbkelas";
String s4 = new String("nbkelas");
String s3 = new String("nbkelas");
System.out.println(s1 == s2);//true
System.out.println(s1 == s3);//false
System.out.println(s1 == s4);//false
System.out.println(s3 == s4);//false
System.out.println("************************************");
/*
//字符串的特性
常量与常量的拼接结果在常量池。且常量池中有一个特性,就是常量池中不会存在相同内容的常量。
只要其中有一个结果是变量,结果就在堆中
如果拼接的结果调用intern()方法,返回值就在常量池中。
*/
String ss1 = "hello";
String ss2 = "world";
String ss3 = "hello"+"world";
String ss4 = ss1+"world";
String ss5 = ss1+ss2;
String ss6 = (ss1+ss2).intern();
System.out.println(ss3==ss4);//false
System.out.println(ss3==ss5);//false
System.out.println(ss4==ss5);//false
System.out.println(ss3==ss6);//true
/*
最后总结一下String类型的使用陷阱
String s1 = "a";
说明:在字符串常量池中创建了一个字面量为"a"的字符串。
s1 = s1 + "b";
说明:实际上原来的“a”字符串对象已经丢弃了,现在在堆空间中产生了一个字符串s1+"b"(也就是"ab")。
如果多次执行这些改变串内容的操作,会导致大量副本字符串对象存留在内存中,降低效率。
如果这样的操作放到循环中,会极大影响程序的性能。
String s2 = "ab";
说明:直接在字符串常量池中创建一个字面量为"ab"的字符串。
String s3 = "a" + "b";
说明:s3指向字符串常量池中已经创建的"ab"的字符串。
String s4 = s1.intern();
说明:堆空间的s1对象在调用intern()之后,会将常量池中已经存在的"ab"字符串赋值给s4。
*/
}
}