★String类
字符串的比较
==比较的是字符串地址
比较字符串内容有两个常用方法:
- public boolean equals(Object obj),严格区分英文大小写
- public boolean equalsIgnoreCase(String str),忽略英文大小写
字符串常量与字符串对象进行equals比较时,推荐把字符串常量写在前面
即"abc".equals(str),而不是str.equals(“abc”),因为可能会报空指针异常
String str1 = "hello";//字符串常量池
String str2 = "hello";//字符串常量池
char[] chars = {'h', 'e', 'l', 'l', 'o'};
String str3 = new String(chars); //堆内存的str3对象
System.out.println(str1 == str2);//true
System.out.println(str2 == str3);//false
System.out.println("java".equals("java"));//true
System.out.println("java".equals("JAVA"));//false
System.out.println("java".equalsIgnoreCase("JAVA"));//true
注意:Arrays.toString(数组对象)和数组对象.toString()方法
int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3};
//Arrays的toString方法
String str1 = Arrays.toString(arr1);
String str2 = Arrays.toString(arr2);
System.out.println(str1);//[1, 2, 3]
System.out.println(str2);//[1, 2, 3]
System.out.println(str1.equals(str2));//true
//Object的toString方法
String str3 = arr1.toString();
String str4 = arr2.toString();
System.out.println(str3);//[I@66cd51c3
System.out.println(str4);//[I@4dcbadb4
System.out.println(str3.equals(str4));//false
System.out.println("123".equals("123"));//true