Difference between this two ?

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

3/19/2020 3:12:09 PM

ketul patel

3 Answers

New Answer


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.


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)


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