How do I convert from int to String?

后端 未结 20 2745
不思量自难忘°
不思量自难忘° 2020-11-21 23:40

I\'m working on a project where all conversions from int to String are done like this:

int i = 5;
String strI = \"\" + i;


        
相关标签:
20条回答
  • 2020-11-22 00:09

    Using "" + i is the shortest and simplest way to convert a number to a string. It is not the most efficient, but it is the clearest IMHO and that is usually more important. The simpler the code, the less likely you are to make a mistake.

    0 讨论(0)
  • 2020-11-22 00:13

    There are many way to convert an integer to a string:

    1)

    Integer.toString(10);
    

    2)

     String hundred = String.valueOf(100); // You can pass an int constant
     int ten = 10;
     String ten = String.valueOf(ten)
    

    3)

    String thousand = "" + 1000; // String concatenation
    

    4)

    String million = String.format("%d", 1000000)
    
    0 讨论(0)
  • 2020-11-22 00:15

    A lot of introductory University courses seem to teach this style, for two reasons (in my experience):

    • It doesn’t require understanding of classes or methods. Usually, this is taught way before the word “class” is ever mentioned – nor even method calls. So using something like String.valueOf(…) would confuse students.

    • It is an illustration of “operator overloading” – in fact, this was sold to us as the idiomatic overloaded operator (small wonder here, since Java doesn’t allow custom operator overloading).

    So it may either be born out of didactic necessity (although I’d argue that this is just bad teaching) or be used to illustrate a principle that’s otherwise quite hard to demonstrate in Java.

    0 讨论(0)
  • 2020-11-22 00:15
    String strI = String.valueOf(i);
    
    String string = Integer.toString(i);
    

    Both of the ways are correct.

    0 讨论(0)
  • 2020-11-22 00:15

    use Integer.toString(tmpInt).trim();

    0 讨论(0)
  • 2020-11-22 00:17

    Personally, I don't see anything bad in this code.

    It's pretty useful when you want to log an int value, and the logger just accepts a string. I would say such a conversion is convenient when you need to call a method accepting a String, but you have an int value.

    As for the choice between Integer.toString or String.valueOf, it's all a matter of taste.
    ...And internally, the String.valueOf calls the Integer.toString method by the way. :)

    0 讨论(0)
提交回复
热议问题