Thursday, September 11, 2025

System.out.format in Java

 In Java, System.out.format() is a method used for formatted output to the console, similar to printf() in C. It allows you to control how various data types (integers, floats, strings, etc.) are displayed, including their alignment, precision, and padding.

The format() method takes a format string as its first argument, followed by a variable number of arguments that correspond to the format specifiers within the string.
Basic Syntax:
Java
System.out.format(formatString, arg1, arg2, ...);
Key Components:
  • formatStringThis is a String containing plain text and format specifiers.
  • Format SpecifiersThese begin with a percent sign (%) and indicate how a corresponding argument should be formatted. Common format specifiers include:
    • %d: For decimal integers.
    • %f: For floating-point numbers.
    • %s: For strings.
    • %n: For a platform-independent newline character.
  • Arguments (arg1arg2, ...): These are the values to be formatted and inserted into the output string according to the format specifiers.
Example:
Java
public class FormatExample {    public static void main(String[] args) {        String name = "Alice";        int age = 30;        double salary = 75000.50;        System.out.format("Name: %s, Age: %d, Salary: %.2f%n", name, age, salary);    }}
Output:
Code
Name: Alice, Age: 30, Salary: 75000.50
Explanation of Format Specifiers in the Example:
%s: Formats the name string, %d: Formats the age integer, %.2f: Formats the salary double to two decimal places, and %n: Inserts a newline character.
Additional Formatting Options (Flags, Width, Precision):
Format specifiers can also include flags, width, and precision settings for more advanced formatting. For instance:
  • %5d: Right-justifies an integer within a field of 5 characters.
  • %-10s: Left-justifies a string within a field of 10 characters.
  • %05d: Pads an integer with leading zeros to a width of 5.
  • %,d: Adds locale-specific group separators (e.g., commas for thousands) to an integer.
For a comprehensive list of format specifiers and options, refer to the documentation for the java.util.Formatter class.

No comments:

Post a Comment

The AI Driven Software Developer, Optimize Innovate Transform

  The AI-Driven Software Developer: Optimize, Innovate, Transform": AI Transformation in Software Development : Understand how AI is re...