String
package com.yuzhenc.common;
import java.util.Arrays;
public class Test10 {
public static void main(String[] args) {
String str = "abcdefgh";
String str1 = new String();
String str2 = new String("abcdefgh");
String str3 = new String(new char[]{'a','b','c','d','e','f','g','h'});
String str4 = "abcdefgh";
System.out.println(str == str4);
System.out.println(str == str2);
System.out.println(str == str3);
System.out.println(str2 == str3);
String str5 = "a"+"b";
String str6 = str1 + str2;
System.out.println(str.substring(3));
System.out.println(str.substring(3,6));
System.out.println(str.concat("123456"));
System.out.println(str.replace('a','z'));
System.out.println(Arrays.toString("hello sqlboy".split(" ")));
System.out.println(str.toUpperCase());
System.out.println(str.toUpperCase().toLowerCase());
System.out.println(" a b c".trim());
System.out.println(String.valueOf(false));
System.out.println(str.toString());
System.out.println("abcdefgh".equals(str));
System.out.println("abcdefgh".compareTo(str));
System.out.println("abcde".compareTo("abcdefg"));
System.out.println("abcd".compareTo("ABCD"));
System.out.println("abcd".compareTo("bcde"));
}
}
StringBuilder
- 不可变字符串:String
- 可变字符串:StringBuilder StringBuffer
- 在不改变地址的情况下,可以修改字符串,这样的字符串称为可变字符串,否则,该字符串为不可变字符串
package com.yuzhenc.common;
public class Test11 {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("hello sqlboy");
sb.append(" welcome to java");
System.out.println(sb);
sb.delete(3,6);
System.out.println(sb);
sb.deleteCharAt(24);
System.out.println(sb);
sb.insert(24,'a');
System.out.println(sb);
sb.replace(3,9,"lo");
System.out.println(sb);
sb.setCharAt(15,'0');
System.out.println(sb);
for (int i = 0; i < sb.length(); i++) {
System.out.print(sb.charAt(i)+"\t");
}
System.out.println();
System.out.println(sb.substring(0,5));
}
}
StringBuffer
package com.yuzhenc.common;
public class Test12 {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("hello sqlboy");
sb.append(" welcome to java");
System.out.println(sb);
sb.delete(3,6);
System.out.println(sb);
sb.deleteCharAt(24);
System.out.println(sb);
sb.insert(24,'a');
System.out.println(sb);
sb.replace(3,9,"lo");
System.out.println(sb);
sb.setCharAt(15,'0');
System.out.println(sb);
for (int i = 0; i < sb.length(); i++) {
System.out.print(sb.charAt(i)+"\t");
}
System.out.println();
System.out.println(sb.substring(0,5));
}
}
String、StringBuilder和StringBuffer区别
- String类是不可变类,即一旦一个String对象被创建后,包含在这个对象中的字符序列是不可改变的,直至这个对象销毁;
- StringBuffer类则代表一个字符序列可变的字符串,可以通过append、insert、reverse、setChartAt、setLength等方法改变其内容。一旦生成了最终的字符串,调用toString方法将其转变为String;
- JDK1.5新增了一个StringBuilder类,与StringBuffer相似,构造方法和方法基本相同。不同是StringBuffer是线程安全的,而StringBuilder是线程不安全的,所以性能略高。通常情况下,创建一个内容可变的字符串,应该优先考虑使用StringBuilder;
- StringBuilder:JDK1.5开始,效率高,线程不安全;
- StringBuffer:JDK1.0开始,效率低,线程安全。