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 ?
valueOf will transform a given object that is null to the String "null" , whereas . toString() will throw a NullPointerException . The compiler will use String.
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.
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.
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).
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With