File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in K & B self test Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt in K & B self test" Watch "Doubt in K & B self test" New topic
Author

Doubt in K & B self test

ram shah
Greenhorn

Joined: Jun 02, 2007
Posts: 28
This from self test given in K & B book chapter 3.

code
-------------------------------------------------------
class Dims{
public static void main(String[] args){
int [] [] a = {{1,2, }, {3,4}};
int [] b = (int [])a[1];
Object o1 = a;
int [] [] a2 = (int [] [])o1;
int [] b2 = (int []) o1; // Line 1
System.out.println(b[1]);
}}
-------------------------------------------------------

The answer is a class cast exception thrown at line 1. If line 1 is removed the output is 4. Can somebody explain how?
saravana.T kumar
Greenhorn

Joined: Jul 13, 2007
Posts: 23
Here in the code
int [] b2 = (int []) o1; // Line 1
where o1 is an 2-d array

a single Dimension array cannot accept a 2-d array

Its is given in Chap 3 with examples.

int [] [] // 2-d can accept a 2-d or a 1-d array
int [] // can accept a primitive or 1-d array
ram shah
Greenhorn

Joined: Jun 02, 2007
Posts: 28
Thanks for your reply...

But, could you pls explain how the output is 4 when line 1 is removed?
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by ram shah:
...The answer is a class cast exception thrown at line 1. If line 1 is removed the output is 4. Can somebody explain how?

First, consider what happens if that line is removed. The variable 'a' references a "two-dimensional" array. In Java, a multi-dimensional array is really just an array of arrays. So 'a' references an array where the first element a[0] references an array containing {1, 2}, and the second element a[1] references an array containing {3, 4}. In the above code, a[1] is assigned to 'b' (and note the explicit cast in that line is not necessary). Now do you see why the output is 4?

Now consider what happens when line 1 is present. The variable 'o1' is assigned a reference to 'a', which -- as we saw above -- actually references an array of arrays. But in line 1, we try to cast that reference to an array of ints. Do you see what the ClassCastException occurrs?

PS: Please use Code Tags when posting code.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
 
Consider Paul's rocket mass heater.
 
subject: Doubt in K & B self test