This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
thejwal pavithran wrote:hey guys, thanks ..its working properly now..but could you please explain why calling getClass() method gives Integer as the datatype?
If we call X.getClass(), it will tell us that the class of that object is java.lang.Integer. However, the compiler doesn't know that. When it looks at how we're using X, it only looks at the type the reference is declared to be, which in this case is Object. The only thing the compiler looks at the type of the RHS for is to determine whether it's legal to assign it to the variable on the LHS. After that, it doesn't go, "Oh, X is declared as an Object, but I see it's pointing to an Integer, so I'll let you use it as an Integer."
Although the details are different, this concept is exactly what's happening in your case. It's the difference between the compile-time type of a reference and the runtime type of the object it points to. The compiler only cares about the first one, and in the general case, it's impossible for it to know the second one.