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]
# 1

public StringBuffer reverse()

/*

The character sequence contained in this string buffer is replaced

by the reverse of the sequence.

*/

BIJ001a at 2007-7-28 17:55:40 > top of Java-index,Java Essentials,Java Programming...
# 2

String scr= sb.reverse().toString();

BIJ001a at 2007-7-28 17:55:40 > top of Java-index,Java Essentials,Java Programming...
# 3

Both String and StringBuffer implement CharSequence and a String can be constructed from a CharSequence. A StringBuffer is not a String and sb.reverse() returns a StringBuffer not a String.

sabre150a at 2007-7-28 17:55:40 > top of Java-index,Java Essentials,Java Programming...
# 4

> 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.

BIJ001a at 2007-7-28 17:55:40 > top of Java-index,Java Essentials,Java Programming...
# 5

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.

oasis.deserta at 2007-7-28 17:55:40 > top of Java-index,Java Essentials,Java Programming...
# 6

So basically, i have to tell java that the result of sb.reverse() should be converted into a string right? (If thats the case then sorry, cause i thought that assigning sb.reverse() to a string would automatically make java convert it into a string)

Overkilla at 2007-7-28 17:55:40 > top of Java-index,Java Essentials,Java Programming...
# 7

> 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.

sabre150a at 2007-7-28 17:55:40 > top of Java-index,Java Essentials,Java Programming...
# 8

K thanks everyone :)

Overkilla at 2007-7-28 17:55:40 > top of Java-index,Java Essentials,Java Programming...