Last Updated : 12 Jul, 2025
Given a string s, write a Java program to print all words with even length in the given string.
Example to print even length words in a StringInput: s = "i am Geeks for Geeks and a Geek" Output: am
Geek
Example:
Java
// Java program to print
// even length words in a string
class GfG {
public static void printWords(String s)
{
for (String w : s.split(" ")){
// if length is even
if (w.length() % 2 == 0)
System.out.println(w);
}
}
public static void main(String[] args)
{
String s = "i am Geeks for Geeks and a Geek";
printWords(s);
}
}
Explanation of the above Program:
Using Dynamic ProgrammingTime complexity: O(n) where n is length of given string
Auxiliary Space: O(1)
In this approach, we split the string into words and store the length of each word in an array. Then, we loop through the array and check if the length of each word is even. If it is, we print the word. This approach uses dynamic programming to store the length of each word in an array, which can be reused in subsequent loops, reducing the overall number of calculations. However, in practice, the difference in performance between this approach and the original approach is likely to be negligible.
Here is the DP approach in Java:
Java
class GfG {
public static void printWords(String s) {
// Split string into words
String[] w = s.split(" ");
// Create an array to store the
// length of each word
int[] len = new int[w.length];
// Calculate the length of each
// word and store in the array
for (int i = 0; i < w.length; i++) {
len[i] = w[i].length();
}
// Check if the length of each word
// is even and print if true
for (int i = 0; i < w.length; i++) {
if (len[i] % 2 == 0) {
System.out.println(w[i]);
}
}
}
public static void main(String[] args) {
String s = "i am Geeks for Geeks and a Geek";
printWords(s);
}
}
Complexity of the above Program:
Time complexity: O(n) where n is length of given string
Auxiliary Space: O(n) where n is the total number of characters in the input string.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4