Difference between this two ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Difference between this two ?

String s = "Hello!"; String s = new String("Hello!");

19th Mar 2020, 3:12 PM
Ketul Patel
Ketul Patel - avatar
3 Answers
+ 2
Difference between this two ? String s = "Hello!"; It's String Literal which store in SCP. E.g String s1 = "Hello!"; String s2 = "Hello!"; Here, s1 & s2 are equal but in case of objects they are different. String s = new String("Hello!"); It's String Object Store in Heap Memory. https://1.bp.blogspot.com/-s7Y6Qf5JyrI/U-DVyWt0ABI/AAAAAAAABvE/Sw-Myrm_j_o/s1600/String+literal+vs+String+Object+in+Java.png
21st Mar 2020, 8:39 AM
Learner
+ 4
Both are String objects. The former one will be stored in String Constant Pool (SCP) which is a small part on the heap and it cannot have duplicates and the later one will have memory allocated to it on the heap. When you say- String s = new String("Hello"); Two copies of the object are created, one in SCP and other on heap. But if "Hello" is already present in the SCP, one copy will be discarded and only the one in the heap remains.
19th Mar 2020, 4:00 PM
Avinesh
Avinesh - avatar
+ 2
The point is, there is no effective difference. In both cases you declare and initialize a new String object. The first variant is a convenient shorthand (also called syntactic sugar, because sweet favor to make developers life easier)
19th Mar 2020, 4:08 PM
Tibor Santa
Tibor Santa - avatar