public class Test14
{
public static void main(String[] args)
{
int i=5;
double d=5.0;
boolean b1=(i==d);
System.out.println(b1);
char c='a';
long l=97l;
boolean b2=(c==l);
System.out.println(b2);
boolean b3=true;
boolean b4=false;
boolean b5=(b3==b4);
System.out.println(b5);
}
}
上面的代码输出结果为:true、true、false不太理解。
i为int类型,且为5,d为double类型,且为5.0,为什么在进行比较是否相等时尽然是相等的,是在比较的过程中i自动升级类型成double类型了吗?
同理是字符c和long长整型。
为什么会输出来结果为true,而不是false?java里面哪些运算符在进行互相运算时会自动升级类型?
int与其他类型运算时,如long,double等,默认转换为long、double进行比较。
数值型数据运算时低精度会自动转为高精度类型
== 比较的时两边的首地址(计算机中的存储位置)
// 自动转换按从低到高的顺序转换。不同类型数据间的优先关系如下:
// 低--------------------------------------------->高
// byte,short,char-> int -> long -> float -> double
int i = 5;
double d = 5.0;
boolean b1 = (i == d); // 比较之前,内部int i 事先会转化为double
System.out.println(b1);
char c = 'a';
int cc = c;
System.out.println(cc);// 97
long l = 97l;
boolean b2 = (c == l);
System.out.println(b2);
boolean b3 = true;
boolean b4 = false;
//== 基本类型比较的是值 不是内存地址
boolean b5 = (b3 == b4);
System.out.println(b5);