標籤:java 學習
String類的概述和使用
(1)多個字元組成的一串資料。
其實它可以和字元數組進行相互轉換。
(2)構造方法:
A:public String()
B:public String(byte[] bytes)
C:public String(byte[] bytes,int offset,int length)
D:public String(char[] value)
E:public String(char[] value,int offset,int count)
F:public String(String original)
下面的這一個雖然不是構造方法,但是結果也是一個字串對象
G:String s = "hello";
(3)字串的特點
A:字串一旦被賦值,就不能改變。
注意:這裡指的是字串的內容不能改變,而不是引用不能改變。
B:字面值作為字串對象和通過構造方法建立對象的不同
String s = new String("hello");和String s = "hello"的區別?
(4)字串的面試題(看程式寫結果)
A:==和equals()
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2);// false
System.out.println(s1.equals(s2));// true
String s3 = new String("hello");
String s4 = "hello";
System.out.println(s3 == s4);// false
System.out.println(s3.equals(s4));// true
String s5 = "hello";
String s6 = "hello";
System.out.println(s5 == s6);// true
System.out.println(s5.equals(s6));// true
B:字串的拼接
String s1 = "hello";
String s2 = "world";
String s3 = "helloworld";
System.out.println(s3 == s1 + s2);// false
變數拼接,先開闢空間,地址值當然不一樣
System.out.println(s3.equals((s1 + s2)));// true
System.out.println(s3 == "hello" + "world");// false 這個我錯了,應該是true
兩個常量拼接,先拼接,然後找有沒有,s3有
System.out.println(s3.equals("hello" + "world"));// true
String類的概述和使用