what is the difference between the following statements | Sololearn: Learn to code for FREE!

+3

what is the difference between the following statements

1.String s1= new String("Hello"); 2.String s2= "Hello";

5/18/2022 9:46:41 AM

Aly Alsayed

7 Answers

New Answer

+3

1st also throws error, missing " for Closing... edit: (error corrected, posted in separate next reply below in detail) briefly: main difference comes from the point that new String()  always creates a new String object in heap memory. Also, when we create a String using literal – it is interned from string pool..

+2

The 2nd throws an error: String s2= ("Hello);

+2

here is clear information: When we create a String object using the 'new' operator, it always creates a new object in heap memory. On the other hand, if we create an object using String literal syntax e.g. “Baeldung”, it may return an existing object from the String pool, if it already exists. Otherwise, it will create a new String object and put in the string pool for future re-use. - main difference comes from the point that new String()  always creates a new String object. Also, when we create a String using literal – it is interned. -- https://www.baeldung.com/java-string-pool

+1

oh sorry i edited the question now , is there any differnce now ?

+1

thanks sir for ur time .. I understand it now Jayakrishna🇮🇳

+1

You're welcome,. Aly Alsayed (For discuss clarity, added in new post, edited first one.)

0

I think what you want to know is this: https://www.geeksforgeeks.org/strings-in-java/ (Which is highly Google-able if you tried)