Why the following code will yield a nice ClassCastException:
public static void main(String []args){
StringBuilder s1 = new StringBuilder("quaqua");
StringBuilder s12= (StringBuilder)s1.subSequence(0,3);
System.out.println(s12);
}
whereas the following code ( substituting StringBuilder with String):
public static void main(String []args){
String s1 = new String("quaqua");
String s12= (String)s1.subSequence(0,3);
System.out.println(s12);
}
works fine?;
I understand that there is the method substring(int begin, int end);
however I am just curious why the cast with StringBuilder (which implements CharSequence) does not work whereas with String works.
Thanks in advance.
This is because the actual class that StringBuilder.subSequence returns is String:
...
public CharSequence subSequence(int start, int end) {
return substring(start, end);
}
public String substring(int start, int end) {
...
return new String(value, start, end - start);
}
You cannot cast String to StringBuilder.