Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference in converting string buffer to string using .toString(), String.valueOf() and + " "

What is the main difference in conversion of StringBuffer to String for the following three cases :

Case 1 : Using toString()

StringBuffer sb = new StringBuffer("Welcome");
String st = sb.toString();

Case 2 : Using + ""

StringBuffer sb = new StringBuffer("Welcome");
String st = sb + "";

Case 3 : Using String.valueOf()

StringBuffer sb = new StringBuffer("Welcome");
String st = String.valueOf(sb);

Which is best practice to use in performance wise ?

like image 407
Rajavel D Avatar asked Aug 07 '14 05:08

Rajavel D


People also ask

What is the difference between toString () and valueOf () in Java?

valueOf will transform a given object that is null to the String "null" , whereas . toString() will throw a NullPointerException . The compiler will use String.

What is difference between String and StringBuffer?

String consumes more as compared to the stringbuffer. StringBuffer uses less memory as compared to the string. It utilises a string constant pool to store the values. It prefers heap memory to store the objects.

What is the difference between convert toString () and toString () in C#?

Both these methods are used to convert a value to a string. The difference is Convert. ToString() method handles null whereas the ToString() doesn't handle null in C#. In C# if you declare a string variable and if you don't assign any value to that variable, then by default that variable takes a null value.

What is the difference between String valueOf and integer toString?

You will clearly see that String. valueOf(int) is simply calling Integer. toString(int) for you. Therefore, there is absolutely zero difference, in that they both create a char buffer, walk through the digits in the number, then copy that into a new String and return it (therefore each are creating one String object).


1 Answers

This

StringBuffer sb = new StringBuffer("Welcome");
String st = sb + "";

will result more or less in

StringBuffer sb = new StringBuffer("Welcome");
StringBuilder builder = new StringBuilder();
builder.append((sb == null) ? "null" : sb.toString());
builder.append("");
String st = builder.toString();
like image 124
Sotirios Delimanolis Avatar answered Nov 15 '22 17:11

Sotirios Delimanolis