0
0
JavaHow-ToBeginner · 3 min read

How to Use System.out.println in Java: Simple Guide

Use System.out.println in Java to print text or variables to the console followed by a new line. It is a simple way to display output during program execution by passing the message inside parentheses and ending with a semicolon.
📐

Syntax

The syntax of System.out.println is straightforward:

  • System: The core class that provides access to system resources.
  • out: A static field of System representing the standard output stream (console).
  • println: A method that prints the given argument and moves to the next line.
java
System.out.println("Your message here");
💻

Example

This example shows how to print a simple message and a number to the console using System.out.println.

java
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, world!");
        int number = 42;
        System.out.println("The number is: " + number);
    }
}
Output
Hello, world! The number is: 42
⚠️

Common Pitfalls

Common mistakes when using System.out.println include:

  • Forgetting the semicolon ; at the end of the statement.
  • Using parentheses incorrectly or missing quotes around text.
  • Trying to print without converting non-string types properly (though Java handles this with + operator).
java
public class Main {
    public static void main(String[] args) {
        // Wrong: missing semicolon
        // System.out.println("Hello")

        // Correct:
        System.out.println("Hello");

        // Wrong: missing quotes around text
        // System.out.println(Hello);

        // Correct:
        System.out.println("Hello");
    }
}
Output
Hello
📊

Quick Reference

Tips for using System.out.println effectively:

  • Use it to debug by printing variable values.
  • Combine strings and variables with the + operator.
  • Remember it adds a new line after printing.
  • Use System.out.print if you don't want a new line.

Key Takeaways

Use System.out.println to print messages followed by a new line in Java.
Always end the statement with a semicolon to avoid syntax errors.
Combine text and variables using the + operator inside println.
System.out.println automatically moves to the next line after printing.
Use System.out.print if you want to print without moving to a new line.