In Java, providing output to the console is one of the most basic yet essential tasks. Whether you are debugging code or interacting with a user, understanding how to format and display text is crucial.
System.out.println() method is actually a chain of three things: System (Class), out (Static Object of PrintStream), and println (Method).
Java provides two primary methods to output text. The choice depends on whether you want the cursor to stay on the same line or move to a new one.
println() MethodThe "ln" stands for "line". This method prints the text and then **moves the cursor to the next line** automatically.
print() MethodThis method prints the text but **keeps the cursor on the same line**. Any subsequent output will appear right next to it.
You can use the println() method to perform mathematical calculations directly inside the parentheses. Unlike text, numbers do not require double quotes.
Note: If you put numbers inside quotes (e.g., "10 + 20"), Java treats them as a String and will print them as-is without calculating.
Sometimes you need to print special characters like tabs, new lines, or double quotes inside a string. Java uses a backslash \ followed by a specific character to handle this.
| Escape Character | Description | Example Result |
|---|---|---|
\n |
New Line (moves to next line) | Hello World |
\t |
Horizontal Tab (adds space) | Hello World |
\\ |
Prints a single backslash | C:\Users |
\" |
Prints a double quote | "Hello" |
Concatenation means joining two or more items together. In Java, we use the + operator to join strings with other variables or text.
For more control over how data looks (like limiting decimal places), Java provides the printf() method, which stands for "Print Formatted".
%d - Integer%s - String%f - Floating-point (decimal)In professional Java development, there is another way to output data specifically for errors: System.err.println(). Most IDEs will highlight this output in **Red** to alert the developer.
System.err.println("Critical Error: Database connection failed!");
You have mastered the art of displaying data! You now know the difference between print and println, how to use escape characters, and how to format complex numbers. In the next chapter, we'll dive into Comments to make your code more understandable.