Java Formatter Close with try-with-resources statement

Introduction

Java Formatter class implements the AutoCloseable interface.

It supports the try-with-resources statement.

By using this approach, the Formatter is automatically closed when it is no longer needed.


// Use automatic resource management with Formatter.
import java.util.Formatter;

public class Main {
  public static void main(String args[]) {

    try (Formatter fmt = new Formatter()) {
      fmt.format("%s is easy %d %f", "Java", 10, 123.6);
      System.out.println(fmt);//from  w  w  w. ja  v a2 s .  c o  m
    }
  }
}



PreviousNext

Related