This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes String stuff Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "String stuff" Watch "String stuff" New topic
Author

String stuff

meeta gaur
Ranch Hand

Joined: Dec 05, 2012
Posts: 226


Example.java:12: error: incompatible types
String sub=s.subSequence(5,12);
^
required: String
found: CharSequence
1 error

String class implements CharSequence interface then why can't it hold returned object ?


OCAJP
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 16811
    
  19

meeta gaur wrote:
Example.java:12: error: incompatible types
String sub=s.subSequence(5,12);
^
required: String
found: CharSequence
1 error

String class implements CharSequence interface then why can't it hold returned object ?


All String objects are IS-A CharSequence, but not all CharSequence objects are IS-A String.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3011
    
    9
meeta gaur wrote:String class implements CharSequence interface then why can't it hold returned object ?

Because CharBuffer, Segment, StringBuffer and StringBuilder also implement CharSequence and so the compiler doesn't know that it will definitely be a String that is returned.
You can override this by putting an explicit cast in your code

This says to the compiler - I know that the object returned from the method could be something other than a String, but I'm telling you it will be a String
Of course, if, at run time, something other than a String is returned, you will get a ClassCastException.


Joanne
meeta gaur
Ranch Hand

Joined: Dec 05, 2012
Posts: 226

Thanks to all.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String stuff
 
Similar Threads
[Java Programmer Certification Mock Exam (Dan Chisholm) wrong solution..
Making custom StringBuilder (or StringBuffer) - forget thread-safe / unsafe
Need help in generics
scjp 1.5 question related to collections
Help for generics