字元串定義:一個字元串是由多個字元組成的一串資料(字元序列,字元數組)
構造方法:
- 空字元串
- byte[] -----> String
- char[] -----> String
public class Summarize {
public static void main(String[] args) {
//空字元串
String s = new String();
//利用位元組數組建立位元組數組所表示的字元串
byte[] bytes = {97, 98, 99, 100};
String s1 = new String(bytes);
System.out.println(s1);
//利用位元組數數組的一部分,從byte數組的offset開始的length個位元組值
String s2 = new String(bytes, 1, 3);
System.out.println(s2);
//利用字元數組建立字元數組代表的字元序列
char[] chars = {'A', 'B', 'C', 'D'};
String s3 = new String(chars);
System.out.println(s3);
//public String(String original)
String s4 = new String("abcdef");
System.out.println(s4);
}
}
String對象不可變
String對象一旦被建立後,對象所有的狀态及屬性在其生命周期内不會發生任何變化。
思考:
鍵盤錄入一個任意字元串s,并用一個temp字元串引用也指向它。這個時候修改s字元串的内容,請問temp字元串的内容會随之改變嗎?
public class Demo {
public static void main(String[] args) {
// 建立Scanner對象
Scanner scanner = new Scanner(System.in);
// 鍵盤接收nextLine -- > s
String s = scanner.nextLine();
// temp 指向
String temp = s;
// 更改s内容
s = "aaa";
// 列印
System.out.println("temp = " + temp);
System.out.println("s = " + s);
}
}
答案:不會
原因與本質
- String是一個final類,代表不可變的字元序列
- 字元串是常量,用雙引号引起來,他們的值在建立之後不可更改
- String對象的内容是存儲在字元數組value[ ]中的
字元串常量池
字元串的配置設定和其他對象配置設定一樣,是需要消耗高昂的時間和空間的,而且字元串使用的非常多,
JVM為了提高性能和減少記憶體的開銷,在執行個體化字元串對象的時候進行了一些優化:
使用字元串常量池
首先要明确,Java的雙引号引起來的字面值常量字元串,它們都是對象。
這些對象比較特殊,程式在編譯時期就能确定它們的值
每當建立字元串常量對象時,JVM會首先檢查字元串常量池,如果該字元串對象引用已經存在常量池中,那麼就直接傳回常量池中的執行個體引用。如果字元串對象引用不存在于常量池中,就會執行個體化該字元串并且将其引用放到常量池中。
//練習
class Demo1{
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = new String("hello");
//String.equals預設重寫了Object.equals方法,比較的是字元串的值
System.out.println(s1 == s2); //false
System.out.println(s1.equals(s2)); //true
String s3 = new String("world");
String s4 = "world";
System.out.println(s3 == s4); //false
System.out.println(s3.equals(s4)); //true
}
}
字元串常見問題與練習
class Demo2{
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "Hel" + "lo";
String s3 = "Hel" + new String("lo");
String s4 = new String("Hello");
String s5 = "H"; String s6 = "ello";
String s7 = s5 + s6;
System.out.println(s1 == s2); //true
System.out.println(s1 == s3); //false
System.out.println(s3 == s4); //false
System.out.println(s1 == s7); //false
}
}