为什么java中“1000==1000”为false,“100==100”为true呢?
如果你尝试运行以下代码
public class test {
public static void main(String[] args) {
Integer a=100,b=100;
System.out.println(a==b);
Integer c=1000,d=1000;
System.out.println(c==d);
int e=100,f=100;
System.out.println(e==f);
int g=1000,h=1000;
System.out.println(g==h);
}
}
你会得到
true
false
true
true
为什么会出现不同呢?先来看看java中int和integer的基本知识:
- Integer是int的包装类,int则是java的一种基本数据类型
- Integer变量必须实例化后才能使用,而int变量不需要 (最新的版本Integer实例化可以直接赋值,如上代码,而不需要使用Integer a=new Integer(100)这种实例化方式)
- In