Displaying at most 10 characters in a string in Java

Java 8Object Oriented ProgrammingProgramming

To display at most 10 characters in a string, work with the Formatter class.

Import the following package for Formatter class in Java −

import java.util.Formatter;

Create a new Formatter object −

Formatter f = new Formatter();

Let us now display at most 10 characters in a string −

f = new Formatter();
System.out.println("Displaying at most 10 characters: "+f.format("%.10s", "This is demo text!"));

The following is an example −

Example

 Live Demo

import java.util.Formatter;
public class Demo {
   public static void main(String args[]) {
      Formatter f = new Formatter();
      String str = "This is demo text!";
      System.out.println("String: "+str);
      // displaying at most 10 characters
      f = new Formatter();
      System.out.println("Displaying at most 10 characters: "+f.format("%.10s", "This is demo text!"));
   }
}

Output

String: This is demo text!
Displaying at most 10 characters: This is de
raja
Published on 26-Dec-2018 11:15:00
Advertisements