一文教你学会JAVA包装类和基础类的判等

玩笑

特此声明:本人黑眼圈是熬夜编程所致,本人时间管理一塌糊涂,请放心与吾交友!

测试过程

  1. 测试一:同基础类型的判等
public static void main(String[] args) {
	int ai = 1;
	int bi = 1;
	float af = (float) 0.1;
	float bf = (float) 0.1;
	double ad = 0.1;
	double bd = 0.1;
	if (ai == bi&&af == bf&&ad == bd) {
		System.out.println("right");
	}

结果:right
结论:==可以用于相同基础类型判等。
反思:没啥好反思的,都懂。

  1. 测试二:不同基础类型的判等
public static void main(String[] args) {
	float af = (float) 0.1;
	double bd = 0.1;
	if (af == bd) {
		System.out.println("right");
	}else{
		System.err.println("error");
	}
}

结果:error

public static void main(String[] args) {
	double ad =1;
	float af = 1;
	int ai = 1;
	long al = 1;
	if (af == 1&&ai==1&&ai==1&&al==1) {
		System.out.println("right");
	}else{
		System.err.println("error");
	}
}

结果:right
结论:不同基础类型之间,整数可以用==判等,小数不能用其判等。
反思:特别注意,JAVA中小数默认为double型,这意味着如果float类型小数直接和默认小数判等是错误的

public static void main(String[] args) {
	float af = (float) 0.1;
	if (af == 0.1) {
		System.out.println("right");
	}else{
		System.err.println("error");
	}
}

结果error。

  1. 测试三:相同包装类判等
	public static void main(String[] args) {
		Float af=(float) 3.2;
		Float af2 =(float)3.2;
		if (af == af2) {
			System.out.println("right");
		}else{
			System.err.println("error");
		}
	}

结果:error

	public static void main(String[] args) {
		Integer aI= 3;
		Integer aI2 =3;
		if (aI == aI2) {
			System.out.println("right");
		}else{
			System.err.println("error");
		}
	}

结果:right
结论:我知道你或许会困惑,为什么时而==可判等,时而又不可以。由于包装类很多我就不穷举了,直接放结论吧:

  • Boolean可以用==判等
  • Byte可以用==判等
  • Short只有[-128,127]内的整数可以用==判等,但不建议用。
  • Long只有[-128,127]内的整数可以用==判等,但不建议用。
  • Integer只有[-128,127]内的整数可以用==判等,但不建议用。
  • Float不可用
  • Doulbe不可用
  • Character中ASCII码小于等于127可以用==判等。
    什么,这么多类不一样你记不住?那就不要用==,整数用.equal()很香,小数用其他方法。
  1. 测试四:不同包装类判等

有了三的结论,你还在想==能不能用?行,那我们试试:

	public static void main(String[] args) {
		Integer aI= 87;
		Long aL =(long)87;
		if (aI == aL) {
			System.out.println("right");
		}else{
			System.err.println("error");
		}
	}

结果:你猜?我编译器都报红了!死了这条心吧。
5. 测试五:基础类和其对应包装类判等

	public static void main(String[] args) {
		Integer aI= 87;
		int ai =87;
		if (aI == ai) {
			System.out.println("right");
		}else{
			System.err.println("error");
		}
	}

结果:right

	public static void main(String[] args) {
		Double aD= 1.1;
		double ad =1.1;
		if (aD == ad) {
			System.out.println("right");
		}else{
			System.err.println("error");
		}
	}

结果:right
结论:相同类型,只要有一个是基础类,就完全可以直接==判等。
6. 测试六:基础类和其非对应包装类判等

	public static void main(String[] args) {
		Long aL= (long)1;
		int  ai =1;
		if (aL == ai) {
			System.out.println("right");
		}else{
			System.err.println("error");
		}
	}

结果:right

	public static void main(String[] args) {
		Float aF= (float)1.1;
		double  ad =1.1;
		if (aF == ad) {
			System.out.println("right");
		}else{
			System.err.println("error");
		}
	}

结果:error
结论:和不同基础类的判等一样,包装类完全可以当基础类看待。

原创文章 5 获赞 9 访问量 218

猜你喜欢

转载自blog.csdn.net/weixin_44159662/article/details/105730242