Home »
Java Programs »
Java Basic Programs
Java program to check a given Email address is valid or not
Given/input an email address, we have to check whether it is valid or not.
Submitted by Nidhi, on March 04, 2022
Problem statement
In this program, we will check a given email address is valid or not using regular expressions and print appropriate messages.
Java program to check a given Email address is valid or not
The source code to check a given Email address is valid or not is given below. The given program is compiled and executed successfully.
// Java program to check a given Email address
// is valid or not
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.*;
public class Main {
public static boolean isValidEmail(String val) {
String regex = "^[a-zA-Z0-9_+&*-]+(?:\\." +
"[a-zA-Z0-9_+&*-]+)*@" +
"(?:[a-zA-Z0-9-]+\\.)+[a-z" +
"A-Z]{2,7}$";
Pattern pattern = Pattern.compile(regex);
if (val == null)
return false;
return pattern.matcher(val).matches();
}
public static void main(String[] args) {
String email1 = "[email protected]";
String email2 = "xyl@[email protected]";
if (isValidEmail(email1) == true)
System.out.println("Email is valid");
else
System.out.println("Email is not valid");
if (isValidEmail(email2) == true)
System.out.println("Email is valid");
else
System.out.println("Email is not valid");
}
}
Output
Email is valid
Email is not valid
Explanation
In the above program, we created a public class Main. It contain two static methods isValidEmail() and main().
The isValidEmail() method returns true when the given string contains a valid Email address otherwise it returns false.
The main() method is an entry point for the program. Here, we used a regular expression to check a given Email address is valid or not and printed the appropriate message.
Java Basic Programs »