String类对象表示不可修改的Unicode编码字符串
import java.io.UnsupportedEncodingException;
//字符串的一些构造方法
public class TestStringConstructor {
public static void main(String[] args) {
// 初始化一个新创建的 String 对象,使其表示一个空字符序列
String s = new String();
System.out.println(s.length());
System.out.println(s);// 这块输出的是""而不是null
byte[] b = { 97, 98, 99, 100, 101, 102, 103 };// 这个要理解
// 通过使用平台的默认字符集解码指定的 byte 数组,构造一个新的 String
System.out.println(new String(b));
// 通过使用平台的默认字符集解码指定的 byte 子数组,构造一个新的 String
System.out.println(new String(b, 3, 2));
try {
// 通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String
System.out.println(new String(b, "GBK"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
char[] c = { 'h', 'i', 'j', 'k', 'l', 'm', 'n' };
// 分配一个新的 String,使其表示字符数组参数中当前包含的字符序列
System.out.println(new String(c));
// 分配一个新的 String,它包含取自字符数组参数一个子数组的字符
System.out.println(new String(c, 2, 4));
System.out.println(new String("Hello,World!"));
System.out.println(new StringBuffer("abc"));
}
}
StringBuffer类对象保存可修改的Unicode字符序列
StringBuilder类JDK5.0以后引入,该类能够提供与StringBuffer相同的功能,二者区别如下:
1.StringBuffer类是线程安全的,而StringBuilder则不是,即不保证其对象的同步性,在多线程环境中是不安全的。2.StringBuilder在性能上要比StringBuffer好一些
import java.util.Date;
//字符串缓冲区的一些基本操作
public class TestStringBuffer {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("abc");
sb.append("defg");//附加字符串
System.out.println(sb);
sb.insert(3, "---");//插入字符串
System.out.println(sb);
sb.reverse();//倒转字符串
System.out.println(sb);
sb.append(new Date());
System.out.println(sb);
}
}