String類(lèi)
String對(duì)象的創(chuàng)建方式
1、 String s1 = "alan"; 創(chuàng)建一個(gè)字符串對(duì)象alan,名為s1.或者說(shuō)s1指向?qū)ο骯lan
2、String s2 = new String(); 創(chuàng)建一個(gè)空字符串對(duì)象,名為s2
3、String s3 = new String("alan"); 創(chuàng)建一個(gè)字符串對(duì)象alan,名為s3
- 字符串與byte數(shù)組之間的轉(zhuǎn)換。
package com.alan.string;
import java.io.UnsupportedEncodingException;
public class StringDemo3 {
public static void main(String[] args) throws UnsupportedEncodingException {
// 字符串與byte數(shù)組之間的相互轉(zhuǎn)換
String str = new String("JAVA 編程 基礎(chǔ)");
//將字符串轉(zhuǎn)換為byte數(shù)組,并打印輸出
byte[] arrs = str.getBytes("GBK");
for(int i = 0;i<arrs.length;i++) {
System.out.print(arrs[i]+" ");
}
System.out.println();
//將byte數(shù)組轉(zhuǎn)回字符串,展示
String str1 = new String(arrs,"GBK");
System.out.println(str1);
}
}
等于“==”運(yùn)算符與equals方法的區(qū)別

image.png
package com.alan.string;
public class StringDemo4 {
public static void main(String[] args) {
// ==和equals的區(qū)別
//定義三個(gè)字符串,內(nèi)容都是alan
String str1 = "alan";
String str2 = "alan";
String str3 = new String("alan");
System.out.println("str1和str2的內(nèi)容相同?"+str1.equals(str2));
System.out.println("str1和str2的內(nèi)容相同?"+str1.equals(str3));
System.out.println("str1和str2的地址相同?"+ (str1==str2));
System.out.println("str1和str2的地址相同?"+ (str1==str3));
}
}
字符串不可變性

image.png
StringBuilder
String具有不可變性,StringBuilder不具備
建議:當(dāng)頻繁操作字符串的時(shí)候,使用StringBuilderStringBuilder與StringBuffer
1、 二者基本相似
2、StringBuffer是線程安全的,StringBuilder則沒(méi)有,所以性能略高。
3、字符串處理一般都是單線程的,無(wú)需考慮線程安全性,所以使用StringBuilder.
package com.alan.string;
public class StringDemo5 {
public static void main(String[] args) {
//定于一個(gè)字符串“你好”
StringBuilder str = new StringBuilder("你好");
str.append(",alan");
System.out.println(str);
//將字符串變成"你好,ALAN"
//方式1
System.out.println(str.delete(3, 7).insert(3, "ALAN"));
//方式2
System.out.println(str.replace(3, 7, "ALAN"));
//最后存在堆中的內(nèi)容
System.out.println(str);
}
}