public static void main(String[] args) {
/*
字符串的特点
字符串不可变,它们的值在创建后不能被更改
虽然String的值是不可变的,但是它们可以被共享
字符串效果上相当于字符数组(char[]),但是底层原理是字节数组(byte[])
*/
String s1 =new String("abc");
String s2 =new String("abc");
//将字符串转换为字节数组
System.out.println(s1.getBytes());
System.out.println(s2.getBytes());
System.out.println("-------1-------");
System.out.println(s1==s2);
System.out.println(s1.equals(s2));
System.out.println("-------2-------");
//字符串是引用数据类型,再说一遍字符串是引用数据类型, ==比较的是地址值
String s3 ="asdf";
String s4 = s3;
method1(s3);
System.out.println(s4);
System.out.println(s3);
System.out.println("-------3-------");
String s5="dfg";
String s6="dfg";
System.out.println(s5==s6);
}
public static void method1(String s1){
s1="123";
}
重点
String s14 = "ab";
String s24 = "abc";
String s34 = s14 + "c";
System.out.println(s34 == s24); //false
System.out.println(s34.equals(s24)); //true
JVM对于字符串引用,由于在字符串的"+"连接中,有字符串引用存在,而引用的值在程序编译期是无法确定的,即s14 +"c"无法被编译器优化,只有在程序运行期来动态分配并将连接后的新地址赋给s34。所以上面程序的结果也就为false。