+ 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