StringBuilder from String in Java - java

Assume that we have a StringBuilder or StringBuffer like below:
StringBuilder s1 = new StringBuilder("xxx");
StringBuffer s2 = new StringBuffer("xxx");
We can get a String from the above variables using the toString() method.
I know that toString is an over-ridden method in both classes.
Assume also that we have a String like below:
String s3 = "xxx";
I can't get a StringBuilder or StringBuffer using toStringBuilder() or toStringBuffer(). Instead, the way we can achieve is like below:
StringBuilder sb = new StringBuilder(s3);
Is there a reason why toStringBuilder()/toStringBuffer() is not defined and is there any other effective way to get a StringBuilder/StringBuffer from String.

String itself is immutable. That has many advantages, especially with concurrent usage, sharing substrings and such.
Also back and forth coupling between classes is bad design.

toString is a method that is part of the Object class and thus all classes of java will have such method. A String is immutable and as such both toStringBuilder and toStringBuffer will create new objects. I think that if there were such methods many users would be mislead that using these methods they can modify the string in-place. Also because of the same reasons there can not possible be any more efficient way to create a StringBuilder/StringBuffer.

You might ask for a considerable number of String.toFoo() methods, and where to draw the line? You can construct StringBuilder and StringBuffer using the constructor. That's enough - why add another method?

Related

What's the difference between StringBuilder and ArrayList<String>?

In an interview, I want to build up a new String with some substrings. I argued that ArrayList<String> is almost the same as StringBuilder, but the interviewer said I should always use StringBuilder if I need to deal with String. I think the time complexity of adding/removing functions between them are the same.
They aren't the same thing at all. StringBuilder builds a single string, while ArrayList<String> is just that--an array of separate strings. Of course, you can concatenate all of the array's strings with String.join("", list), where the first argument is the separator that you want to use, but why would you go that route instead of just using the class that was designed to do exactly what you're trying to do in the first place?
It all comes down to memory consumption. String is an object, while ArrayList<String> holds separate objects, StringBuilder holds only one.
StringBuilder has a member function to return the whole built string, whereas in ArrayList, you have to concatenate the strings yourself.
Unless you continue to need the separate elements you are adding to the list, you should use a StringBuilder.
After all, you can't directly get a concatenated string from the contents of the list: you have to put it in, say, a StringBuilder.
But in the specific case of building up a string of substrings, StringBuilder provides methods to allow you to append portions of Strings without using substring: the append(CharSequence, int, int) method is an optimization to avoid creating that extra string.
It should be mentioned that, at least when I have written python, it has been considered better to build up a list, and then use ''.join(theList) at the end, which is basically the analog of ArrayList<String>.
I don't know enough about python to know why this is considered particularly better.
You can "build" strings using both. However StringBuilder is a class specializing in building strings with its append insert delete charAt etc... methods. An ArrayList is a general purpose collection which lacks most of this functionality. Consider implementing the following (contrived example) with an ArrayList:
StringBuilder sb = new StringBuilder().append("time: ")
.append(System.currentTimeMillis())
.deleteCharAt(4)
.reverse();
System.err.println(sb); // 3153067310451 emit
Ergonomics and readability aside, there are performance considerations but those are largely irrelevant on trivially sized examples.
If you need a single String at the end, performance and memory consumption are some differences for sure. Whenever you build a String from parts, in the good case you end up using StringBuilder, or in a slightly worse case StringBuffer, and in the worst case you end up concatenating two strings, then throw them away, and repeat - lots of allocations and garbage collection in this case.
JLS12 still mentions StringBuffer by name for optimization (but hopefully StringBuilder is used internally, as similar technique):
An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.
In the particular case of having a List<String> and later using String.join() on it, StringJoiner contains the particular StringBuilder object which is going to be used.
So there will be a builder anyway, and then it may be more efficient to use it from the beginning.

what should i use-String or StringBuilder for storing SQL queries in a code which uses many different SQL queries

I have a code which uses multiple SQL queries.
Should i use String to store these different SQL queries or should i use a StringBuilder.
If using StringBuilder should i have each query in a new StringBuilder object or use a single StringBuilder object.
String is Immutable and StringBuilder is Mutable i.e. no new object is created when you edit StringBuilder unlike String.
If your application is used in large scale then its advisable to use StringBuilder instead of String
NOTE:- String is Thread Safe while StringBuilder is not
Well, if you are willing concatenate theses queries into one query part by part, then use unique StringBuilder object instead of concatenating String objects to each other. That's the best practise in terms of performance.
Avoid using unique StringBuilder for all (different) concatenation sets in your class, that thing must be dangerous if you're using threads. You have to define new StringBuilder object for each set of concatenated strings.

Why do I need to redefine a String if I use the method replace?

Why do I need to redefine the variable theString if I use the method replace in this code :
String theString = "I w#nt to h#ve the regul#r \"A\"!";
theString = theString.replace("#", "a");
System.out.println(theString);
Why can't I do :
theString.replace("#", "a");
and that's it?
Strings are immutable -- you cannot change them once they have been created. There are exceptions of course, if you use reflective magic, but for the most part, they should be treated as invariants. So therefore the method replace(...) does not change the String, it can't, but rather it creates and returns a new String. So to be able to use that new String, you have to get access to its reference, and that can be done by assigning it to a String variable or even to the original String variable. This discussion gets to the heart of what is the difference between an object and a reference variable.
Because String objects are, by design, immutable, so you need to create a new String to contain your changes
The posted answers mention the technical reason (strings are immutable) but neglect to mention why it is that way. See this: Why are strings immutable in many programming languages?
Taken from this link
In Java, String is not implemented as character arrays as in other programming languages. Instead string is implemented as instance of String class.
Strings are constants/ immutable and their values cannot be changed after they are created. If any operations that results in the string being altered are performed a new instance of String object is created and returned. This approach is done for implementation efficiency by Java.
It is recommended to use StringBuffer or StringBuilder when many changes need to be performed on the String. StringBuffer is like a String but can be modified. StringBuffer is thread safe and all the methods are synchronized. StringBuilder is equivalent to StringBuffer and is for use by single thread. Since the methods are not synchronized it is faster.

StringBuilder Vs StringBuffer OR vector Vs ArrayList

My requirement is to store the large chunk of data (String value) but i am confused which one is better to use. I only want to append the incoming data.
e.g. String str1 = "abc"
String str2 = "123";
String Str3 = "xyz";
suppose i am appending/ adding to (Sbuilder/SBuffer/ vector/ ArrayList)
one after another,
e.g. str1, str2 str3 then output must be "abc123xyz"
str2, str1,str3 output must be "123abcxyz"
Use StringBuilder and ArrayList
StringBuffer and Vector have thread synchronization that adds overhead (unless you need it, but even then there's ways to add that to the newer classes)
From the javadoc for StringBuffer:
The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.
Also, I think the Vector is backed internally by an Array as well, and is pretty much deprecated. If you want fast appends then you might want to take a look at LinkedList (it is slightly faster than ArrayList for pure appends because you don't have to grow the backing Array periodically).
However, if this is just for sequences of characters then the StringBuilder is optimized for exactly this case, and you shouldn't muck around with Collections with all of their overhead.
If you don't need to synchronize you can avoid StringBuffer and Vector and prefer StringBuilder and ArrayList instead.
Whether to use StringBuilder or ArrayList depends on your requirements. If you just want to concatenate the strings SB is enough.
If data size is variable in that case we used StringBuffer because the StringBuffer class is designed to create and manipulate dynamic string information. The memory allocated to the object is automatically.
If you are doing this inside a single thread you will want to use a StringBuilder over anything when all you want to achieve is string concatenation; for multiple types use an ArrayList.

No reverse method in String class in Java?

Why there is no reverse method in String class in Java? Instead, the reverse() method is provided in StringBuilder? Is there a reason for this? But String has split(), regionMatches(), etc., which are more complex than the reverse() method.
When they added these methods, why not add reverse()?
Since you have it in StringBuilder, there's no need for it in String, right? :-)
Seriously, when designing an API there's lots of things you could include. The interfaces are however intentionally kept small for simplicity and clarity. Google on "API design" and you'll find tons of pages agreeing on this.
Here's how you do it if you actually need it:
str = new StringBuilder(str).reverse().toString();
Theoretically, String could offer it and just return the correct result as a new String. It's just a design choice, when you get down to it, on the part of the Java base libraries.
If you want an historical reason, String are immutable in Java, that is you cannot change a given String if not creating another String.
While this is not bad "per se", initial versions of Java missed classes like StringBuilder. Instead, String itself contained (and still contains) a lot of methods to "alter" the String but since String is immutable, each of these methods actually creates and return a NEW String object.
This caused simple expressions like :
String s = "a" + anotherString.substr(10,5).trim().toLowerCase();
To actually create in ram something like 5 strings, 4 of which are absolutely useless, with obvious performance problems (despite after there has been some optimizations regarding underlying char[] arrays).
To solve this, Sun introduced StringBuilder and other classes that ARE NOT immutable. These classes freely modify a single char[] array, so that calling methods does not need to produce many intermediate String instances.
They added "reverse" quite lately, so they added it to StringBuilder instead of String, cause that's now the preferred way to manipulate strings.
As a side-note, in Scala you use the same java.lang.String class and you do get a reverse method (along with all kinds of other handy stuff). The way it does it is with implicit conversions, so that your String gets automatically converted into a class that does have a reverse method. It's really quite clever, and removes the need to bloat the base class with hundred of methods.
String is immutable, meaning it can't be changed.
When you reverse a String, what's happening is that each letter is switched on it's own, means it will always create the new object each times.
Let us see with example:
This means that for instance Hello becomes as below
elloH lloeH loleH olleH
and you end up with 4 new String objects on the heap.
So think if you have thousands latter of string or more then how much object will be created.... it will be really a very expensive. So too much memory will be occupied.
So because of this String class not having reverse() method.
Well I think it could be because it is an immutable class so if we had a reverse method it would actually create a new object.
reverse() acts on this, modifying the current object, and String objects are immutable - they can't be modified.
It's peculiarly efficient to do reverse() in situ - the size is known to be the same, so no allocation is necessary, there are half as many loop iterations as there would be in a copy, and, for large strings, memory locality is optimal. From looking at the code, one can see that a lot of care was taken to make it fast. I suspect the author(s) had a particular use case in mind that demanded high performance.

Categories