Formatting Strings with System.out.format () method. - Java Language Basics

Java examples for Language Basics:String

Introduction

System.out.format () method takes two arguments: the output format template and the string to display.

Demo Code

public class Main {
  public static void main(String[] args) {
    int accountBalance = 1234;
    System.out.format("Balance: $%,d%n", accountBalance);
  }/*from   ww w.ja va  2 s  .com*/
}

The formatting string begins with a percent sign % followed by one or more flags.

The %,d code displays a decimal with commas dividing each group of three digits.

The %n code displays a newline character.

The next example displays the value of pi to 11 decimal places:

Demo Code

public class Main {
  public static void main(String[] args) {
    double pi = Math.PI; 
    System .out.format ("%.11f%n", pi); 
  }/*from  ww w.ja va 2 s  . c  o m*/
}

Result


Related Tutorials