VOOZH about

URL: https://www.geeksforgeeks.org/java/validate-variable-names-to-naming-conventions-in-java/

⇱ Validate Variable Names According to Naming Conventions in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Validate Variable Names According to Naming Conventions in Java

Last Updated : 23 Jul, 2025

Let's write a Java Program that checks whether a given variable name complies with the naming convention or not using Regular Expressions in Java.

Example for Validating Name of Variable Using Regex

Input: _myName
Output: Correct

Input: 2ndVariable
Output: Incorrect

Regex to Check Variable Name is Valid according to Naming Convention

Below is the implementation to Check Variable Name is Valid according to the Naming Convention:


Output
myVariable123 is valid: true
3rdVariable is valid: false




Explanation of the above Program:

The regular phrase ^[a-zA-Z_$] is the main idea.[a-zA-Z_$0–9]*$ guarantees that the variable name is

  • begins with a letter, dollar symbol ($), or underscore (_).
  • followed by one or more letter, dollar sign, underscore, or digit occurrences.
Comment