aspose file tools*
The moose likes Beginning Java and the fly likes String stuff Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String stuff" Watch "String stuff" New topic
Author

String stuff

meeta gaur
Ranch Hand

Joined: Dec 05, 2012
Posts: 305


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 ?


My one regret in life is that I am not someone else.
- Woody Allen
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18824
    
  40

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: 3527
    
  15
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: 305

Thanks to all.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String stuff