Java Methods for Outputting Numbers with Examples

使用 GPT-4o-mini 回答Java Q&A Hub

問題:

Java Output Numbers and give examples

答案:

In Java, you can output numbers using various methods, primarily through the System.out class. The most common methods for outputting numbers are System.out.print(), System.out.println(), and System.out.printf(). Below are examples of each method:

1. Using System.out.print()

This method prints the output without adding a new line at the end.

public class PrintExample {
    public static void main(String[] args) {
        int number = 10;
        double decimalNumber = 5.75;

        System.out.print("The integer is: " + number);
        System.out.print(" and the decimal is: " + decimalNumber);
    }
}

Output:

The integer is: 10 and the decimal is: 5.75

2. Using System.out.println()

This method prints the output and adds a new line at the end.

public class PrintExample {
    public static void main(String[] args) {
        int number = 10;
        double decimalNumber = 5.75;

        System.out.println("The integer is: " + number);
        System.out.println("The decimal is: " + decimalNumber);
    }
}

Output:

The integer is: 10
The decimal is: 5.75

3. Using System.out.printf()

This method allows for formatted output, similar to the printf function in C. You can specify the format of the output.

public class PrintExample {
    public static void main(String[] args) {
        int number = 10;
        double decimalNumber = 5.75;

        System.out.printf("The integer is: %d%n", number);
        System.out.printf("The decimal is: %.2f%n", decimalNumber);
    }
}

Output:

The integer is: 10
The decimal is: 5.75

Explanation of printf Format Specifiers:

  • %d is used for integers.
  • %.2f is used for floating-point numbers, where .2 specifies that two digits should be displayed after the decimal point.
  • %n is used to insert a new line, which is platform-independent.

Summary

  • Use System.out.print() for continuous output on the same line.
  • Use System.out.println() for output followed by a new line.
  • Use System.out.printf() for formatted output, allowing for more control over how numbers are displayed.