0

For a while whenever I need an int to be a string I have been writing this:

int a = 22;
String b = a + "";

I was wondering if there are any differences that I should take into account in reference to

String b = String.valueOf(a) 
//or 
String b = Integer.toString(a) 

Do the above methods have any benefits to being used over "lazy casting" or are all of the above approaches the same under the hood?

shmosel
  • 49,289
  • 6
  • 73
  • 138
pianoisland
  • 163
  • 1
  • 1
  • 10

1 Answers1

2

From the source code in String.java, String#valueOf calls Integer#toString:

/**
 * Returns the string representation of the {@code int} argument.
 * <p>
 * The representation is exactly the one returned by the
 * {@code Integer.toString} method of one argument.
 *
 * @param   i   an {@code int}.
 * @return  a string representation of the {@code int} argument.
 * @see     java.lang.Integer#toString(int, int)
 */
public static String valueOf(int i) {
    return Integer.toString(i);
}

and Integer.toString is

public static String toString(int i) {
    if (i == Integer.MIN_VALUE)
        return "-2147483648";
    int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
    char[] buf = new char[size];
    getChars(i, size, buf);
    return new String(buf, true);
}

For that reason, I'd just stick with Integer#toString.

Regarding String b = a + "":

  • This is an anti-pattern and should be avoided, as it creates an unnecessary amount of String objects.
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
Jacob G.
  • 28,856
  • 5
  • 62
  • 116
  • *This is an anti-pattern and should be avoided, as it creates an unnecessary amount of `String` objects.* Source? – shmosel Oct 11 '17 at 01:25
  • @shmosel OP is half-right on this: there are unnecessary objects created, but `StringBuilder/StringBuffer` instead of `String`. `String a = b + c;` is translated to `String a = new StringBuilder(b).append(c).toString()` by compiler, hence the unnecessary `StringBuilder` created. – Adrian Shum Oct 11 '17 at 02:02
  • @AdrianShum Yes, I'm aware of that. Though I wonder if the compiler can optimize out the empty space append. – shmosel Oct 11 '17 at 02:04
  • @shmosel It may be possible in the future, but I have just tested in Java8, `StringBuilder` is still created when appending with empty string. – Adrian Shum Oct 11 '17 at 02:30