Open In App

Validate Variable Names According to Naming Conventions in Java

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Java




// Java Program Regex to Check Variable Name
// Valid according to Naming Convention
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
// Driver Class
public class VariableNameValidator {
    // Main Function
    public static void main(String[] args) {
        // Example variable names
        String validVariable = "myVariable123";
        String invalidVariable = "3rdVariable";
  
        // Check if the variable names are valid
        boolean isValid1 = isValidVariableName(validVariable);
        boolean isValid2 = isValidVariableName(invalidVariable);
  
        // Display the results
        System.out.println(validVariable + " is valid: " + isValid1);
        System.out.println(invalidVariable + " is valid: " + isValid2);
    }
  
    private static boolean isValidVariableName(String variableName) {
        // Define the regular expression for a valid variable name
        String regex = "^[a-zA-Z_$][a-zA-Z_$0-9]*$";
  
        // Create a Pattern object
        Pattern pattern = Pattern.compile(regex);
  
        // Create a Matcher object
        Matcher matcher = pattern.matcher(variableName);
  
        // Check if the variable name matches the pattern
        return matcher.matches();
    }
}


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.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads