• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

Question on using return value and not.  RSS feed

 
Ranch Hand
Posts: 37
Eclipse IDE Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In K&B book, there's a question like below:
Given that CharSequence is an interface implemented by both the String and StringBuilder classes, and then given the following method:

public <S extends CharSequence> S foo(S s) {
// INSERT HERE
}

Which of th following can be inserted at //INSERT HERE to compile and run without error?

A : return s;
B : return (Object) s;
C : return s.toString();
D : return new StringBuilder(s);
E : return (S) new StringBuilder(s);
F : return null;

Answer : A and F.

I'm not sure whether D is correct, so I wrote the code below:



Line 4 runs method foo(), no problem; Line 5 prints foo()'s return value, an exception is thrown:
Exception in thread "main" java.lang.ClassCastException: java.lang.StringBuilder cannot be cast to java.lang.String
at Test.main(Test.java:5)

I think both Line 4 and 5 should throw exceptions. Could someone explain to me why there's no exception at Line 4?
Thanks.
 
Ranch Hand
Posts: 287
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The option "D" is wrong because you are hard-coding the return type where it could be String or StringBuilder based on the argument passed.

Line 4 and Line 5 compile and don't throw any exceptions because they are instances of CharSequence
 
Ranch Hand
Posts: 384
Java MyEclipse IDE Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi harsha ,

i have tried this code it does throw exception at line 5 .
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!