Generics in Java 5/6 are type-erased, which means that any generic type is fundamentally just an Object
type (or whatever the least common denominator type is, which is in this case CharSequence
) at runtime. The appropriate casts are inserted wherever needed. So your method gets type-erased to something that looks like this:
public static CharSequence foo(CharSequence s) {
return (CharSequence) new StringBuilder(s);
}
And your call gets type-erased to this:
System.out.println((String)foo("hello"));
Apparently Java won't bother inserting the (String)
cast if the return value is never used—why bother?