How to find If a given String contains only letters in Java?

To verify whether a given String contains only characters −

  • Read the String.
  • Convert all the characters in the given String to lower case using the toLower() method.
  • Convert it into a character array using the toCharArray() method of the String class.
  • Find whether every character in the array is in between a and z, if not, return false.

Example

Following Java program accepts a String from the user and displays whether it is valid or not.

import java.util.Scanner;
public class StringValidation{
   public boolean validtaeString(String str) {
      str = str.toLowerCase();
      char[] charArray = str.toCharArray();
      for (int i = 0; i = 'a' && ch 

Output

Enter a string value:
24ABCjhon
Given String is invalid
Updated on: 2019-08-07T12:13:04+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements