HOW TO CONVERT FROM INT TO STRING IN JAVA?

naomi burke

Total Post:28

Points:196
Posted by  naomi burke
Java  String 
 777  View(s)
Ratings:
Rate this:
I'm working on a project where all conversions from int to String are done like this:
int i = 5;
String strI = "" + i;
I'm not familiar with Java. Is this usual practice or is something wrong, as I suppose?
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: How to convert from int to String in java?

    1. Integer.toString(i)
    2.  String.valueOf(i)
    The concatenation will work, but is unconventional and could be a bad smell as it suggests the author doesn't know about the two methods above (what else might they not know?).

    Java has special support for the + operator when used with strings (see docs) which translates the code you posted into:
    StringBuilder sb = new StringBuilder();
    sb.append("");
    sb.append(i);
    String strI = sb.toString();

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!