Displaying 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

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

323 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements