+ 3

what is the difference between the following statements

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

18th May 2022, 9:46 AM
Aly Alsayed
Aly Alsayed - avatar
7 Answers
+ 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
18th May 2022, 10:34 AM
Jayakrishna 🇮🇳
+ 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.. so it returns the reference may not new always......
18th May 2022, 9:58 AM
Jayakrishna 🇮🇳
+ 2
The 2nd throws an error: String s2= ("Hello);
18th May 2022, 9:47 AM
Lisa
Lisa - avatar
+ 1
oh sorry i edited the question now , is there any differnce now ?
18th May 2022, 10:07 AM
Aly Alsayed
Aly Alsayed - avatar
+ 1
thanks sir for ur time .. I understand it now Jayakrishna🇮🇳
18th May 2022, 10:37 AM
Aly Alsayed
Aly Alsayed - avatar
+ 1
You're welcome,. Aly Alsayed (For discuss clarity, added in new post, edited first one.)
18th May 2022, 10:41 AM
Jayakrishna 🇮🇳
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)
18th May 2022, 10:07 AM
Lisa
Lisa - avatar