Display At Most 10 Characters in a String in Java



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
Updated on: 2019-07-30T22:30:24+05:30

465 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements