poniedziałek, 4 lutego 2013

Iteresting facts and traps in Java


I am learning now for some test, and I like to share with my obeservations
Let's start with some example class.

Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. package pl.selfimproveit;
  2.  
  3. public class IntegerTest {
  4.  
  5.     public static void main(String[] args) {
  6.    
  7.         Integer a = 134;
  8.         Integer b = 134;
  9.  
  10.         if (a == b) System.out.println("The same object! - test 1");
  11.         if (a.equals(b)) System.out.println("Equals values -test 1");
  12.        
  13.         Integer c = 12;
  14.         Integer d = 12;
  15.  
  16.         if (c == d) System.out.println("The same object! - test 2");
  17.         if (c.equals(d)) System.out.println("Equals values - test 2");
  18.  
  19.     }
  20. }
How do you think, what will be the ouput?
Equals values -test 1
The same object! - test 2
Equals values - test 2
Suprised? Now you are wondering but how this is possible? Tests 2 tells me that the objects are equal and they have same value, but why this is not the same with Test 1? This is because two instances of the following warpper objects (created via boxing) will be always equal(in meaning ==) when their primitive are equals! Integer in range between -127...128 is a Short, so in first test we were out of the range short, and condition (a==b) failed.


Brak komentarzy:

Prześlij komentarz