• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

tricky question

 
velan vel
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hai ranchers
can any one explain on this question


1 class instanceOf
2 {
3 public static void main(String arg[])
4 {
5 G g=new G();
6 H h=new H();
7 System.out.println(h instanceof G);
8 }
9 }
10 class G{}
11 class H{}


a Program compiles correctly and prints true when executed.

b Program compiles correctly and prints false when executed.

c Run time error

d Compile time error.

why it is compile time error

by velan vel
 
Mehul Sanghvi
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess this should explain:

www.visionwebhosting.net

Regards,
Mehul
 
santosh kothapalli
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer is compile time error as class G and class H has no relationship
hence g instanceof H or h instaceof G results in incompatible types.

cheers,
santosh.
 
Hiren Dutta
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think it will an Runtime error as in runtime itself we will know what is the actual instance.
 
Falguni Mehta
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code gives a compile time error as instanceOf is a Java Keyword.
The name of the class cannot be a keyword.
 
Mukesh Mittal
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please check the class name instanceOf. Actual keyword is instanceof (lowercase o)
 
Mukesh Mittal
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with Santosh. Its a compile time error not runtime error.
 
Abdi Duale
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Interesting question. So, when say instanceof operator is used to check whether an object is of a particular type what exactly are we checking in order to determine their relationship? Are we checking if they have the same methods, members etc or what?
For instance, in the above example if H was a subclass of G, the test would return true right? because H would have some commonalities of G such as non-private methods, non-private class variable ( basically is would pass the IS-A test). what exactly does intanceof check?

Thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic