About us

Join us FREE!

hardcode string vs @string in Java code - Android

Tutorial by Er Satya connectclue-author-image

All > Tech Blogger | Java | Spring Boot | HTML | CSS | MySQL > Java | Spring Boot

1 like

Please login to like this article.

connectclue-linkedin-share

hardcode string vs @string in Java code - Android

Using multiple strings of the same value no matter the method (Strings.xml vs programmatically) 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.

That way you have a fixed place to alter all your strings within the project. Let us say you used the same string in 10 different locations in the code. What if you decide to alter it? Instead of searching for where all it has been used in the project you just change it once and changes are reflected everywhere in the project.

Well, strings.xml would have to be parsed, wouldn't it? Then I suppose hardcoded would be best for performance, though probably unnoticeable at runtime. People do choose to use it though in order to have all the strings in one spot in case there are plans to translate the app.

There are many benefits to setting the strings in a strings.xml file; in a nutshell, it allows you to use the same string in multiple locations, which is good if you somehow need to modify the string later. It also allows you to display the same text in different languages; hardcoding the string doesn't give you all those options.
BTW, you don't need to put every text in the strings.XML file; only the ones that might be used in multiple places in the application.
The general rule for placing strings in the strings.xml file are these:
  • Will it be used in multiple locations 
  • Will it be used in multiple languages 
  • Will it be dynamic or static 


connectclue-linkedin-share

More articles:


Recent lost & found:


Login for enhanced experience

connectclue-tick Create and manage your profile

connectclue-tick Refer an author and get bonus Learn more

connectclue-tick Publish any lost and found belongings

connectclue-tick Connect with the authors & add your review comments

connectclue-tick Join us for Free to advertise for your business or Contact-us for more details

connectclue-tick Join us for Free to publish your own blogs, articles or tutorials and get your Benefits

connectclue-login

Back to top