Java - How do I find the length of a string in an array?
Categories:
Java: Efficiently Finding String Lengths in Arrays

Learn various methods to determine the length of strings stored within a Java array, from basic loops to modern stream API approaches, ensuring robust and readable code.
Working with arrays of strings is a common task in Java programming. Often, you'll need to inspect the properties of these strings, such as their individual lengths. This article explores several effective ways to find the length of each string within a String
array, catering to different scenarios and programming styles. We'll cover traditional loop-based methods, enhanced for-loops, and the more modern Java Stream API.
Understanding String Arrays and Lengths
Before diving into the methods, it's crucial to distinguish between the length of the array itself and the length of the individual strings it contains. An array's length (array.length
) tells you how many elements (strings, in this case) are in the array. Each string within the array, however, has its own length (string.length()
), which indicates the number of characters it contains. It's also important to handle potential null
values within the array, as calling length()
on a null
string will result in a NullPointerException
.
flowchart TD A[Start] --> B{String Array Initialization} B --> C{Iterate through Array Elements} C --> D{Is Current Element Null?} D -- Yes --> E[Handle Null (e.g., skip or default value)] D -- No --> F[Get String Length: element.length()] F --> G[Process Length (e.g., print, store)] G --> C C -- All Elements Processed --> H[End]
Flowchart for processing string lengths in an array, including null checks.
Method 1: Using a Standard For Loop
The traditional for
loop provides explicit control over array iteration. This method is straightforward and allows for easy indexing, which can be useful if you need to refer to the index of the string while processing its length. It's a fundamental approach that every Java developer should be familiar with.
public class StringLengthExample {
public static void main(String[] args) {
String[] words = {"Java", "Programming", null, "Array", "Length"};
System.out.println("Using a standard for loop:");
for (int i = 0; i < words.length; i++) {
String currentWord = words[i];
if (currentWord != null) {
System.out.println("String at index " + i + ": \"" + currentWord + "\" has length: " + currentWord.length());
} else {
System.out.println("String at index " + i + ": is null");
}
}
}
}
Example of finding string lengths using a standard for loop with null checks.
Method 2: Using an Enhanced For-Each Loop
The enhanced for-each
loop (also known as the 'for-each' loop) simplifies iteration over arrays and collections. It's more concise and less error-prone than the standard for
loop when you don't need access to the index. This is often the preferred method for simple iteration tasks.
public class StringLengthExample {
public static void main(String[] args) {
String[] words = {"Java", "Programming", null, "Array", "Length"};
System.out.println("\nUsing an enhanced for-each loop:");
for (String word : words) {
if (word != null) {
System.out.println("\"" + word + "\" has length: " + word.length());
} else {
System.out.println("A string is null");
}
}
}
}
Example of finding string lengths using an enhanced for-each loop with null checks.
Method 3: Using Java Stream API (Java 8+)
For Java 8 and later, the Stream API offers a functional and often more expressive way to process collections and arrays. Streams allow for powerful operations like filtering, mapping, and reducing data in a declarative style. This method is particularly useful for complex data transformations or when chaining multiple operations.
import java.util.Arrays;
import java.util.Objects;
public class StringLengthExample {
public static void main(String[] args) {
String[] words = {"Java", "Programming", null, "Array", "Length"};
System.out.println("\nUsing Java Stream API:");
Arrays.stream(words)
.filter(Objects::nonNull) // Filter out null strings
.forEach(word -> System.out.println("\"" + word + "\" has length: " + word.length()));
// If you want to collect lengths into a list:
System.out.println("\nCollecting lengths into a list:");
java.util.List<Integer> lengths = Arrays.stream(words)
.filter(Objects::nonNull)
.map(String::length)
.toList(); // .collect(Collectors.toList()) for older Java 8
System.out.println("List of lengths: " + lengths);
}
}
Example of finding and collecting string lengths using the Java Stream API.
null
values when iterating through arrays of objects, especially strings. Failing to do so will lead to NullPointerException
at runtime, which can crash your application.Choosing the Right Method
The best method depends on your specific needs:
- Standard
for
loop: Choose this when you need access to the index of the array elements, or for maximum control over the iteration process. - Enhanced
for-each
loop: Ideal for simple iteration where you only need the element itself, not its index. It's generally more readable and less prone to off-by-one errors. - Java Stream API: Prefer this for more complex operations, chaining multiple transformations (like filtering and mapping), or when working with larger datasets where its declarative style can improve readability and maintainability. It's also well-suited for parallel processing if performance is critical.