java:String类的概述和构造方法
public class Demo2_stringCon {
// public string();
// public string(byte[]bytes);把字节数组转换成字符串
// public string(byte[]bytes,int index,int length);把字节数组的一部分转换成字符串
// public string(char[]value);把字符数组转换成字符串
// public string(char[]value,int index,int length);把字符数组的一部分转换成字符串
// public string(string original);把字符串常量转换成字符串
public static void main(String[] args) {
// 字符串是常量,一旦赋值就不能被更改
String str="abc";//"abc"可以看成一个字符串对象
str="def";//当把def赋值给str,原来的abc变成了垃圾被回收
System.out.println(str.toString());//具体可见String中的toString()方法重写过程,返回的是对象本身
System.out.println(str);
String s1=new String();
System.out.println("空参构造s1的值:"+s1);
byte[] arr1= {97,98,99};
String s2=new String(arr1);//解码,将计算机读得懂的转换成我们读的懂的
System.out.println("把字节数组转换成字符串:"+s2);//对应项目字符集解码的值
byte[] arr2= {97,98,99,100,101,102};
String s3=new String(arr2,2,3);//2代表索引,3代表转换多少个
System.out.println("把字节数组的一部分转换成字符串:"+s3);
char[] arr3= {'a','b','c','d','e','f'};
String s4=new String(arr3);
System.out.println("把字符数组转换成字符串:"+s4);
char[] arr4= {'a','b','c','d','e','f'};
String s5=new String(arr2,2,3);//2代表索引,3代表转换多少个
System.out.println("把字符数组的一部分转换成字符串:"+s5);
String s6=new String("呵呵");
System.out.println("把字符串常量转换成字符串:"+s6);
}
}
运行结果: