Left pad a String in Java with zeros

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 20-Dec-2018 08:01:04
Advertisements