这是以前培训的时候整理的,自己验证过,不过不知道归纳的对不对,如有错误不吝赐教~ 一般在做题目和面试中遇到这类问题比较多,现在真正做项目的时候比较都是equals保险点,而且也不需要地址的比较。
public class Test { public static void main(String[] args) { int num1 = 300; Integer num3 = new Integer(300); Integer num4 = new Integer(300); if (num3 == num4) { System.out.print("1 "); } else if (num3.equals(num4)) { System.out.println("2 "); } if (num1 == num3) { System.out.print("3"); } else if (num1 == num4) { System.out.print("4"); } } } -128到127之内的INT型数据都会被视为放在同一地址中 ==比较的是地址 equals比较的是值 但num3的地址不等于num4的地址。。 Int型num1没地址。。。偷懒就算true 如果num1是 Integer 类型则比较就会返回 false . new出来的地址比较一律false 输出:2 3 int中的new和无地址比较为true, 字符串 只要new了比较就是false String s1 = "abc" + "def"; String s2 = new String(s1); if (s1 == s2) System.out.println("1"); if (s1.equals(s2)) System.out.println("2"); 输出:2 Integer i5 = 128; Integer i6 = 128; System.out.println(i5 == i6); System.out.println(i5.equals(i6)); System.out.println("-----------"); Integer i7 = 127; Integer i8 = 127; System.out.println(i7 == i8); System.out.println(i7.equals(i8)); 输出:false true --------- true true public static void main(String[] args) { String s1 = "hello,world" ; String s2 = "hello,"; String s3 = "world" ; String s4 = s2 + s3 ; String s5 = "hello,"+"world"; if(s1==s4){ System.out.print(1); } if(s1==s5){ System.out.print(2); } if(s4==s5){ System.out.print(3); } } 输出:2 Integer a=new Integer (9); int b=9; System.out.println(a==b); 输出:true Integer a=new Integer (9); long c=9; System.out.println(a==c); 输出:true Integer a = new Integer(9); long c =new Long(9); System.out.println(c==a); 输出:true Integer a=new Integer (9); Long c=new Long(9); System.out.println(a==c); 编译报错 5. 以下返回 true 的表达式( AC ) A.”george”==”george” B.”george”=”george” C.“george”.equals(new String(“george”)) D.”george”== new String(“george”)