Careeroza
Printing Output
println vs print
System.out.println() prints the text and then moves to a new line. System.out.print() prints without a new line.
Example
public class Main {
public static void main(String[] args) {
System.out.println("Line one");
System.out.println("Line two");
System.out.print("Same ");
System.out.print("line");
System.out.println(); // just a new line
System.out.println("Done");
}
}Output
Line one Line two Same line Done
Printing Numbers and Expressions
Example
Numbers are written without quotes. Java calculates the expression first, then prints the result.
public class Main {
public static void main(String[] args) {
System.out.println(42);
System.out.println(3 + 4);
System.out.println(10 * 2.5);
System.out.println("3 + 4"); // text, not math
System.out.println("Sum: " + 3 + 4); // joins left to right
System.out.println("Sum: " + (3 + 4));
}
}Output
42 7 25.0 3 + 4 Sum: 34 Sum: 7
Note: "Sum: " + 3 + 4 prints Sum: 34 because the String is joined with 3 first, then with 4. Use brackets to do the math first.
Practice
Exercise: Print the following using exactly two statements: print for "Java " and println for "is fun".
Show answer
System.out.print("Java ");
System.out.println("is fun");