Arrays are Objects
I'm still under preparation for the SCJP 1.5 exam. I don't care what others say about it, I'm taking it. Though if I fail I swear never to talk about it again. I was suppose to take it last March but then I thought it would be a good idea to postpone it for a while since the holy week would be a good time for me to gain more solid understanding of the language.
Yes, I know certifications are not ways to determine the capability of the programmer. But believe me, the roadpath that you take while learning stuff you missed during work is worth the effort. It actually happened to me before while working on a statistics-related stuff project and it's good that I read on the narrowing and widening stuff which I could never have known during the timespan of that project if I never studied for the exam.
I believe that the SCJP 1.5 is one of the hardest exams in the I.T. world. If I pass, I plan to take the SCJD afterwards(maybe sometime next year). For those who are not familliar with the SCJD, in nutshell it's a hands-on exam in Java(they say it's one of the unique exams available in the I.T. world).
Ok, let's get to the main purpose of this post. A proof of concept that arrays are indeed Objects.
Take a look at this code; //Oooops not that one
Take a look at this code: //the one below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class Main { public static void main(String[] args) { int[] iArray = new int[2];
iArray[0] = 1; iArray[1] = 2;
for (int i : iArray) { System.out.println("Value: " + i); }
}
} |
Not the most elegant code you've seen, I know. But it should compile just fine(untested BTW)
Now, there are strange way of doing things. But it's important that you(actually I) know this for the exam.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class Main2 {
public static void main(String[] args) { Object arrObj = new int[]{1, 2};
int[] iArr = (int[])arrObj;
for(int i : iArr) { System.out.println("Value: " + i); }
}
} |
The code above should compile just fine(again, untested). You might be wondering if it's possible to access the elements using an index from the arrObj reference like this
arrObj[0];
NO! It's not possible. Why? Because the int array object or int[] has already been widened to an object. Because of this, the cast at line 8 was necessary. With the cast having done, it would now be possible to access the elements through the iArr reference like this
iArr[0] = 6;
iArr[1] = 23;
and being more weird, it's also possible to do the following without the iArr reference.
( (int[])arrObj )[0] = 27;
Seriously, I'm getting very very very nervous for the exam. But stay tuned for more weird Java stuff. Laterz! ;)