print vs println
Control lines like a pro, and join text with +.
print vs println 🖨️
Java has two ways to say things:
System.out.println(...)says it, then moves to a new line (like pressing Enter).System.out.print(...)says it and stays on the same line.
public class Main {
public static void main(String[] args) {
System.out.print("Zoom");
System.out.print("Zoom");
System.out.println("!");
System.out.println("Done");
}
}That prints:
ZoomZoom! Done
Notice there's no space between Zoom and Zoom. Java prints exactly what you give it, nothing more.
Joining text with +
The + sign glues text together:
public class Main {
public static void main(String[] args) {
System.out.println("Mars" + "Rover");
System.out.println("Mars " + "Rover");
}
}The first line prints MarsRover, the second prints Mars Rover, because the second one has a space inside the quotes.
Text + numbers
You can glue numbers onto text too:
public class Main {
public static void main(String[] args) {
System.out.println("Moons of Mars: " + 2);
}
}🌍 Fun fact
The Curiosity rover has been exploring Mars since 2012. Every command it gets is checked very carefully, because one missing space or semicolon could mean a very expensive mistake!
Want to run it yourself?
Predict what the code prints first, then check! Copy an example above, paste it into the free online Java editor, and press Run. Keep the first line as public class Main.
Opens Programiz, a free site that isn't run by First Coding Path and may show ads. Grown-ups, you might like to take a look first.