+ 1

What is the difference between these expressions

String a="hi"; String a = new String("hi"); What is the difference between these two ways of declaring 'a'

23rd May 2019, 8:52 AM
Ayush Pandey
Ayush Pandey - avatar
9 Answers
+ 5
String a = hi; ⬆️ this is stored in string pool String a = new String(hi); ⬆️ this is stored on heap it's not in string pool so when you compare both of these strings if the variables were diffrent using ==, the result returned would be false
23rd May 2019, 9:51 AM
D_Stark
D_Stark - avatar
+ 5
@D_Stark So if you know that you will use a certain string very often you should initiate it as literal and if not you would initate it as object on the heap?
23rd May 2019, 10:08 AM
Thoq!
Thoq! - avatar
+ 4
Ayush Pandey the equals() function compares the strings and not the refreneces so it would return true as both strings are the same.
23rd May 2019, 11:15 AM
D_Stark
D_Stark - avatar
+ 1
Bro Airree i am not so begineer that i dont understand that much concepts.
23rd May 2019, 8:59 AM
Ayush Pandey
Ayush Pandey - avatar
+ 1
I wanna know what makes it different if we compare it.
23rd May 2019, 8:59 AM
Ayush Pandey
Ayush Pandey - avatar
+ 1
D_Stark what if we compare usinh equals to function will it output true
23rd May 2019, 10:28 AM
Ayush Pandey
Ayush Pandey - avatar
0
The first one declares a String, while the second one declares an object
23rd May 2019, 8:57 AM
Airree
Airree - avatar
0
It will be false, because there is an object, and objects are only equal if you assign it to be
23rd May 2019, 9:05 AM
Airree
Airree - avatar