String using sb.reverse() without new operator
Hi, this is a portion of my code:
String sc = Integer.toString(c);
StringBuffer sb =new StringBuffer(sc);
String scr =new String(sb.reverse());
c is a value that a user enters. Now my question is in the last line, it works fine if i type it in the following way:
String scr =new String(sb.reverse());
But if i simply try to use
String scr= sb.reverse();
I get an error saying:
Found java.lang.StringBuffer but expected java.lang.String
As far as i know, String bla = new String("bla"); and String bla = "bla" are the same thing, so why does one work and the other does not?
[742 byte] By [
Overkilla] at [2007-11-27 10:29:07]

> As far as i know, String bla = new String("bla");
> and String bla = "bla" are the same thing, s
No, they are not.
The first one refereneces to the string value put by the compiler into the constant pool, and the second one will create a new String object (based on the same value).
== will show they are different objects.
A String and String Buffer are same in human sense.But java treats String and String Buffer as two different types.The reason for this is:
Once we create a String Object we cannot modify it.When we make changes to it using some operators like + ,.concat that means we are creating a new string object and not modifying older version.
But String Buffer allows modifications on the same object that it created earlier.
> So basically, i have to tell java that the result of
> sb.reverse() should be converted into a string right?
Correct. On StringBuffer you can use the toString() method.