Home Java multiline string formation
Reply: 4

Java multiline string formation

Luke
1#
Luke Published in 2012-04-13 16:11:27Z

I'm by no means a java programmer, so this may seem pretty basic.

Which of these are 'better' when you want to keep your code lines short.

String str = "First part of a string.";
str += " Second part of string.";

or

String str = "First part of string." +
" Second part of string."

I guess my question is do both the += and + make a new String object? If they do then neither really are better, it would just be a matter of preference. The example I gave would be a good example of real world use. I don't want a comparison of doing a concatenation 3 times to 1000 times with either method.

Thanks

Tony Ennis
2#
Tony Ennis Reply to 2012-04-13 16:16:33Z

I prefer the 2nd method. The reason is that the compiler will likely combine the result of the concatenation into a single string at compile time while the 1st method may be done at run-time (depending on the actual implemention.) It's a small thing unless you're doing something millions of times, however.

Roger Lindsjö
3#
Roger Lindsjö Reply to 2018-02-14 18:33:55Z

The Java compiler is actually required to concatenate the second example at compile time. See 15.28. Constant Expressions and 3.10.5. String Literals.

josh.trow
4#
josh.trow Reply to 2012-04-13 16:18:19Z

Here's what I get when I compile then decompile this:

public static void main(String[] args) {
    String str = "First";
    str += " Second";
    System.out.println(str);

    String str2 = "First" + " Second";
    System.out.println(str2);
}

Becomes:

public static void main(String args[]) {
    String s = "First";
    s = (new StringBuilder()).append(s).append(" Second").toString();
    System.out.println(s);
    String s1 = "First Second";
    System.out.println(s1);
}

So the second method is better.

ChadNC
5#
ChadNC Reply to 2012-04-13 16:27:43Z
StringBuilder sb = new StringBuilder();
sb.append("First part");
sb.append("Second part");
System.out.print(sb.toString());
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.376565 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO