Check if Email Address is Valid or not in Java

Last Updated : 28 Nov, 2024

Validating email addresses means they meet the correct format by avoiding invalid inputs. To Validate email addresses in Java, we can use Regular Expressions (Regex).

Example:

The below example example uses Pattern and Matcher from the java.util.regex package to validate email addresses.

Java
// Java program to check if an email address
// is valid using Regex
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.ArrayList;

public class EmailValidate {
  
    // Method to check if the email is valid
    public static boolean isValid(String email) {
      
        // Regular expression to match valid email formats
        String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@" +
                            "(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
    
        // Compile the regex
        Pattern p = Pattern.compile(emailRegex);
      
        // Check if email matches the pattern
        return email != null && p.matcher(email).matches();
    }

    public static void main(String[] args) {
      
        // List of email addresses to validate
        ArrayList<String> e = new ArrayList<>();
        e.add("review-team@geeksforgeeks.org");
        e.add("writing.geeksforgeeks.org");    

        // Loop through emails and validate each
        for (String email : e) {
            System.out.println(email + ": " + (isValid(email) ? "Yes" : "No"));
        }
    }
}

Output
review-team@geeksforgeeks.org: Yes
writing.geeksforgeeks.org: No

Explanation: In the above example, the "emailRegex" checks for valid email formats like username@domain.com. The Pattern class compiles the regex and matches it against the email string. Valid emails return "Yes" and the invalid emails return "No".

Comment