How to check if a string is a valid keyword in Java?

JavaServer Side ProgrammingProgramming

To check if a string is a valid keyword in Java, the code is as follows −


 Live Demo

import java.util.*;
public class Demo{
   static boolean valid_identifier(String my_str, int n){
      if (!((my_str.charAt(0) >= 'a' && my_str.charAt(0) <= 'z')
         || (my_str.charAt(0)>= 'A' && my_str.charAt(1) <= 'Z')
         || my_str.charAt(0) == '_'))
         return false;
      for (int i = 1; i < my_str.length(); i++){
         if (!((my_str.charAt(i) >= 'a' && my_str.charAt(i) <= 'z')
            || (my_str.charAt(i) >= 'A' && my_str.charAt(i) <= 'Z')
            || (my_str.charAt(i) >= '0' && my_str.charAt(i) <= '9')
            || my_str.charAt(i) == '_'))
         return false;
      return true;
   public static void main(String args[]){
      String my_str = "Hi_there!3";
      int n = my_str.length();
      if (valid_identifier(my_str, n))
         System.out.println("It is valid");
         System.out.println("It is invalid");


It is invalid

A class named Demo contains a function named ‘valid_identifier’ that returns Boolean output. It takes a string and an integer, checks to see if the string contains characters between ‘a’ to ‘z’ or ‘A’ to ‘Z’ or an underscore character, otherwise returns false. It iterates through the length of the string, and checks for the validity of the string and sees if it contains integers between ‘0’ and ‘9’ too. Otherwise, it returns false. In the main function, the string is defined, and the length of the string is assigned to a variable. The function is called by passing the string and the string length. This displays the relevant message.

Published on 17-Aug-2020 09:39:08