String s = new String(“hello”)和String s = “hello”;的区别? 字符串比较之看程序写结果 字符串拼接之看程序写结果 注意事项: 1、==比较引用数据类型的时候,比较的时候地址值 2、String类中使用equals方法比较的是字符串的值,因为String类中重写了equals方法
public class StringDemo3 {
public static void main(String[] args) {
String s1 = new String("hello");//地址值在堆里面
String s2 = "hello";//地址值在常量池里面
System.out.println(s1==s2);
System.out.println(s1.equals(s2)); //true
}
1、字符串如果是变量相加,是先在常量池中开辟空间,然后再做拼接。 2、字符串如果是常量相加,是先相加,然后再去常量池中去找,如果找到了,就返回,如果没有找到就开辟新的空间,存储拼接后的值。给个代码好好理解一下:
public class StringDemo5 { public static void main(String[] args) { String s1 = "hello"; String s2 = "world"; String s3 = "helloworld"; String s4 = "hello"+"world"; System.out.println(s3==s4); // true---s4是常量相加先拼接在找 String s5 = s1+s2; //s1,s2就是变量,变量相加要开辟空间导致与s3地址不同 System.out.println(s3==s5); // false System.out.println(s3==(s1+s2)); // false System.out.println(s3.equals(s1+s2)); // true } }
String类的判断功能: boolean equals(Object obj)比较字符串中的内容是否相同,区分大小写比较的 boolean equalsIgnoreCase(String str)比较字符串中的内容是否相同,忽略大小写 boolean contains(String str)判断大的字符串中是否包含小的字符串, 如果包含,返回true,反之返回false 注意:区分大小写 boolean startsWith(String str)测试此字符串是否以指定字符串开头 boolean endsWith(String str)测试此字符串是否以指定字符串结尾 boolean isEmpty()判断字符串是否是空字符串下面代码是举例:
注意:今后在做字符串比较内容的时候,很容易出现NullPointerException空指针异常 * 前面调用方法的变量有可能是null值 * 所以今后,为了避免出现这样的问题,如果是变量1.equals(变量2)的时候,在做equals之前判断一下变量1是不是null * 如果是一个变量1与字符串常量1做equals比较的时候,把字符串常量1放在前面调用方法,因为我们说过单独一个字符串也是一个String对象 *
public class StringDemo6 {
public static void main(String[] args) {
String s1 = "helloworld";
String s2 = "Helloworld";
String s3 = "HelloWorld";
//boolean equals(Object obj)比较字符串中的内容是否相同,区分大小写比较的
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println("********************************");
//boolean equalsIgnoreCase(String str)比较字符串中的内容是否相同,忽略大小写
System.out.println(s1.equalsIgnoreCase(s2));
System.out.println(s1.equalsIgnoreCase(s3));
System.out.println("********************************");
//boolean contains(String str)
//判断大的字符串中是否包含小的字符串,如果包含,返回true,反之返回false
//区分大小写
System.out.println(s1.contains("Hello")); //false
System.out.println(s1.contains("hel"));
System.out.println(s1.contains("owo"));
System.out.println("********************************");
//boolean startsWith(String str)
//测试此字符串是否以指定字符串开头
//区分大小写
System.out.println(s1.startsWith("hel"));
System.out.println(s1.startsWith("Hel")); // false
System.out.println(s1.startsWith("hell34")); // false
System.out.println("********************************");
//boolean endsWith(String str)
//测试此字符串是否以指定字符串结尾
//区分大小写
System.out.println(s1.endsWith("rld"));
System.out.println(s1.endsWith("rlD"));
System.out.println("********************************");
//boolean isEmpty()
//判断字符串是否是空字符串
System.out.println(s1.isEmpty());
System.out.println("********************************");
String s4 = "";
String s5 = null;
System.out.println(s4==s5);
System.out.println(s5==s4);
System.out.println(s4.equals(s5)); //false