How come I can't use toLowerCase() after using a StringBuffer?

java, string

Solution

Well, it doesn't. You'd have to use `.toString().toLowerCase()`:

String lowercase = sb.toString().toLowerCase();

If you want to be very strict about not creating unnecessary instances, you can iterate all characters, and lowercase them:

for (int i = 0; i < sb.length(); i++) {
   char c = sb.charAt(i);
   sb.setCharAt(i, Character.toLowerCase(c));
}

And finally - prefer `StringBuilder` to `StringBuffer`

Problem

I read that in Java, String is immutable, so we can't really use toLowerCase intuitively, i.e the original string is unmodified: ``` String s = "ABC"; s.toLowerCase(); > "ABC" ``` But even using StringBuffer(which supports mutable Strings) does not work ``` StringBuffer so = new StringBuffer("PoP"); so.toLowerCase() > Static Error: No method in StringBuffer has name 'toLowerCase' ``` I appreciate any tips or advice.

Original source