How to find the vowels in a given string using Java?

By IncludeHelp Last updated : February 4, 2024

A string is a sequence of characters. These characters may be alphabets, digits, and special characters. In this tutorial, we will learn how to find the vowels in a given string.

Problem statement

Given a string, you have to find and print the vowels from the given string using a Java program.

Finding the vowels in a given string

To find the vowels in a given string, iterate through each character of the string, and check whether the character is a vowel or not using the conditional statement. If the character is a vowel, print it.

Java program to find the vowels in a given string

In this program, we are reading a string from the user, and printing the vowels in it.

// Java code to find the vowels in a given string

// Importing the package
import java.util.*;

public class Main {
  public static void main(String args[]) {
    // Declaring a string variable
    String str;

    // Taking user input
    Scanner sc = new Scanner(System.in);
    System.out.println("Input a string :");
    str = sc.nextLine();

    // Printing the string
    System.out.println("The string is : " + str);

    // Finding and printing the vowels
    for (char ch: str.toCharArray()) {
      // Checking character is a vowel
      if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
        ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
        // Printing the vowel
        System.out.println(ch);
      }
    }
  }
}

Output

The output of the above program is:

RUN 1:
Input a string :
Hello World
The string is : Hello World
e
o
o

RUN 2:
Input a string :
Learn Java Programming Here With Us.
The string is : Learn Java Programming Here With Us.
e
a
a
a
o
a
i
e
e
i
U
 
 

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.