Home » Android » android – XML string resources vs Java Constant Strings?

android – XML string resources vs Java Constant Strings?

Posted by: admin June 15, 2020 Leave a comment


I have a String is like String data="apps";

i know loading String in Android in two ways..

First one is

so it is a constant i defined it as

public static final String data="apps";

And another type is defing it in res/vslues/strings.xml file like..

<string name="data">apps</string>
<string name="hello_world">Hello world!</string>

if i want to use it..

for the first way ClassName.data

for second way context.getResources().getString(resourceid)


so now my question is I want to use same String in 30 times in different classes.And I have more number of variables.so which will load faster and take lesser memory in the above methods..

How to&Answers:

However, speed shouldn’t really be an issue in either case. I would recommend organizing based on what makes sense.

Constants class

Put strings constants that will be used internally, like database column names or other keys.


Put strings that are displayed for the user. This way you can take advantage of localization, etc.

As per requirement you should be prefer second approach means XML


The XML string values are meant to be display strings that can be overridden based on locale. This way you can refer to a translatable display value by a constant key.


You should consider using XML strings as a way to display something to the user and change it depending on locale.

Never the less, public static final String data="apps"; should be used in order to hide some not-for-user data like db connections, log messages etc.


I think the speed and memory usage would be the same. The constant in a class is just like a constant in the string.xml which is stored once and referenced whenever you need it elsewhere.
However, the advantage of storing in string.xml over the other would be the extra import lines of code which would be avoided. Meanwhile, you have to remember that with string.xml storage you can only use it where the context of an activity is accessible.


I’d suggest that you leverage the Android resource system.

To quote the book Android In Practice:

Resources in Android are efficient and fast. XML resources are compiled into a binary format. This makes them friendly at development time, without being slow at Runtime.