Java String字符串类的equals方法如何避免NullPointerException

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!");
		}

	}

}
我们只要这么调整一下就不错出现空指针异常!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值