-2

I have the following code

public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 4; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

it prints out a star pattern

*
**
***
****

What is the purpose of System.out.println();? Why do we put it at the end of the loop?

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
  • 5
    It's not rocket science, run with and without, you should be able to see the difference. – karakfa Mar 01 '21 at 19:54
  • `println()` performs 2 actions: move to new line and print. When you do nit give it anything to print it just moved to the next line. – PM 77-1 Mar 01 '21 at 19:57

2 Answers2

1

Just to print out a "\n" (move to the next line). Strange question...

Valery
  • 295
  • 2
  • 12
  • 2
    Note that the choice of the line separator depends on the system. `println` is platform independent and will pick `\r\n` on Windows (more specifically, it uses `System.lineSeparator()`) – Zabuzard Mar 01 '21 at 19:59
1

Explanation

print("*") only prints stars in the current line.

But at some point you have to finish the current line and move on to the next line. That is what println() does (ln stands for line).

So without the System.out.println() you will get everything in a single line:

**********

And with it you get multiple lines:

*
**
***
****

println vs print

println behaves more or less identical to print with a newline symbol (\n or \r\n), so:

System.out.println(foo);

// behaves the same as

System.out.print(foo + System.lineSeparator());

You can see the exact details in the source code.

Zabuzard
  • 25,064
  • 8
  • 58
  • 82