• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String stuff

 
meeta gaur
Ranch Hand
Posts: 305
Notepad Tomcat Server Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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 ?
 
Henry Wong
author
Marshal
Pie
Posts: 21021
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Joanne Neal
Rancher
Posts: 3742
16
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
meeta gaur
Ranch Hand
Posts: 305
Notepad Tomcat Server Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to all.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic