Q:

Java program to check a given Email address is valid or not

belongs to collection: Java Basic Programs

0

Java program to check a given Email address is valid or not

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this program, we will check a given email address is valid or not using regular expressions and print appropriate messages.

Program/Source Code:

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 = "xyl.123@testmail.com";
    String email2 = "xyl@123@testmail.com";

    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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to store the date in a single integer... >>
<< Java program to check a given IP address is valid ...