File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question on using return value and not. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question on using return value and not." Watch "Question on using return value and not." New topic

Question on using return value and not.

Jeffrey Tian
Ranch Hand

Joined: Jun 02, 2010
Posts: 34
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) {

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(

I think both Line 4 and 5 should throw exceptions. Could someone explain to me why there's no exception at Line 4?
Harsha Smith
Ranch Hand

Joined: Jul 18, 2011
Posts: 287
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
naveen yadav
Ranch Hand

Joined: Oct 23, 2011
Posts: 384

Hi harsha ,

i have tried this code it does throw exception at line 5 .
I agree. Here's the link:
subject: Question on using return value and not.
It's not a secret anymore!