Left Justify Output in Java



In Java, the left-justifying output means aligning text or data to the left within a specified width, with extra spaces on the right to fill the remaining space. It is commonly used when displaying tabular data or formatting strings.

Left justification can be obtained using methods such as String.format() or printf(), which allow you to specify the width of the output field and the alignment of the content. Including a minus sign after the %, makes it left justified.

Note ? By default, output is right justified

To display the Left justify output in Java is quite easy. Let us learn the following methods:

Left justify output using printf() Method

To retrieve the left justify output from a given data, we can include a minus sign after the %, making it left justified. The printf() method is used to display the left justify output.

Example

The following example uses the printf() method to justify a string and an integer within specified widths.

public class PrintfExample {
   public static void main(String[] args) {
      String str = "Hello, World!";
      int number = 42;
      System.out.printf("Left justified string: %-20s%n", str);
      System.out.printf("Left justified number: %-10d%n", number);
   }
}

Output

The above program produces the following results ?

Left justified string: Hello, World!       
Left justified number: 42 

Left justify output using String format() Method

Here is another way to retrieve the left justify output in Java using the format() method. This method belongs to the string class and is used to format the given data into a specific format using specifiers.

Example

In the example below, we use the String.format() method to retrieve the left-justified output by formatting the given integer and string values.

public class StringFormatExample {
   public static void main(String[] args) {
      String str = "Hello, World!";
      int number = 42;

      String formattedStr = String.format("Left justified string: %-20s", str);
      String formattedNum = String.format("Left justified number: %-10d", number);

      System.out.println(formattedStr);
      System.out.println(formattedNum);
   }
}

Output

Following is the output of the above program ?

Left justified string: Hello, World!       
Left justified number: 42
Revathi Satya Kondra
Revathi Satya Kondra

Technical Content Writer, Tutorialspoint

Updated on: 2024-12-24T12:04:36+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements