1、字符串(String)
①字符串是屬於引用數據類型。
②String 類代表字符串。Java 程序中的所有字符串字面值(如 "abc" )都作爲此類的實例實現。字符串是常量;它們的值在創建之後不能更改。
package cn.tx.string;
public class StringDemo1 {
public static void main(String[] args) {
//定義一個字符串變量,賦值“ffx”
String str = "ffx";
System.out.println("輸出str:"+str);
}
}
2、字符串的構造器
常用的構造器:
例子如下:
public class StringDemo2 {
public static void main(String[] args) {
//創建一個空字符串的對象
String s = new String();
System.out.println("輸出字符串s:"+s);
//創建一個字節數組
byte[] bs ={96,97,99,105,108};
//以字節數組作爲參數的字符串對象的創建
String s1 = new String(bs);
//把字節數組中的每一個數值轉換成相應的ascii的zifu後組裝成字符串
System.out.println("以字節數組作爲參數創建字符串:"+s1);
//第一個參數是字節數組,第二個參數是以指定索引開始(0開始),第三個參數是截取的長度,注意數組不要越界
String s2 = new String(bs,3,2);
System.out.println("以字節數組作爲參數的字符串截取創建:"+s2);
//創建一個字符數組
char[] cs ={'a','c','f','f','x','u'};
String s3 = new String(cs);
System.out.println("以字符數組作爲參數創建字符串:"+s3);
String s4 = new String(cs,3,2);
System.out.println("以字符數組作爲參數的字符串截取創建:"+s4);
//以常量的字符串作爲參數
String s5 = new String("ffxilu");
System.out.println("以常量字符串作爲參數:"+s5);
}
}
3、最常見的面試題String s1 = new String(“abc”);和String s2 = “abc”;有什麼區別?
前者創建了兩個對象,後者創建一個對象。
== :比較基本類型,比較值是否相同。比較引用類型,比較地址值是否相同。
equals();:比較引用類型默認比較的是地址是否相同,對於一般的引用類型都會重寫該方法,一個類具體比較的是什麼我們就得分析源碼。
具體看代碼:
public class StringDemo3 {
public static void main(String[] args) {
//創建常理的字符串
String str = "helloworld";
//創建字符串的對象
String str1 = new String("helloworld");
//兩個字符串地址的比較
System.out.println(str == str1);
//兩個字符串的值比較
System.out.println(str.equals(str1));
//定義一個字符串的常量
String str2 = "renliang";
String str3 = "renliang";
//判斷兩個地址是否相等,比較的是地址
System.out.println(str2 == str3);
System.out.println(str2.equals(str3));
String str4 = "hello";
String str5 = "world";
String str6 = "helloworld";
//str4和str5拼接後一定會產生新的字符串(即使在數據共享區中存儲拼接後的值相等的字符串)
System.out.println(str6 == (str4+str5));
//如果是兩個沒有引用的常量做拼接那麼就會去數據共享區中查找是否有相等的字符串,如果有相等的就不去創建新的字符串了,直接使用。
System.out.println(str6 == ("hello"+"world"));
}
}