Reputation: 3788
Imagine that you want to display a welcome message to a game but are required to keep the lines in the source code at a maximum length of 80 characters width. In the game the length of the lines are of no importance. An example of the welcome message would be:
private void welcomeMessage() {
System.out.println("Welcome to the game. This message should learn me how to create a long messages like this in a read-able fashion. Imagine there is a limit of 80 characters per line for a programmer to see. How to fix this efficiently? This is one large line in my IDEA. ");
}
This line is way too long for it to be 80 characters per line of code, as you can see by the scroll bar. I previously learned to simply do something like this:
private void welcomeMessage() {
System.out.println("Welcome to the game. This message should learn me" +
" how to create a long messages like this in a read-able " +
"fashion. Imagine there is a limit of 80 characters per line for" +
" a programmer to see. How to fix this efficiently? This is one " +
"large line in my IDEA. ");
}
However I find this solution ugly, this creates a dependency which is so annoying. If I add to "Welcome to the game. This message should learn me"
just one word I have to change all the other lines, so all lines after a line depends on it.
I can also imagine there are penalties just for making it readable in this way. It makes me wonder:
Imagine this was a real game, would you then just make a txt text file and import it with a StringBuffer etc. to display it on the screen? Or how else would you display longer text messages?
Upvotes: 1
Views: 1992
Reputation: 421090
Does the compiler append all lines directly since they themselves do not depend on other variables or does it happen at runtime? (I am afraid that it would call the concatenation operator function ('+') 4 times)
The compiler will concatenate the strings. No runtime overhead.
Would a StringBuffer with .append() be more efficient in this example because it does not create 5 strings but instead appends it to the StringBuilder object?
No.
Demo:
class Test {
public static String test = "a" + "b" + "c";
}
The command
javac Test.java && javap -c -v Test
yields the following output
[...]
Constant pool:
#1 = Methodref #5.#15 // java/lang/Object."<init>":()V
#2 = String #16 // abc
#3 = Fieldref #4.#17 // Test.test:Ljava/lang/String;
[...]
Code:
stack=1, locals=0, args_size=0
0: ldc #2 // String abc
2: putstatic #3 // Field test:Ljava/lang/String;
5: return
[...]
Upvotes: 2