Thursday 2 October 2014

Exploring Integer - the wrapper class for primitive int

Try `==` and `equals()` for Integer



  1. public class IntegerClass {

  2. public static void main(String[] args) {

  3. Integer i1 = 11;
  4. Integer i2 = 11;
  5. if(i1 == i2){
  6. System.out.println("i1 == i2");
  7. }
  8. if(i1.equals(i2)){
  9. System.out.println("i1.equals(i2)");
  10. }
  11. /* * * * * * * * * * * * * * * * * * * * * */
  12. Integer i3 = 128;
  13. Integer i4 = 128;
  14. if(i3 == i4){
  15. System.out.println("i3 == i4");
  16. }else{
  17. System.out.println("i3 != i4");
  18. }
  19. /* * * * * * * * * * * * * * * * * * * * * */
  20. if(i3.equals(i4)){
  21. System.out.println("i3.equals(i4)");
  22. }else{
  23. System.out.println("!(i3.equals(i4))");
  24. }
  25. }
  26. }
Line 5 will be actually compiled as Iinteger.valueOf(11)
Thanks to compiler which actually autoboxes primitive values to corresponding wrapper classes.