Comparing Interger Wrapper class with Equals and ==

    package Equalsand_Twoequals;

    public class IntegerCompare {

	public IntegerCompare() {
		// TODO Auto-generated constructor stub
	}
	public static void main(String[] args) {
		Integer i1 = 10;
		Integer i2 = 10;
		Integer i3 = new Integer(10);
		Integer i4 = new Integer(10);
		int i5 = 10;
		
		Integer i6 = 1000;
		Integer i7 = 1000;
		Integer i8 = new Integer(1000);
		Integer i9 = new Integer(1000);		
		int i10 = 1000;
		/* Equals*/
		System.out.println("EQUALS");
		System.out.println(i1.equals(i2));             
		System.out.println(i1.equals(i3));
		System.out.println(i3.equals(i4));
		System.out.println(i1.equals(i5));
		System.out.println(i3.equals(i5));
		
		System.out.println(i6.equals(i7));
		System.out.println(i6.equals(i8));
		System.out.println(i8.equals(i9));
		System.out.println(i6.equals(i10));
		System.out.println(i8.equals(i10));
		
		
		/*==*/
		System.out.println("==");
		System.out.println(i1==i2);             
		System.out.println(i1==i3);
		System.out.println(i3==i4);
		System.out.println(i1==i5);   // int compared either to Integer or new Integer will result true   
		System.out.println(i3==i5);		 // int compared either to Integer or new Integer will result true	
		
		System.out.println(i6==i7);   // false because == will compare only upto 127 
		System.out.println(i6==i8);
		System.out.println(i8==i9);
		System.out.println(i6==i10); // int compared either to Integer or new Integer will result true
		System.out.println(i8==i10); // int compared either to Integer or new Integer will result true
		
		
		Integer i11 = 10;
		Integer i12 = i11;
		Integer i13 = new Integer(10);
		Integer i14 = i13;
		int i15 = 10;
		
		Integer i16 = 1000;
		Integer i17 = i16;
		Integer i18 = new Integer(1000);
		Integer i19 = i18;		
		int i20 = 1000;
		
		System.out.println("======");
		
		System.out.println(i11==i12);
		System.out.println(i13==i14);   // Imp one
		System.out.println(i14==i11);
		
		System.out.println(i16==i17);	// Imp One
		System.out.println(i18==i19);   // Imp one
		System.out.println(i19==i16);
	}
}
       

Output is

EQUALS
true
true
true
true
true
true
true
true
true
true
==
true
false
false
true
true
false
false
false
true
true
======
true
true
false
true
true
false

Leave a comment

Your email address will not be published. Required fields are marked *