Creating Strings with Specified Length and Fill Character in Java: Analysis of Efficient Implementation Methods

Nov 29, 2025 · Programming · 10 views · 7.8

Keywords: Java String Processing | Apache Commons Lang | Performance Optimization

Abstract: This article provides an in-depth exploration of efficient methods for creating strings with specified length and fill characters in Java. By analyzing multiple solutions from Q&A data, it highlights the use of Apache Commons Lang's StringUtils.repeat() method as the best practice, while comparing it with standard Java library approaches like Arrays.fill(), Java 11's repeat() method, and other alternatives. The article offers comprehensive evaluation from perspectives of performance, code simplicity, and maintainability, providing developers with selection recommendations for different scenarios.

Problem Background and Requirements Analysis

In Java programming practice, there is often a need to create strings of specified length filled with specific characters. This requirement appears in various scenarios such as generating fixed-length placeholders, creating separators, initializing buffers, etc. However, the Java standard library does not provide a direct constructor for this functionality, requiring developers to find efficient alternatives.

Core Solution: Apache Commons Lang Library

Based on Q&A data analysis, using Apache Commons Lang library's StringUtils.repeat() method is recognized as the optimal solution. This method provides a concise and efficient implementation:

String filled = StringUtils.repeat("*", 10);

This method accepts two parameters: the character or string to repeat, and the number of repetitions. The internal implementation is highly optimized and can handle various edge cases, including scenarios with length 0 or negative values. As a widely used utility library, Apache Commons Lang is already present as a dependency in most non-trivial projects, resulting in low introduction cost.

Standard Java Library Alternatives

For projects that prefer not to introduce external dependencies, the standard Java library's Arrays.fill() method can be used:

protected String getStringWithLengthAndFilledWithCharacter(int length, char charToFill) {
  if (length > 0) {
    char[] array = new char[length];
    Arrays.fill(array, charToFill);
    return new String(array);
  }
  return "";
}

This approach is more concise than manual looping, and the Arrays.fill() method is optimized at the底层 level with good performance characteristics. Additionally, the code includes length checks for enhanced robustness.

Java 11 and Later Solutions

Starting from Java 11, the String class natively provides a repeat() method:

String s = "*".repeat(10);

This is the most concise solution, requiring no external dependencies. For projects using newer Java versions, this is the preferred approach. The internal implementation is similarly highly optimized with excellent performance.

Comparison of Other Alternative Methods

The Q&A data also mentioned several other implementation approaches:

String.format Method

String s = String.format("%0" + length + "d", 0).replace('0', charToFill);

Collections.nCopies Method

String s = String.join("", Collections.nCopies(length, String.valueOf(charToFill)));

Stream API Method

String s = Stream.generate(() -> String.valueOf(charToFill)).limit(length).collect(Collectors.joining());

While these methods can functionally achieve the requirement, they have shortcomings in terms of performance and code readability. String.format involves string formatting and replacement with significant overhead; Collections.nCopies and Stream API methods create unnecessary intermediate objects with lower memory efficiency.

Performance Analysis and Best Practices

From a performance perspective, the efficiency ranking of various methods is approximately:

  1. Java 11+ String.repeat() - Native implementation, optimal performance
  2. Apache Commons Lang StringUtils.repeat() - Highly optimized third-party implementation
  3. Standard library Arrays.fill() - Good performance characteristics
  4. Other methods - Relatively poor performance

In practical projects, selection should consider:

Relevant Knowledge of String Processing

The reference article provides in-depth knowledge about string processing. In Java, strings are immutable objects, and any modification operations create new string instances. Understanding string internal representation and operational characteristics is crucial for writing efficient string processing code.

Strings are stored in memory as character arrays, and the use of char[] arrays forms the foundation of efficient string operations. Both StringUtils.repeat() and Arrays.fill() methods leverage the efficient operation characteristics of character arrays at the底层 level.

Summary and Recommendations

Creating strings with specified length and fill characters has multiple implementation approaches in Java. Based on Q&A data analysis and practical performance considerations, the following selection strategy is recommended:

Choosing the appropriate implementation method not only improves code performance but also enhances code readability and maintainability, representing an important practice in high-quality Java programming.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.