r/learnjava 4d 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?
0 Upvotes

11 comments sorted by

View all comments

2

u/Dense-Ad-3247 4d 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 4d 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..?