Java test valid email address

Here are a few ways to test if a Java string is a valid email address:

Method 1: Using a regular expression

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class EmailValidator {
    private static final Pattern EMAIL_PATTERN = Pattern.compile("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$");

    public static boolean isValidEmail(String email) {
        Matcher matcher = EMAIL_PATTERN.matcher(email);
        return matcher.matches();
    }
}

This regular expression matches most common email address formats, but it's not foolproof. You can adjust the pattern to fit your specific needs.

Method 2: Using a library

import com.google.common.net.InternetDomainName;
import com.google.common.net.Validation;

public class EmailValidator {
    public static boolean isValidEmail(String email) {
        try {
            InternetDomainName domainName = InternetDomainName.from(email);
            return Validation.isValid(email);
        } catch (Exception e) {
            return false;
        }
    }
}

This method uses the Google Guava library, which provides a more comprehensive email validation mechanism.

Method 3: Using a simple check

public class EmailValidator {
    public static boolean isValidEmail(String email) {
        String[] parts = email.split("@");
        if (parts.length!= 2) {
            return false;
        }
        String localPart = parts[0];
        String domain = parts[1];
        if (localPart.isEmpty() || domain.isEmpty()) {
            return false;
        }
        return true;
    }
}

This method is very basic and may not catch all invalid email addresses, but it's simple and easy to implement.

You can use these methods in your Java code like this:

String email = "[email protected]";
if (EmailValidator.isValidEmail(email)) {
    System.out.println("Email is valid");
} else {
    System.out.println("Email is not valid");
}

Remember that email validation is not an exact science, and there may be valid email addresses that don't pass these tests. It's always a good idea to use a combination of these methods and additional checks to ensure the email address is valid and well-formed.