Suppose you have the following with you
Object obj;
Object[] objArr;
Let me start with a couple of Java statements :
1. obj = "Java";
2. obj = 10;
3. obj = true;
4. obj = new int[10];
5. objArr = new int[10];
6. objArr = new String[10];
You would be surprised if I tell you that statements 2,3 and 5 are erroneous!
Hold on!
"Every class in Java extends Object" then why such a discrepancy?
Point 1 : Primitive types(numbers, characters, boolean) are not objects(they do not belong to any class).This explains why 2 & 3 are wrong.
Point 2 : String is not a primitive type(this explains why 1 is correct)
Point 3 : All arrays(even arrays of primitive types) derive from the Object class.(this explains why 4 is correct)
Now the question is why 5 is wrong but 6 correct?
You cannot convert an array of ints to an array of Objects, because that will mean each int(of the int[]) getting converted to an Object(of the Object[]) which is not permissible(point1).
But the same thing works for 6 because a String getting converted to an Object is permissible(point2).
So what is the way out for primitive types?
Wrapper classes!
The primitve types can be converted to Objects using the wrapper classes - Integer,Boolean,Double etc.
For example,
Integer a = new Integer(10);
obj = a;
should work fine.
For that matter whenever you need to use a primitve type in a place which expects an Object, use the wrapper classes to generate an Object first.
Note : If you are using Java 1.5 your compiler won't show errors on statements 2 & 3.This is because Java 1.5 supports the automatic conversion of primitive types to the corresponding wrapper objects.However statement 5 would still be an error there.
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment