Skip to content
Related Articles

Related Articles

Java program to print Even length words in a String

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 12 Sep, 2022
Improve Article
Save Article

Given a string str, write a Java program to print all words with even length in the given string. Examples:

Input: s = "This is a java language"
Output: This

Input: s = "i am GFG"
Output: am


  • Take the string
  • Break the string into words with the help of split() method in String class. It takes the string by which the sentence is to be broken. So here ” “(space) is passed as the parameter. As a result, the words of the string are split and returned as a string array
String[] words = str.split(" ");
for(String word : words)
{ }
int lengthOfWord = word.length();
  • If the length is even, then print the word.

Below is the implementation of the above approach: 


// Java program to print
// even length words in a string
class GfG {
 public static void printWords(String s)
  // Splits Str into all possible tokens
  for (String word : s.split(" "))
   // if length is even
   if (word.length() % 2 == 0)
    // Print the word
 // Driver Code
 public static void main(String[] args)
  String s = "i am Geeks for Geeks and a Geek";



Time complexity: O(n) where n is length of given string
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!