第四章03 String类匿名对象

String类匿名对象 与 有名对象 是什么?

public class mainDemo{
	public static void main(String args[]){
		String str = "hello";
		System.out.println(str.equals("hello")); //有名对象调用equals方法,输出true
		System.out.println("hello".equals(str)); //匿名对象调用equals方法,输出true
	}
}

String类匿名对象的用途

  • 范例1:用户输入str,比较str与字符串"hello"是否相等

public class mainDemo{
	public static void main(String args[]){
		String str = "hello";
		if(str.equals("hello")){
			System.out.println("系统启动");
		}
	}
}

当输入的str =“null”, 则代码报错(NullPointerException)。

  • 范例2:用户输入str,比较str与字符串"hello"是否相等(推荐写法)

public class mainDemo{
	public static void main(String args[]){
		String str = "hello";
		if("hello".equals(str)){
			System.out.println("系统启动");
		}
	}
}

即使str为空,也不会报错。

猜你喜欢

转载自blog.csdn.net/guxunshe5199/article/details/81168345