How do you display messages in the console?
There are two ways to display messages in the console: System.out.println () and System.out.print (). How do these two methods differ?
The differences between System.out.println () and System.out.print ():
- out.println displays a message on the screen and moves the cursor to a new line
- out.print () displays a message on the screen, but it doesn’t move the cursor to a new line
Let's look at a couple examples to better understand.
Example 1
1 2 3 4 5 6 7 |
class Test { public static void main(String[] args) { System.out.println("I learn"); System.out.println ("Java"); } } |
If run this code on your computer, you will see the following in the console:
I learn
Java
Comments:
We used System.out.println (). That’s why the cursor automatically moved to a new line after the phrase “I learn” was displayed (as if we had pressed enter).
Remember: System.out.println () displays the message at the screen and then moves the cursor to a new line.
Example 2
1 2 3 4 5 6 7 8 |
class Test { public static void main(String[] args) { System.out.println("I learn"); System.out.println ("Java"); System.out.println ("Cool!"); } } |
If you run this code on your computer, you will see the following in the console:
I learn
Java
Cool!
Comments:
1 |
System.out.println("I learn"); |
After displaying “I learn,” the cursor was automatically moved to a new line.
1 |
System.out.println ("Java"); |
After displaying “Java,” the cursor was also moved to a new line.
1 |
System.out.println ("Cool!"); |
After displaying “Cool!”, the cursor was automatically moved to a new line.
Remember: System.out.println () displays the message on the screen and then moves the cursor to a new line.
Example 3
1 2 3 4 5 6 7 |
class Test { public static void main(String[] args) { System.out.print("I learn"); System.out.print("Java"); } } |
If you run this code on your computer, you will see the following in the console:
I learnJava
Comments:
Since we used the following,
1 |
System.out.print("I learn"); |
the cursor wasn’t moved to a new line after displaying “I learn.” That’s why the word “Java” is displayed immediately after “I learn.”
But how do I add a space between “I learn” and “Java?”
That is how:
1 2 3 4 5 6 7 |
class Test { public static void main(String[] args) { System.out.print ("I learn "); System.out.print ("Java"); } } |
Do you notice how it differs from the previous version of the code?
1 |
System.out.print ("I learn"); |
1 |
System.out.print ("I learn "); |
Yes, we added a space. And now, if you run this code on your computer, you will see the following in your console:
I learn Java
LET’S SUMMARIZE:
System.out.println () moves the cursor to a new line.
System.out.print () doesn’t move the cursor to a new line.
P.S. „Println” in System.out.println () stands for „printnewline“.