Tech career with our top-tier training in Data Science, Software Testing, and Full Stack Development.
phone to 4Achievers +91-93117-65521 +91-801080-5667
Navigation Icons Navigation Icons Navigation Icons Navigation Icons Navigation Icons Navigation Icons Navigation Icons

+91-801080-5667
+91-801080-5667
Need Expert Advise, Enrol Free!!
Share this article

Simple Email Validator in Java – A Beginner’s Guide

Simple Email Validator in Java – Full Guide for Beginners

In this guide, we will walk you through creating a simple email validator program in Java. This program will validate an email address based on basic rules using regular expressions (regex). For beginners, it’s an excellent exercise to understand how to use regular expressions in Java, as well as basic input handling.

What You Will Learn:

  • How to validate an email using regex in Java
  • How to take user input and use it for validation
  • How to implement basic error handling and display output

Step-by-Step Guide to Creating the Email Validator in Java

Prerequisites:

  1. You should have a basic understanding of Java programming.
  2. You should know how to write Java classes, methods, and use basic libraries.
  3. A simple text editor or IDE (such as IntelliJ IDEA, Eclipse, or NetBeans) installed on your system.

1. Setting Up Your Java Environment

Before starting, make sure you have the Java Development Kit (JDK) installed on your computer. You can download it from the official Oracle website if you haven’t already.

  • Download JDK: Oracle JDK
  • After downloading and installing the JDK, make sure your environment variables are set up properly so you can run Java from the terminal.

2. Writing the Simple Email Validator Program

Create a new Java class named EmailValidator. Here's a basic outline of the code:
 

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

public class EmailValidator {

    // Method to validate the email
    public static boolean isValidEmail(String email) {
        // Define the regular expression for a valid email
        String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
        
        // Compile the regex
        Pattern pattern = Pattern.compile(emailRegex);
        
        // Match the input email with the pattern
        Matcher matcher = pattern.matcher(email);
        
        // Return true if the email matches the pattern
        return matcher.matches();
    }

    public static void main(String[] args) {
        // Create a scanner object for user input
        Scanner scanner = new Scanner(System.in);

        // Ask the user to input an email address
        System.out.println("Enter an email address to validate:");
        String email = scanner.nextLine();

        // Validate the email
        if (isValidEmail(email)) {
            System.out.println("The email address " + email + " is valid.");
        } else {
            System.out.println("The email address " + email + " is not valid.");
        }

        // Close the scanner object
        scanner.close();
    }
}

3. Explanation of the Code

  • Imports: We import java.util.Scanner for reading user input and java.util.regex.* for regular expression functionality.

  • isValidEmail Method: This method takes an email address as a parameter and returns true if it matches the regex pattern, and false if it does not.

  • Regular Expression: The regular expression used here is designed to match most valid email formats:

     

    String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
    

     

  • ^[a-zA-Z0-9_+&*-]+ allows the username part of the email (before the @ symbol) to include letters, digits, and some special characters.
  • @ symbol separates the username and domain parts.
  • (?:[a-zA-Z0-9-]+\\.)+ matches the domain name part (with periods separating domain labels).
  • [a-zA-Z]{2,7}$ ensures that the domain ends with a valid Top-Level Domain (TLD) like .com, .org, etc+
     
  • main Method:

    • We use a Scanner to get the email input from the user.
    • The isValidEmail method is called to check if the email is valid.
    • Based on the result, we print whether the email is valid or not.
  • 4. Running the Program

    To run this Java program, follow these steps:

Compile the Program: Open a terminal or command prompt and navigate to the directory where your EmailValidator.java file is located.

Run the following command to compile the Java file:
 

javac EmailValidator.java

Run the Program: After the compilation is successful, run the program with:

java EmailValidator
  1. Test the Program:

    • When you run the program, you’ll be prompted to enter an email address.
    • The program will then validate the email address and print whether it's valid or not.

5. Sample Output

Valid Email:

Enter an email address to validate:
john.doe@example.com
The email address john.doe@example.com is valid.

Invalid Email:

Enter an email address to validate:
john.doe@com
The email address john.doe@com is not valid.

Key Concepts Covered in This Guide:

  1. Regular Expressions in Java: We used regular expressions to define a pattern for valid email addresses.
  2. Scanner Class: We used Scanner to read user input from the console.
  3. Conditional Logic: We used if-else statements to display appropriate messages based on the validation result.
  4. Basic Java Syntax: This program demonstrates fundamental Java syntax like method creation, class structure, and string manipulation.

This simple email validator is a great starting point for Java beginners to understand how regex and input handling work in Java. Once you’ve understood this program, you can build on it to add additional validation checks or integrate it with a larger application.

Aaradhya, an M.Tech student, is deeply engaged in research, striving to push the boundaries of knowledge and innovation in their field. With a strong foundation in their discipline, Aaradhya conducts experiments, analyzes data, and collaborates with peers to develop new theories and solutions. Their affiliation with "4achievres" underscores their commitment to academic excellence and provides access to resources and mentorship, further enhancing their research experience. Aaradhya's dedication to advancing knowledge and making meaningful contributions exemplifies their passion for learning and their potential to drive positive change in their field and beyond.

Explore the latest job openings

Looking for more job opportunities? Look no further! Our platform offers a diverse array of job listings across various industries, from technology to healthcare, marketing to finance. Whether you're a seasoned professional or just starting your career journey, you'll find exciting opportunities that match your skills and interests. Explore our platform today and take the next step towards your dream job!

See All Jobs

Explore the latest blogs

Looking for insightful and engaging blogs packed with related information? Your search ends here! Dive into our collection of blogs covering a wide range of topics, from technology trends to lifestyle tips, finance advice to health hacks. Whether you're seeking expert advice, industry insights, or just some inspiration, our blog platform has something for everyone. Explore now and enrich your knowledge with our informative content!

See All Bogs

Enrolling in a course at 4Achievers will give you access to a community of 4,000+ other students.

Email

Our friendly team is here to help.
Info@4achievers.com

Phone

We assist You : Monday - Sunday (24*7)
+91-801080-5667
Register for Free Demo
By clicking the button above, you agree to our Terms of Use and Privacy Policy. We do not share this information.

Whatsapp

Call