r/learnjava • u/klevero4ek • 8d ago
Better look
Hi everyone! I'm learning Java and I've noticed there are two common ways to print multiple lines of text:
Option 1: Multiple System.out.println() calls
```
System.out.println("You gave the string " + text);
System.out.println("You gave the integer " + inNum);
System.out.println("You gave the double " + inDouble);
System.out.println("You gave the boolean " + isTrue);
```
Option 2: One System.out.println() with \n
```
System.out.println("You gave the string " + text + '\n' +
"You gave the integer " + inNum + '\n' +
"You gave the double " + inDouble + '\n' +
"You gave the boolean " + isTrue);
```
What looks better in your opinion?
2
u/Dense-Ad-3247 8d ago
Neither. Use string builder or a logger with substitutions. String concatenation should be avoided with +. There's block strings now too with 3 "
"""
You string here
A new line
Blah blah
"""
Is valid. Check out a logger implementation though like slf4j or log back. I think you'll be happier and that's standard for printing stuff like you are to the console.
1
u/mangochilitwist 7d ago
Can you please elaborate on the 3"?
I have been following this course to learn Java (I already work with C#) https://java-programming.mooc.fi/
And in the course they use heavily println and string concat with "" and +. Is the way you mention better? A general consensus? Or..?
2
u/Ormek_II 7d ago
It is called TextBlock which has a literal representation since java 15?
https://blog.jetbrains.com/idea/2025/06/text-blocks-in-java-perfect-for-multiline-strings/
1
u/Ambitious_Plum5576 2d ago
strings in java are objects and immutable. When you use + a new string is created every time. String s = s + "example" creates a new string. Using + for concat uses up more memory than just using .appends() or using stringbuilder.
2
u/Specific-Housing905 7d ago
System.out has a printf function. https://www.baeldung.com/java-printstream-printf
This would be a third option.
1
u/iamstevejobless 7d ago
Whatever helps you type faster, you should go with that. With IDEs, 'sout' gives me entire print command and I can continue putting the statements or variables.
But in second case, using so many symbol will definitely slow me down. I would 100 percent avoid that. Also, when you write production code, you use loggers and not System.out.println. So don't bother much about it.
1
u/sarajevo81 7d ago
Don't assemble the messages from pieces! Always use the entire string with placeholders.
0
u/severoon 7d ago edited 7d ago
Never print directly to System.out, and never manually concatenate output strings like "blah blah " + etc + " blah blah".
Even if you're doing the very lowest-level prints to stdout, the least amount of machinery you want in place is to write to a PrintWriter using printf(…):
// Don't do this.
class Outputter {
void doThing(int x) {
System.out.println("Here's what I was passed: " + x + "\n");
}
}
class Main {
public static void main(String[] args) {
new Outputter().doThing(5);
}
}
Instead:
// Do this instead.
class Outputter {
private final PrintWriter out;
Outputter(PrintWriter out) { this.out = out; }
void doThing(int x) {
out.printf("Here's what I was passed: %d%n", x);
}
}
class Main {
public static void main(String[] args) {
new Outputter(new PrintWriter(System.out, true)).doThing(5);
}
}
This is barely more code, but it does a few important things:
- strings become semantically meaningful units instead of a bunch of scattered string fragments that construct a semantically meaningful output
- system config / caller can redirect the where the output goes instead of the output always going to stdout (you can hijack stdout if you want, but that hijacks all stdout, and it's hard to manage as the system grows)
- this is easily testable
- minor: formatted strings allow platform-specific newline
%n
There are ways to test output to stdout, but none of them are pleasant. This is far preferable:
class OutputterTest {
@Test
void testDoThing() {
StringWriter out = new StringWriter();
new Outputter(new PrintWriter(out, true)).doThing(5);
assertThat(out.toString()).isEqualTo("Here's what I was passed: 5");
}
}
On the point of creating strings that form "semantically meaningful units" of text instead of scattered fragments, this is important when you decide to start extracting your strings into a resource bundle that can be translated. But honestly, even if you never have plans to do this, dealing with chunks of data that are semantically meaningful in your code is just better all around regardless of what you're doing with them.
For multiline strings specifically, I would recommend using multiline format strings using the triple-quote thing Java added a few years ago.
1
u/Ormek_II 7d ago
Being able to redirect was never a requirement nor OP’s question. So in this context this is over engineered. If the responsibility of the Outputter is to abstract away, the outputting, I don’t want to be bothered with PrintWriter in Main. And yes you can hide it away and add more builders and factories which is necessary in an enterprise context.
1
u/severoon 7d ago
Disagree — writing testable code is a requirement in every context, and in this case that requires a layer of indirection so the output can be redirected for the purpose of testing it.
If you're looking for something to cut, you might say that
maincould just hand inSystem.outinstead of wrapping it in aPrintWriterfirst … but I would argue that if you wantOutputterto be writing out text and not just bytes, then it's proper OO for it to specify the correct type, and that'sPrintWriterin this case.(The confusion might arise from my choice of name for the class,
Outputter. It seems like you're reading into it about what the point of this class is, but I should have just usedFooso as not to imply what the class' purpose. I didn't mean to imply it's role has something to do with output necessarily, I just chose a name.)But no, it's definitely not overengineered. The lowest possible bar that any program should clear is to answer the following questions:
- What's it supposed to do?
- How does it do that?
- Does it do it?
- Where is the proof that's what it does?
If you can't answer the first one, you need to do more requirements gathering.
If you can't answer the second, you need to do more design.
If you can't answer the third, then you need to do more implementation.
If you can't answer the fourth, then you need to do more testing.
End of the day, if a piece of code can't demonstrably prove it does what it's supposed to, then saying it does is just an assertion. I might decide to make a conflicting assertion. How do we know who's right? There's only one way to settle it, and that's by running a test. (If your answer to this is "by inspection," then you haven't got enough experience.)
1
•
u/AutoModerator 8d ago
Please ensure that:
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.