In this article, we will learn how to write a Java program to find the strings with the maximum length in an array. This is a useful exercise for working with arrays and understanding how to handle string properties in Java.
Problem Statement:
We are given an array of strings, and the task is to identify and return the string(s) that have the maximum length in the array. If there are multiple strings with the same maximum length, all of them should be returned.
Approach to Solve the Problem
- Find Maximum Length:
- Traverse the array to find the maximum length of the strings.
- Collect Strings:
- Traverse the array again to collect all strings that have the maximum length.
- Display Results:
- Print the string(s) with the maximum length.
Java program to find strings of maximum length in an Array
Here is the Java program to solve the problem:
package com.javacodepoint.stringarray;
import java.util.ArrayList;
import java.util.List;
public class MaxLengthStrings {
public static void main(String[] args) {
// Input array of strings
String[] words = { "apple", "banana", "cherry", "dragonfruit" };
// Call the method to find maximum length strings
List<String> maxLengthStrings = findMaxLengthStrings(words);
// Display the results
System.out.println("The string(s) with the maximum length: " + maxLengthStrings);
}
// Method to find strings with the maximum length in an array
public static List<String> findMaxLengthStrings(String[] words) {
List<String> result = new ArrayList<>();
int maxLength = 0;
// Find the maximum length
for (String word : words) {
if (word.length() > maxLength) {
maxLength = word.length();
}
}
// Collect strings with the maximum length
for (String word : words) {
if (word.length() == maxLength) {
result.add(word);
}
}
return result;
}
}
OUTPUT:
The string(s) with the maximum length: [dragonfruit]
Code Explanation:
- Input Array: The array
words
contains the strings to be analyzed. - Find Maximum Length:
- Use a
for
loop to find the maximum length among the strings in the array.
- Use a
- Collect Strings:
- Use another
for
loop to collect all strings that match the maximum length.
- Use another
- Output Results:
- The program displays the string(s) with the maximum length.
Conclusion
This program is an effective solution for finding strings of maximum length in an array. It helps you practice important concepts such as string manipulation, array traversal, and list handling in Java.
You can learn the Top 20 string array programs for interview preparation (Click here).