Java string literal automatically interpreted as String object, but how?

后端 未结 3 1928
余生分开走
余生分开走 2021-01-12 00:42

What are the mechanics behind Java automatically interpreting string literals as String objects, since there are no overloaded operators and there is no default support for

3条回答
  •  抹茶落季
    2021-01-12 00:52

    Basically the compiler rewrites your code.

    String x = "Some String";
    

    For concatenation, it is just syntactic sugar for StringBuffer append method, ie this:

    z += " with some more in it";
    

    is compiled as:

    z = new StringBuffer(z).append(" with some more in it").toString();
    

    Now for a single concat this is an object created and 2 method calls, so if you are building a very long string inside a loop, it is FAR more efficient to write:

    StringBuilder buf = new StringBuilder(); // Not synchronized so quicker than StringBuffer
    while ( condition is true )
        buf.append(...);
    String z = buf.toString();
    

    rather than:

    String z = "";
    while (condition is true)
       z += "...";
    

    Edit: removed wrong code example...

提交回复
热议问题