In this article, we will understand how to print even length words. String is a datatype that contains one or more characters and is enclosed in double quotes (“ ”). Char is a datatype that contains an alphabets or an integer or an special character.
Below is a demonstration of the same −
Suppose our input is −
Input string: Java Programming are cool
The desired output would be −
The words with even lengths are: Java cool
Algorithm
Step 1 - START Step 2 - Declare a string namely input_string. Step 3 - Define the values. Step 4 - Iterate over the string usinf a for-loop, compute word.length() modulus of 2 for each word to check if the length gets completely divided by 2. Store the words. Step 5 - Display the result Step 6 - Stop
Example 1
Here, we bind all the operations together under the ‘main’ function.
public class EvenLengths { public static void main(String[] args) { String input_string = "Java Programming are cool"; System.out.println("The string is defined as: " +input_string); System.out.println("\nThe words with even lengths are: "); for (String word : input_string.split(" ")) if (word.length() % 2 == 0) System.out.println(word); } }
Output
The string is defined as: Java Programming are cool The words with even lengths are: Java cool
Example 2
Here, we encapsulate the operations into functions exhibiting object-oriented programming.
public class EvenLengths { public static void printWords(String input_string) { System.out.println("\nThe words with even lengths are: "); for (String word : input_string.split(" ")) if (word.length() % 2 == 0) System.out.println(word); } public static void main(String[] args) { String input_string = "Java Programming are cool"; System.out.println("The string is defined as: " +input_string); printWords(input_string); } }
Output
The string is defined as: Java Programming are cool The words with even lengths are: Java cool