user image

Published in : 2022-03-02

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


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?


Rakshit Date : 2022-03-06

Best answers


Best answers


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.

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

Convert Stored Procedure of Oracle to SQL Server
Publish date: 2022-03-02 | Comments: 1

Tag: General

Connecting jupyter notebook with Android studio
Publish date: 2022-03-05 | Comments: 1

Tag: General

Is there any port I need to allow in google VM instances to allow SMTP?
Publish date: 2022-02-14 | Comments: 1

Tag: General

[solved] Unable to pull updates from git "sudo git pull"
Publish date: 2021-12-20 | Comments: 1

Tag: General

docker elastic builder exited with code 127?
Publish date: 2022-02-27 | Comments: 2

Tag: General