Chapter 1 · Lesson 2 of 5
02. print, println and new lines
println ends the line and print doesn't. Use \n for a new line and \t for a tab inside the words.
System.out.println ends the line after it prints. System.out.print doesn't: the next thing printed carries on the same line. Use + to join pieces of text into one.
public class Main { public static void main(String[] args) { System.out.print("Ready, "); System.out.print("steady, "); System.out.println("go!"); System.out.println("Java " + "is " + "fun"); System.out.println("Two\nlines"); }}It shows
Ready, steady, go! Java is fun Two lines
Inside the quotes, \n starts a new line and \t is a tab, a jump to the next column, handy for lining up a table.
public class Main { public static void main(String[] args) { System.out.println("Item\tPrice"); System.out.println("Samosa\t15"); System.out.println("Chai\t10"); }}It shows
Item Price Samosa 15 Chai 10
Your turn
1Steps
- 1Print this little bus timetable, with
\tbetween the stop and the time, each on its own line: - 2
Markettab8:00, thenSchooltab8:15, thenStationtab8:40.
Write it in Main.java, in public class Main. If it reads input, put the answers in Program input, under the terminal.
Use: System.out.println
Starting code
The editor starts empty. Copy this into it to begin, or write your own from scratch.
public class Main { public static void main(String[] args) { System.out.print("Market 8:00 School 8:15 Station 8:40"); }}2Expected output
It should show
Market 8:00 School 8:15 Station 8:40
3Hints
Stuck? Open one hint at a time: each gives a bit more help.
Hint 1
Each stop needs its own line, so use println (or \n) for each.
Hint 2
Between the stop and its time, use \t instead of a space.
Hint 3
The first line is System.out.println("Market\t8:00"); and the other two are made the same way.