user image

Shilpa
Published in : 2022-03-02

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 Date : 2022-03-06

Best answers

34

Best answers

34

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

Unable to Connect AWS EC2 Instance with my subdirectory through domain registrar.
Publish date: 2022-02-25 | Comments: 2

Tag: General

Searching for free live chat service
Publish date: 2022-02-11 | Comments: 2

Tag: General

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

Tag: General

Choose default editor from filezilla on Ubuntu
Publish date: 2022-02-28 | Comments: 4

Tag: General

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

Tag: General

How do i r etrieve users?
Publish date: 2022-03-04 | Comments: 0

Tag: General

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

Tag: General