I did search on this but the keywords must be too generic to narrow down the relevant bits. Why are both ways of declaring a string valid in android and is there any difference?
Using the new keyword you create a new string object, where using foo = "bar" will be optimized, to point to the same string object which is used in a different place in your app.
For instacne:
String foo = "bar";
String foo2 = "bar";
the compiler will optimize the above code to be the same exact object [foo == foo2, in conradiction to foo.equals(foo2)].
EDIT: after some search, @Sulthan was right. It is not compiler depended issue, it is in the specs:
A string literal always refers to the same instance (§4.3.1) of class String.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With