Output & println
println() vs print()
println() vs print()
public class OutputDemo {
public static void main(String[] args) {
System.out.println("Line one");
System.out.println("Line two");
System.out.print("No newline here... ");
System.out.print("...so this continues on the same line");
System.out.println(); // print an empty line to move the cursor down
System.out.println("Now we're on a fresh line");
}
}Line one Line two No newline here... ...so this continues on the same line Now we're on a fresh line
String Concatenation Inside println()
Concatenating values into a single line
String name = "Ava";
int score = 97;
System.out.println("Player " + name + " scored " + score + " points");Player Ava scored 97 points
System.err — a Separate Output Stream
Separating normal output from error output
public class ErrorStreamDemo {
public static void main(String[] args) {
System.out.println("Processing file...");
System.err.println("Warning: file not found, using defaults");
System.out.println("Done.");
}
}Processing file... Warning: file not found, using defaults Done.
Putting It Together
A small worked example mixing all three
public class ReportDemo {
public static void main(String[] args) {
String user = "Marcus";
int attempts = 3;
boolean success = true;
System.out.print("User: ");
System.out.println(user);
System.out.printf("Attempts: %d, Success: %b%n", attempts, success);
if (!success) {
System.err.println("Login failed after " + attempts + " attempts");
}
}
}User: Marcus Attempts: 3, Success: true
Method | Trailing newline? | Typical use |
|---|---|---|
System.out.print() | No | Building up a line piece by piece |
System.out.println() | Yes | Most everyday output — one message per line |
System.out.printf() | Only if %n/\n is included | Formatted, aligned, or precision-controlled output |
System.err.println() | Yes | Error messages and diagnostics, kept separate from normal output |
println() adds a trailing newline; print() does not
The + operator concatenates strings and auto-converts numbers
printf() is the better tool once formatting gets specific — see String Formatting
System.err is a distinct stream, conventionally reserved for errors and diagnostics