Skip to main content
Documents
Share
LinkedIn
Facebook
Twitter
Copy
Java keywordsIntroduction To JavaJava File HandlingJava Language BasicsJava ArraysJava Object-Oriented Programming

Java Output

The System.out.println method in Java is a widely used tool for producing output to the console. It belongs to the PrintStream class and is part of the java.lang package. This method prints the given content and then terminates the line, moving the cursor to the next line.

Usage

System.out.println is used to display messages, variable values, or results of expressions during program execution. It is an essential tool for debugging and logging information in console-based applications.

Syntax

System.out.println(expression);
  • expression: The content to be printed. It can be a string, a variable, or a combination of literals and variables.

Examples

Example 1: Printing a String

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

In this example, the System.out.println method is used to print the string "Hello, World!" to the console.

Example 2: Printing Variables

public class VariableOutput {
    public static void main(String[] args) {
        int number = 10;
        System.out.println("The number is: " + number);
    }
}

Here, a variable number is declared and initialized with the value 10. The System.out.println method prints the message concatenated with the variable's value.

Example 3: Printing Expressions

public class ExpressionOutput {
    public static void main(String[] args) {
        int a = 5;
        int b = 3;
        System.out.println("Sum: " + (a + b));
    }
}

This example demonstrates printing the result of an arithmetic expression. The sum of a and b is calculated within the System.out.println statement and printed to the console.

Tips and Best Practices

  • String Concatenation: Use the + operator to concatenate strings and variables within System.out.println. Ensure correct use of parentheses to avoid precedence issues in expressions.
System.out.println("Result: " + (a + b)); // Correct
  • Debugging: Utilize System.out.println for debugging by printing variable values at different points in your code to track changes and identify issues.
  • Performance: Be cautious about excessive use of System.out.println in performance-critical applications, as it can slow down execution due to I/O operations.
  • Use printf for Formatting: For formatted output, consider using System.out.printf, which allows for more control over the output format.
System.out.printf("Formatted number: %.2f%n", 123.456);
  • Newline Consideration: Remember that System.out.println automatically appends a newline character. Use System.out.print if you want to continue printing on the same line.