In the previous lesson, we went over a program that counted to the number 10 using a for loop. Using the
System.out.println() method, every loop printed the number on a new line.
However, what if we wanted to print our numbers out on one line? So far, we have only used the print method
System.out.println() . Today, I’m going to introduce a new printing method that does not start a new line every time it prints something new. This new print method is
When using this new
System.out.print() method, is important to know that it leaves no spaces. Let’s take the code from the previous lesson and replace the
As you can probably guess, the output from the program above is not a pretty sight to behold:
All the numbers have been mashed together. This is because the
print() method is doing its job. Remember, the job of the
print() method is only to print, and not to create a new line.
In order to make it more readable for people, we can adjust the grammar inside of the print method and add an if else statement for commas to be added between numbers until it reaches the number 10.
Be sure to notice that we used a
println() method first, and then used a
print() method for the loop. The code above gives us the following output:
If nothing else, just remember that
println() prints whatever is in its parentheses and then moves to a new line, whereas
print() does not create a new line or space after it prints.
Great job and see you next lesson!
Leave a Reply