String 类代表字符串,Java程序中的所有字符串的值(“abc”)都作为此类的示例实现。
字符串是常量:他们的值在创建之后不能更改
例如:String str=“abc”;
public String();空构造
public String(byte[] bytes):把字符数组转换成字符串
public String(byte[] bytes,int offset,int length):把字符数组的一部分转换成字符串
public String(char[] value);把字符数组转换成字符串
public String(char[] value,int offset,int count);把字符数组的一部分转换成字符串
public String(String orginal);吧字符串常量转换字符串;
常用的方法:
public int length();获取字符串串的长度;
public class StringDemo2 {
public static void main(String[] args) {
String s1=new String();
System.out.println("s1:"+s1);//常量池中的一个数据(空格)
System.out.println("s1.length:"+s1.length());//s1.length()获取字符串的长度
//public String(byte[] bytes):把字节数组转换成字符串
System.out.println("----------1----------");
byte [] bys= {101,102,103,104,105};
String s2=new String(bys);
System.out.println("s2:"+s2);//字节数组的数字会先通过码表转换之后再输出
System.out.println("s2.length:"+s2.length());
System.out.println("----------2-----------");
//public String(byte[] bytes,int offset,int length);把字节数组的一部分转换成字符串
String s3=new String(bys,1,2);//bys字节数组,从索引为1的位置开始截取长度为2字节数组
System.out.println("s3:"+s3);
System.out.println("s3.length:"+s3.length());
System.out.println("----------3-------------");
//public String(char[] value);把字符数组转换成字符串
char[] chr= {'我','太','阳','a','b','c'};
String s4=new String(chr);
System.out.println("chr:"+s4);
System.out.println("chr.length:"+s4.length());
//public String(char[] value,int offset,int count);把字符数组的一部分转换成字符串
String s5=new String(chr,1,3);
System.out.println("s5:"+s5);
System.out.println("s5.length:"+s5.length());
//public String(String original);把字符串出常量转换字符串
System.out.println("-----------4-----------");
String s6=new String("小朋友");
System.out.println(s6);
System.out.println(s6.length());
}
}
String s=new String(“hello”);和String s="hello"的区别
前者会创建两个对象,后者只会创建一个对象;
public class StringDemo3 {
public static void main(String[] args) {
String s=new String("hello");
String s1="hello";
System.out.println(s==s1);
System.out.println(s.equals(s1));
}
}
如果是字符串相加的话,是先开辟空间,再去拼接
如果是字符串常量,是先拼接,然后再去常量池寻找,如果有就直接返回,没有就开辟新的空间
public class StringDemo4 {
public static void main(String[] args) {
String s1="hello";
String s2="world";
String s3="helloworld";
System.out.println(s3==s1+s2);//字符串相加,==比较地址值是否相等
System.out.println(s3.equals(s1+s2));//字符串相加,equals比较两个值是否相等
System.out.println(s3=="hello"+"world");//字符串常量相加;
}
}