- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to format a string
To format a string, use the String.format() method in Java. The following is an example that formats a string %s.
Example
public class Demo { public static void main(String []args) { String str = String.format("%s %s", "demo", "text"); System.out.print("String: "+str); } }
Output
String: demo text
Left pad a string
To left pad a string, use the String.format and set the spaces.
String.format("|%20s|", "demotext")
If you add 30 above, it will display the first string after 30 spaces from the beginning.
String.format("|%30s|", "demotext")
The following is an example.
Example
public class Demo { public static void main(String []args) { System.out.print(String.format("|%20s|", "demotext")); System.out.println("Left padded!"); } }
Output
| demotext|Left padded
Right pad a string
To right pad a string, use the String.format and set the spaces.
String.format("%1$-" + 20 + "s", "demotext"));
If you add 30 above, it will display the next string after 30 spaces from the beginning.
String.format("%1$-" + 30 + "s", "demotext")
The following is an example.
Example
public class Demo { public static void main(String []args) { System.out.print(String.format("%1$-" + 20 + "s", "demotext")); System.out.println("Right padded!"); } }
Output
demotext Right padded!
- Related Articles
- Java Program to parse string date value with default format
- How to format a date to String in Java?
- Java Program to format time using Custom Format
- Java Program to format Month in MMMM format
- Java Program to format LocalDateTime as ISO_WEEK_DATE format
- Java Program to format LocalTimeDate as BASIC_ISO_DATE format
- Java Program to Format time in AM-PM format
- Java String format() method example.
- How to Format a Date String using SimpleDateFormat in Java?
- Java Program to format hour in H (0-23) format in Java
- Java Program to format date in mm-dd-yyyy hh:mm:ss format
- Java Program to format strings into table
- Java Program to format date with SimpleDateFormat
- Java Program to format date with DateFormat.FULL
- Java Program to format time with DateFormat.MEDIUM

Advertisements