
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if a String is a Valid Keyword in Java
To check if a string is a valid keyword in Java, the code is as follows −
Example
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"); else System.out.println("It is invalid"); } }
Output
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.
Advertisements