String对象的特点

String对象的特点:

以“” 方式给出的字符串,只要字符串序列相同(顺序和大小相同),无论在程序代码中出现几次,JVM都只会建立一个String对象,并在字符串池中维护。

public class StudentTest{
	public static void main(String args[]) {
		//采用构造方法的方式得到对象
		char[] chs = {'a','b','c'};//这个第一次写的时候写成了双引号,值得注意
		String s1 = new String(chs);
		String s2 = new String(chs);
		System.out.println(s1 == s2);//这个比较的是s1和s2的地址  结果是false
		//采用直接赋值的方式得到对象
		String s3 = "abc";
		String s4 = "abc";
		System.out.println(s3 == s4);//这个比较的是s3和s4的内容  结果是true
		//比较字符串对象地址是否相同
		System.out.println(s1==s3);//结果是 false
	}
}

字符串的比较

使用==作比较

        基本类型:比较的是数据值是否相同

        引用类型:比较的是地址值是否相同

对于字符串来说

public static void main(String args[]) {
		//构造方法的方式得到对象
		char[] chs = {'a','b','c'};
		String s1 = new String(chs);
		String s2 = new String(chs);
		
		//直接赋值的方式得到对象
		String s3 = "abc";
		String s4 = "abc";
		
		//比较字符串地址是否相同
		System.out.println(s1==s2);//false
		System.out.println(s1==s3);//false
		System.out.println(s3==s4);//true
		
		//比较字符串对象内容是否相同
		System.out.println(s1.equals(s2));//true
		System.out.println(s1.equals(s3));//true
		System.out.println(s3.equals(s4));//true
	}

猜你喜欢

转载自blog.csdn.net/weixin_53270267/article/details/124215763