How do I convert from int to String?

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

    The expression

    "" + i
    

    leads to string conversion of i at runtime. The overall type of the expression is String. i is first converted to an Integer object (new Integer(i)), then String.valueOf(Object obj) is called. So it is equivalent to

    "" + String.valueOf(new Integer(i));
    

    Obviously, this is slightly less performant than just calling String.valueOf(new Integer(i)) which will produce the very same result.

    The advantage of ""+i is that typing is easier/faster and some people might think, that it's easier to read. It is not a code smell as it does not indicate any deeper problem.

    (Reference: JLS 15.8.1)

提交回复
热议问题