user

Shilpa

2 Mar 2022

Java: I am wondering about when to use String Literals and String New Objects practically? [No theory]

General

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?

Comments

Rakshit

6 Mar 2022

Best Answer

best answer

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.

 

Key points:

  • If a string is going to remain the same throughout the entire program lifecycles, then use String class object because a String object is immutable.
  • If a string can change (let's say: lots of logic and operations in the construction of the string) then using a StringBuilder is the best option.
  • StringBuffer is synchronized i.e. thread-safe. It means two or more threads can't call the methods of StringBuffer simultaneously. 

Ref: Added my own answer with reference to this thread.

© 2024 Copyrights reserved for web-brackets.com