Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Kathy Book SCJP question

 
Srinivas Chowdary
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Page 262 , Question 7
1 class Zippy {
2 String[] x;
3 int[] a[] = { {1,2} ,{3} } ;
4 Object c = new long[4];
5 Object[] d =x ;
6 }

answers is compilation succeeds , but it's not the case , Since x is not initalized and we are trying to assign un-initialize variable at line 5.
Compilation should fail at 5.

Is my understanding correct. Book give answer that compilation succeeds.
 
Gudimella Chandana
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Srini,

The class variables will be initialized to their default values. So in your example String x will be initialized to null.

Try this code

public class example{
public static void main(String args[]){
String[] x;
int[] a[] = { {1,2} ,{3} } ;
Object c = new long[4];
Object[] d =x ;
}
}

Then it will give a compilation error as the member variables have to be initialized explicitly..

Hope this clarifies your doubt.
 
Gudimella Chandana
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry, small rectification, please read the word member variables as local variables.
 
jan ter avest
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gudimella, tip:

You can edit your posts by clicking on the blocknote+pencil symbol!
 
John Lincoln
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

What chandanna, said is correct. Since in the question class zippy, all the variables are instance variables,which do need to be intialized.

But i think, the question is regarding Casting. Array X is of type String and object d is type of Object. Since all the objects in java inherit from class "Object", you can use Object to refer to any other type of object. Compiler will not complain. At run-time, it will throw a ClassCast Exception.

Hope this helps

thanks
 
Srinivas Chowdary
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you guys , Sorry i didn't pay attention that it's member of CLASS.
Yes i agree with you guys.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic