DEV Community

Cover image for Effective Java: Avoid Strings When Other Types Are More Appropriate
Kyle Carter
Kyle Carter

Posted on • Updated on • Originally published at blog.scaledcode.com

Effective Java: Avoid Strings When Other Types Are More Appropriate

Often when receiving data from files, HTTP requests, keyboard input, etc. we receive that data as a String. Often we just keep these variables as a String even if a different variable type is more appropriate. The most appropriate type depends on what we are trying to represent; if we are trying to represent a finite set of items we may use a enum, true/false means boolean, numbers could be an int, long, or even BigInteger. The benefits of using the appropriate type are as follows:

  • Performance improvements with not having to convert back and forth between the String type.
  • The built in functions of the type work correctly for that type such as equals, hashcode, etc.
  • Less error prone.

It can sometimes take a little more effort to save our variables as the correct type, especially if they are provided as a String initially. The payoff is worth it and will keep your code much cleaner.

Top comments (0)