hardcode string vs @string in Java code - Android

Gyroscope picture Gyroscope · Nov 24, 2012 · Viewed 11k times · Source

I'm just wondering what the benefits/overheads are for using @string rather than hard coding strings within the actual Java code... For Example:

// To get the string resource:
getActivity.setTitle(getString(R.string.my_string));

Is this the best practice for Things like Actionbar titles, Dynamically created button text, ect... Or should I just do this:

// Hardcoded string
getActivity.setTitle("My String");

I know there will be a bit more overhead doing it the first way.. Just not sure what best practice is.

Answer

KDEx picture KDEx · Nov 24, 2012

Incase you were unaware as to the actual point of having the @string system please read over the localization documentation. It allows you to easily locate text in your app and later have it translated.

Edit Thanks to Hippo for clearing this up.

Using multiple strings of the same value no matter the method (Strings.xml vs programatically) doesn't seem to have any associated overhead. According to Oracle "All literal strings and string-valued constant expressions are interned" which means that the object is reused rather than re-created if you use it again.