equals()是String类提供的一个方法,是专门负责字符窜内容的比较。
字符串常量就是String的匿名对象。
比如:”hello“就是一个字符串常量,我们通常定义一个字符串会这么做:String str = "hello",其实这种方式实际上就相当于将一个String匿名对象设置了一个名字。
我们在开发中需要的注意的equals()的的使用方法,避免NullPointerException:
package com.jike.jdk8;
public class EqualsTest {
public static void main(String[] args) {
String input = null;
if (input.equals("hello")) {
System.out.println("hello world!");
}
}
}
这段代码很简单。那么运行就会爆出Exception in thread "main" java.lang.NullPointerException,空指针异常。我们在使用equals()的方法时候只需要把 ”字符串常量” 放在equals()前面,String匿名对象也都拥有String类的所有方法和属性。
package com.jike.jdk8;
public class EqualsTest {
public static void main(String[] args) {
String input = "hello";
if ("hello".equals(input)) {
System.out.println("hello world!");
}
}
}
我们只要这么调整一下就不错出现空指针异常!