How do I convert from int to String?

后端 未结 20 3266
不思量自难忘°
不思量自难忘° 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

    It's not only the optimization1. I don't like

    "" + i
    

    because it does not express what I really want to do 2.

    I don't want to append an integer to an (empty) string. I want to convert an integer to string:

    Integer.toString(i)
    

    Or, not my prefered, but still better than concatenation, get a string representation of an object (integer):

    String.valueOf(i)
    

    1. For code that is called very often, like in loops, optimization sure is also a point for not using concatenation.

    2. this is not valid for use of real concatenation like in System.out.println("Index: " + i); or String id = "ID" + i;

提交回复
热议问题