2 Mar 2022
I am always confused, when it comes about String, String Buffer, String Builder, and new String('ABC') objects.
Practically, when do we need to use String Literals and new Objects? - I read Heap memory, String pool, and boolean things many time, but don't know about the practical scenario.
Can someone explain about the practical scenario?
6 Mar 2022
Here is a live example for your questions,
String: Let's say you are adding a key email or username or password to your constants, that will be never changed throughout the entire application, so in that case Use String. Because it is immutable and helps to manage better performance.
StringBuilder: When you want to run a query and let's you want to build some logic to append more query conditionally to your string, at that time you can use stringbuilder. The scope will be so small - its limited when your query builds and executed through your JDBC connections. At that time stringbuilder is best option.
StringBuffer: By chance, if the Object value can change, and will be modified by multiple threads, use a StringBuffer because StringBuffer is synchronized and so no other thread can make a call to the methods or update object's value.
Ref: Added my own answer with reference to this thread.
© 2023 Copyrights reserved for web-brackets.com