Formatting of Strings in Java

ゝ一纸荒年。 2023-01-19 03:09 104阅读 0赞

Introduction

In Java, we can format strings depending on our needs and get the required output. The printf command is very useful in Java. The printf command takes text as a string and formats it depending on the instructions given to it.

String Formatting

  • “%s” Format a string with the required number of characters.
  • “%10s” Format a string with the specified number of characters and also right justify.
  • “%-10s” Format a string with the specified number of characters and also left justify.

For formatting numbers, we use the “d” character and for floating-point numbers we use the “f” character.

Example

  1. package demo;
    public class Demo {
    public static void main(String args[]) {
    String n = “NAME”;
    System.out.printf(“%10s %n”, n);
    }
    }

Output

string formatting right justify

Example

  1. package demo;
    public class Demo {
    public static void main(String args[]) {
    String n = “NAME”;
    String l = “LOCATION”;
    System.out.printf(“%-10s %10s %n”, n, l);
    }
    }

Output

string formatting left justify

Integer Formatting

  • “%d” Format a string with the required numbers.
  • “%5d” Format a string with the required number of integers and also pad with spaces to the left side if integers are not adequate.
  • “%05d” Format a string with the required number of integers and also pad with zeroes to the left if integers are not adequate.

Example

  1. package demo;
    public class Demo {
    public static void main(String args[]) {
    String r = “ROLL NO”;
    int i = 12345;
    System.out.printf(“%s %15d %n”, r, i);
    }
    }

Output

integer formatting

Example

  1. package demo;
    public class Demo {
    public static void main(String args[]) {
    int r = 54321;
    int i = 12345;
    System.out.printf(“%015d %15d %n”, r, i);
    }
    }

Output

integer formatting with zeroes

Floating Point Number Formatting

  • “%f” Format a string with the required numbers. It will always give six decimal places.
  • “%.3f” Format a string with the required numbers. It gives three decimal places.
  • “%12.3f” Format a string with the required numbers. The string occupies twelve characters. If numbers are not adequate then spaces are used on the left side of the numbers.

Example

  1. package demo;
    public class Demo {
    public static void main(String args[]) {
    System.out.printf(“%.3f %n”, 123.45789);
    }
    }

Output

floating point no. formatting

Example

  1. package demo;
    public class Demo {
    public static void main(String args[]) {
    System.out.printf(“%12.3f %n”, 123.45789);
    }
    }

Output

floating point no. formatting with spaces

Summary

This article explains string formatting in Java and the use of the printf command in Java.

reference:https://www.c-sharpcorner.com/UploadFile/3614a6/formatting-of-strings-in-java/

发表评论

表情:
评论列表 (有 0 条评论,104人围观)

还没有评论,来说两句吧...

相关阅读