String类的构造方法
String s1 = "hello,world!";
System.out.println(s1); //hello,world!
s1这个变量中保存的是一个内存地址,然而输出的是一个字符串,说明String类重写了toString()方法。
byte[] bytes = {97,98,99}; //97是a,98是b,99是c
String s2 = new String(bytes);
System.out.println(s2); //abc
将byte数组转成字符串
String s3 = new String(bytes, 1, 2);
System.out.println(s3); //bc
new String(字节数组,数组下标起始位置,长度)
可将byte数组中的一部分转换成字符串
char[] chars = {'w', 'h', 'a', 't', 's', 'u', 'p', '?'};
String s4 = new String(chars);
System.out.println(s4); //whatsup?
将char数组转成字符串
String s5 = new String(chars, 0, 4);
System.out.println(s5); //what
将char数组的一部分转成字符串
总结
关于String类中的构造方法
1.String s = new String("");
2.String s = “”; 最常用
3.String s = new String(byte数组);
4.String s = new String(byte数组,起始下标,长度);
5.String s = new String(char数组);
6.String s = new String(char数组,起始下标,长度);