Left pad a String in Java with zeros


The following is our string −

String str = "Tim";

Now take a StringBuilder object −

StringBuilder strBuilder = new StringBuilder();

Perform left padding and extend the string length. We have set it till 20, that would include the current string as well. The zeros that will be padded comes on the left. Append the zeros here −

while (strBuilder.length() + str.length() < 10) {
strBuilder.append('0');
}

The following is an example −

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String str = "Tim";
      StringBuilder strBuilder = new StringBuilder();
      while (strBuilder.length() + str.length() < 20) {
         strBuilder.append('0');
      }
      // append
      strBuilder.append(str);
      String res = strBuilder.toString();
      System.out.println(res);
   }
}

Output

0000000000000000Tim

Updated on: 29-Jun-2020

421 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements