- How to Add Leading Zeros to Integers in Java ? String Left Padding Example Program
- Left and Right padding Integer and String in Java
- Java String left and right padding example
- Pad a String with Zeros or Spaces in Java
- 1. Overview
- 2. Pad a String Using Custom Methods
- 2.1. Using StringBuilder
- 2.2. Using substring
- 2.3. Using String.format
- 3. Pad a String Using Libraries
- 3.1. Apache Commons Lang
- 3.2. Google Guava
- 4. Conclusion
How to Add Leading Zeros to Integers in Java ? String Left Padding Example Program
Hello guys, you may know that from Java 5 onwards it’s easy to left pad Integers with leading zeros when printing number as String. In fact, You can use the same technique to left and right pad Java String with any characters including zeros, space. Java 5 provides String format methods to display String in various formats. By using the format() method we can add leading zeros to an Integer or String number. By the way, this is also known as left padding Integers with zero in Java. For those who are not familiar with the left and right padding of String, here is a quick recap;
When we add characters like zero or space on left of a String, its known as left padding and when we do the same on the right side of String, it’s known as right padding of String. This is useful when you are displaying currency amounts or numbers, which has fixed width, and you want to add leading zeros instead of space in front of Integers.
If by any chance, You are not using Java 5 or you like to use open source projects like Apache commons, Google Guava or Spring framework then you can use leftPad() and rightPad() methods provided by StringUtils class. I personally prefer JDK function if it provides required functionality but It’s very common to have Spring , Apache commons or Guava already in your classpath.
In that case use those method because they are more convenient, readable and you don’t need to remember different String formatting options to left and right pad a String with zero or any character . By the way, while padding String and number left and right, it’s worth remember not to right pad numbers with zero, it will completely change there meaning.
Left and Right padding Integer and String in Java
In this Java tutorial, we will see How to add leading zero to Integer or String in Java. Both are actually same because you only print String in Java and left padding is done at the time of display and the original Integer value is not affected. The format() method of String class in Java 5 is the first choice. You just need to add «%03d» to add 3 leading zeros in an Integer. Formatting instruction to String starts with «%» and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers.
It means if the number has 1 or 2 digits than some leading zeros will be added to the number to make its width equal to 3. This is also known as left padding of Integers in Java. By default Java left pad with space and if you add 0 then Integer will be left padded with zero. You can not use other character e.g. # here.
On the other hand both Spring and Apache commons StringUtils provides you convenient leftPad() and rightPad() method to add left and right padding on String in Java. These methods also allow you to pass any character of your choice to be used as padding e.g. zero, # or space.
Java String left and right padding example
Let’s see some code example of left and right padding String and Integer in Java using Spring, Apache Commons StringUtils and format method of String.
Pad a String with Zeros or Spaces in Java
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We’re looking for a new Java technical editor to help review new articles for the site.
1. Overview
In this short tutorial, we’ll see how to pad a String in Java. We’ll focus mainly on a left pad, meaning that we’ll add the leading spaces or zeros to it until it reaches the desired length.
The approach for the right padded String is very similar, so we’ll only point out the differences.
2. Pad a String Using Custom Methods
The String class in Java doesn’t provide a convenient method for padding, so let’s create several methods on our own.
First, let’s set some expectations:
assertEquals(" 123456", padLeftZeros("123456", 10)); assertEquals("0000123456", padLeftZeros("123456", 10));
2.1. Using StringBuilder
We can achieve this with StringBuilder and some procedural logic:
public String padLeftZeros(String inputString, int length) < if (inputString.length() >= length) < return inputString; >StringBuilder sb = new StringBuilder(); while (sb.length() < length - inputString.length()) < sb.append('0'); >sb.append(inputString); return sb.toString(); >
We can see here that if the original text’s length is equal to or bigger than the desired length, we return the unchanged version of it. Otherwise, we create a new String, starting with spaces, and adding the original one.
Of course, if we wanted to pad with a different character, we could just use it instead of a 0.
Likewise, if we want to right pad, we just need to do new StringBuilder(inputString) instead and then add the spaces at the end.
2.2. Using substring
Another way to do the left padding is to create a String with the desired length that contains only pad characters and then use the substring() method:
StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) < sb.append(' '); >return sb.substring(inputString.length()) + inputString;
2.3. Using String.format
Finally, since Java 5, we can use String.format():
return String.format("%1$" + length + "s", inputString).replace(' ', '0');
We should note that by default the padding operation will be performed using spaces. That’s why we need to use the replace() method if we want to pad with zeros or any other character.
For the right pad, we just have to use a different flag: %1$-.
3. Pad a String Using Libraries
Also, there are external libraries that already offer padding functionalities.
3.1. Apache Commons Lang
Apache Commons Lang provides a package of Java utility classes. One of the most popular ones is StringUtils.
To use it, we’ll need to include it into our project by adding its dependency to our pom.xml file:
org.apache.commons commons-lang3 3.12.0
And then we pass the inputString and the length, just like the methods we created.
We can also pass the padding character:
assertEquals(" 123456", StringUtils.leftPad("123456", 10)); assertEquals("0000123456", StringUtils.leftPad("123456", 10, "0"));
Again, the String will be padded with spaces by default, or we need to explicitly set another pad character.
There are also corresponding rightPad() methods.
To explore more features of the Apache Commons Lang 3, check out our introductory tutorial. To see other ways of the String manipulation using the StringUtils class, please refer to this article.
3.2. Google Guava
Another library that we can use is Google’s Guava.
Of course, we first need to add it to the project by adding its dependency:
com.google.guava guava 31.0.1-jre
And then we use the Strings class:
assertEquals(" 123456", Strings.padStart("123456", 10, ' ')); assertEquals("0000123456", Strings.padStart("123456", 10, '0'));
There is no default pad character in this method, so we need to pass it every time.
To right pad, we can use padEnd() method.
The Guava library offers many more features, and we have covered a lot of them. Look here for the Guava-related articles.
4. Conclusion
In this quick article, we illustrated how we can pad a String in Java. We presented examples using our own implementations or existing libraries.
As usual, a complete source code can be found over on GitHub.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes: