Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String foo = "bar" vs. String foo = new String ("bar") in Android?

Tags:

java

variables

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?

like image 643
wufoo Avatar asked Jul 12 '26 22:07

wufoo


1 Answers

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.

like image 162
amit Avatar answered Jul 15 '26 11:07

amit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!