String与基本数据类型、包装类
//String --> 基本数据类型、包装类:调用包装类的静态方法:parseXxx(str)
//基本数据类型、包装类-->String:调用String重载的valueOf(xxx)
@Test
public void test1(){
String str1 = "123";
int num = Integer.parseInt(str1);
String str2 = String.valueOf(num);
String str3 = num + ""; //堆
System.out.println(str1 == str3);//false
}
String与char[]
//String --> char[]:调用toCharArray()
//char[] --> String:调用String构造器
@Test
public void test2(){
String str1 = "abc123";
char[] charArray = str1.toCharArray();
for(int i = 0; i < charArray.length;i++){
System.out.println(charArray[i]);
}
char[] arr = new char[]{'h','e','l','l','o'};
String str2 = new String(arr);
System.out.println(str2);
}
结果
a
b
c
1
2
3
hello
String 与 byte[]之间的转换
//String --> byte[]:调用String的getBytes()
//byte[] --> String:调用String的构造器
//编码:字符串-->字节
//解码:字节-->字符串
@Test
public void test3() throws UnsupportedEncodingException {
String str1 = "abc123中国";
byte[] bytes = str1.getBytes();
System.out.println(Arrays.toString(bytes));
byte[] gbks = str1.getBytes("gbk");
System.out.println(Arrays.toString(gbks));
String str2 = new String(bytes);
System.out.println(str2);
String str3 = new String(gbks);
System.out.println(str3);
String str4 = new String(gbks,"gbk");
System.out.println(str4);
}
结果
[97, 98, 99, 49, 50, 51, -28, -72, -83, -27, -101, -67]
[97, 98, 99, 49, 50, 51, -42, -48, -71, -6]
abc123中国
abc123�й�
abc123中国