ADVERTISEMENT
ADVERTISEMENT

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 Solution:

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 = "[email protected]";
    String email2 = "[email protected]@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.

Java Basic Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.