简体   繁体   中英

what is the style recommendation for the Java string concatenation operator “+”?

What is the style recommendation for the Java string concatenation operator "+"?

Edit: Specifically, should it be used or not?

Thinking in Java (Eckel) says that the overloaded + operator is implemented using StringBuilder (although not all compilers may be supporting this as per alphazero's answer) and thus multiple String objects and the associated memory use and garbage collection are avoided. Given this, I would answer my own question by saying that the + operator is probably fine, style-wise. The only caveat is that the + is the only instance of overloading in the language and that exceptionalism might count as a minor reason not to use it. In retrospect, the advantage of terseness is pretty significant in some situations and that has got to count for a lot of style.

As long as your team members are comfortable with it.

Because there is no "correct" coding style. But I agree that you should always use white-spaces between strings and operator for better readability.

Following Java's coding conventions Strings should be concatenated like:

String str = "Long text line " 
             + "more long text.";

Make sure the '+' operator always begins the next line. https://www.oracle.com/technetwork/java/javase/documentation/codeconventions-136091.html#248

It is perfectly fine to use the '+' operator for String concatenation, there are different libraries that provide other structure for it, but for me it is the most simple way.

Hope this helps!

Happy coding,

Brady

Is this what you meant?

"string1" + "string"

or, if you have long lines

"a really long string....." +
"another really long string......" +
"ditto once again" +
"the last one, I promise"

If you have the time to format this right, then:

"a really long string....."        +
"another really long string......" +
"ditto once again"                 +
"the last one, I promise"

Basically, every time you use the + operator, you should use it with at least one whitespace before and after. If you're using it when concatenating long strings, put it at the end of the line.

The overall recommendation is not to use this form (at all) if performance is of concern, and to instead use StringBuilder or StringBuffer (per your threading model). The reason is simply this: Strings in java are immutable and the '+' operator will create many intermediary String objects when processing expressions of form S1 + S2 +... + Sn .

[Edit: Optimization of String Concatenation ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM