Java
Java

 

Introduction

Validating email addresses is a common requirement in software development. Ensuring that a given email is formatted correctly helps to prevent errors during registration, communication, and data storage. An email address typically follows a specific structure, such as: local-part@domain, where the local part can include letters, numbers, and symbols, while the domain part consists of a domain name and a domain extension (e.g., “.com”).

In this example, we will write a Java program that validates whether a given string is a properly formatted email address. The program will use regular expressions to check if the input matches the required email format.

Objective

The objective of this program is to create a Java-based email validator that checks if a given string is in a valid email format. The program will use regular expressions to validate the structure of the email address.

Java Program Code

public class EmailValidator {

    // Method to validate the email address
    public static boolean isValidEmail(String email) {
        // Regular expression pattern for validating email addresses
        String emailPattern = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
        
        // Check if the email matches the regular expression pattern
        return email.matches(emailPattern);
    }

    public static void main(String[] args) {
        // Test cases for validating email addresses
        String[] testEmails = {
            "valid.email@example.com", 
            "invalid-email.com", 
            "another.valid_123@mail.co", 
            "invalid@domain..com"
        };

        // Validate each email
        for (String email : testEmails) {
            if (isValidEmail(email)) {
                System.out.println(email + " is a valid email address.");
            } else {
                System.out.println(email + " is an invalid email address.");
            }
        }
    }
}

Explanation of the Program Structure

The Java program consists of the following parts:

  • isValidEmail() method: This method takes a string input (the email) and checks whether it matches the regular expression pattern defined for valid email addresses. If it does, the method returns true, indicating the email is valid.
  • Regular expression (Regex): The regular expression used in the program defines the rules for a valid email. It checks for:
    • Alphanumeric characters and special characters (like dots, underscores, and hyphens) in the local part.
    • An ‘@’ symbol separating the local part and domain part.
    • Alphanumeric characters and hyphens in the domain part, followed by a valid domain extension.
  • main() method: The main method runs some test cases and validates each email address using the isValidEmail() method. It then prints whether the email is valid or invalid.

How to Run the Program

To run this Java program, follow these steps:

    1. Ensure you have Java installed on your machine. You can download it from the official website if necessary.
    2. Save the code above in a file named EmailValidator.java.
    3. Open a command prompt or terminal window, navigate to the folder where the file is saved, and compile the code using the command:
javac EmailValidator.java
    1. Once the program compiles successfully, run it using the following command:
java EmailValidator
  1. The program will output whether each email address in the test cases is valid or invalid.
© 2024 Learn Programming. All Rights Reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

78 thoughts on “Email Address Validator in Java”
  1. You can immerse yourself in a narrative that makes you scream with passion. This PDF edition is crafted for the modern reader. It offers a superior reading experience with adjustable settings on your device. Get your copy now and join the community of fans who love this book. https://youcanscreampdf.top/ Where To Download You Can Scream Pdf

  2. Discover the thrilling world of mystery and suspense by downloading the Anatomy of an Alibi PDF today. This digital edition offers a seamless reading experience on all your devices. immerse yourself in the gripping narrative that has captured the attention of readers everywhere. Get your copy now and start reading. https://anatomyofanalibipdf.top/ Anatomy Of An Alibi Novel Pdf

  3. What Size Screen Is Iphone 17 Air Iphone 17 Pro Price Germany 256gb Apple Iphone 17 Price Japan 2025 Iphone 17 Pro Price Iphone 17 Pro Price Rumors Apple Iphone 17 Pro Max Camera Zoom Iphone 17 Pro Max Specs Price Release Date 2025 When Is The Iphone 17 Air Coming Out? Iphone 17 Pro Vapor Chamber System Apple Apple Iphone 17 Air Price When Will Apple Release Iphone 17 2026 Iphone 17 Pro Max Specs Camera 2025 Review Iphone 17 Colors Pink Iphone 17 Release Date Price Uae Iphone Air Size Comparison Iphone 17 Price Europe Estimate Apple Iphone 17 Release Date Official Iphone Air Size Dimensions Iphone 16 Vs Iphone 17 Air Size Comparison How Much Is A New Iphone 17 Pro Max Iphone 17 Pro Price Rumors 256gb Pink Iphone 17 Pro Max Case Otterbox Clear Iphone 17 Pro Case Nearby Iphone 17 Specs Camera Differences Case For Orange Iphone 17 Pro Max Spy – Clear Iphone 17 Pro Max Case Apple Iphone 17 Pro Max Release Date Specs Iphone 17 Air Screen Size Iphone 17 Screen Size Iphone 17 Price Rumors Iphone 17 Price Expected Iphone 17 Air Price Dubai Uae Iphone 17 Release Date Announced September 2025 When Will Apple Release The Iphone 17 Iphone 17 Specs Rumor 2025 Apple Iphone 17 Price Expected Price When Will Iphone 17 Be Released Iphone 17 Release Best Iphone 17 Pro Max Case Amazon Iphone 17 Pro Price Usd Starting Price Best Leather Iphone 17 Pro Max Case How Much Storage Do I Need Iphone 17 Pro Max

  4. Iphone 17 Pro Max Price Uk Pounds Iphone 17 Release Date Features Specs Rumors Iphone 17 Pro Price Singapore Apple Store 2025 How Many Colors Does The Iphone 17 Pro Max Have New Apple Iphone 17 Colors Iphone 17 Air Specs Release Date Iphone Air Thickness At Camera Iphone 17 Pro Colors Rumored What Colors For The Iphone 17 Pro Max Iphone 17 Pro Vs Iphone Air Specs Difference What Apple Iphone Air Apple Airpods How Much Is A Iphone 17 Pro Max Worth Iphone 17 Air Price Iphone 17 Air Price Rumors Iphone 17 Pro Max Release Date Features 2025 How Big Is A Iphone 17 Pro Max Iphone 17 Release Date When Will Be Released Apple Iphone Air Reviews 2025 Apple Iphone 17 Pro Reviews Today When Iphone 17 Pro Max Release Date Apple Iphone 17 Launch Date News Iphone 17 Release Date Announcement Apple Apple Iphone 17 News Today Iphone 17 Price In Pakistan In Pkr Iphone Air Battery Capacity Comparison How Much Is Iphone 17 Pro Max 256gb Iphone 17 Price India Iphone Air Review Camera Samples Apple Iphone Air Reviews News Today How Much Is An Unlocked Iphone 17 Pro Max Apple Iphone 17 Pro Release Date Announcement Iphone 17 Pro Max Release Date 2025 Review When Is Apple Iphone 17 Launch Date 2025 How Much Price Of Iphone 17 Pro Max In India Iphone 17 Pro Max Precio PerГє Soles Beats Iphone 17 Pro Case With Magsafe Iphone Air Price Thailand Iphone 17 Price Estimate Turkey Iphone 17 Pro Release Date And Features

  5. Leather Iphone Air Case Iphone 17 Release Date Iphone 17 Coming Out Soon Iphone 17 Air Price Uk Iphone 17 Price In India And Pre-Order Details Iphone 17 Pro Max Specs Apple Official Site What Colors Do The Iphone Air Come In How Much Is An Iphone 17 Max Pro Differences Iphone 17 Pro Vs Pro Max Specs Buy Apple Iphone 17 Pro Max Unlocked Iphone 17 Pro Max Review Camera News Today Iphone Air Vs Iphone 17 Pro Max Specs Comparison Apple Iphone 17 News Today September 23 2025 Apple Iphone 17 Pro Max Release Date Features What Size Screen Is Iphone Air When Will Iphone 17 Come Out 2025 Apple Iphone 17 Specs 2025 How Much Is A 17 Pro Max Iphone When Is Iphone 17 Pro Coming Out? Iphone 17 Pro Price Germany Euro Apple De When Is Apple Releasing The Iphone 17 How Much Is The Iphone 17 Pro Max A Month Iphone 17 Pro Max Features Specs Announced Iphone 17 Air Release Date Rumors Iphone 17 Pro Price Uae Apple Dubai Apple Iphone 17 Pro Case 2025 Iphone Release Date Iphone 17 Release Date Iphone 17 Pro Case Clear With Design How Much Is The 17 Pro Max Iphone How Much Will Cost Iphone 17 Pro Max Iphone 17 Pro Max Release Date Price Rumors 2025 Iphone 17 Pro Max Specifications Apple 2025 Apple Iphone 17 Price Europe Official Apple Iphone 17 Reviews Today September 22 2025 Iphone 17 Pro Vs Pro Max Specs Size Battery When Will Iphone 17 Release Date Rumors Iphone 17 Specs Vs Iphone 16 Differences What Are The Dimensions Of Iphone 17 Pro Max Iphone Air Review Embargo

  6. Descubre la profunda libertad que ofrece la teoría de Let Them y cómo aplicarla en tu vida diaria para reducir el estrés. Si buscas el documento en español y en formato PDF completo, esta lectura te enseñará a soltar el control sobre las acciones de los demás y recuperar tu paz mental inmediatamente. https://lateorialetthem.top/ Dejar Que Las Cosas Fluyan

  7. Dive into the mischievous world of St. Petersburg and witness the events that shaped American fiction. From whitewashing fences to hunting for buried treasure, the plot is packed with excitement. We provide a dedicated space for readers to access this novel without barriers. If you prefer reading on a screen, our digital edition is perfect for you. Secure your copy of the Tom Sawyer PDF today and enjoy the flexibility of reading one of the world’s most famous books on your tablet, laptop, or e-reader without any hassle.

  8. Thresh and his mercy toward Katniss show that honor still exists even in the arena. These small moments of humanity define the moral core of the story. It is a complex narrative that refuses to see people as purely good or evil. To appreciate the character nuances, reading the novel is essential. Whether you choose a paperback or a The Hunger Games pdf, the important thing is to witness the choices these characters make under extreme pressure. https://thehungergamespdf.ru/ The Hunger Games 1 Pdf Free Download

  9. The “Sun Soul” Monk brings a video-game-like blaster feel to the martial artist. Xanathar’s Guide to Everything lets monks shoot radiant bolts of energy. Players looking for a PDF to see the range and damage of these bolts will appreciate our monk subclass tier list. We discuss how to kite enemies effectively using this unique fighting style. Channel the power of the sun and blast your foes from a distance with this radiant monk tradition. https://xanatharsguidetoeverythingpdf.ru/ Xanathar’s Guide To Everything Pdf Online Free

  10. As the dragons prepare for war, the sky fills with fire and lightning. The imagery in this book is cinematic and grand. The Onyx Storm epub brings these visuals to your mind’s eye. The relationships are complex and messy, just like real life. The ebook format is ideal for those who want to read privately. It is a story of heroism and sacrifice that inspires. https://onyxstormepub.ru/ Read Onyx Storm Online Pdf

  11. The frantic race to the Cornucopia to grab supplies is a masterclass in action writing. Every second counts, and one wrong move means death. The adrenaline rush of reading this scene is undeniable. Collins puts you right inside Katniss’s head. For action fans, this book delivers. If you want to read it on the go, searching for a The Hunger Games pdf is a great option to have the book accessible on your phone during your daily commute. https://thehungergamespdf.ru/ The Unofficial Hunger Games Wilderness Survival Guide Pdf Download

  12. The bread that Peeta tossed to a starving Katniss years ago is a recurring motif. It symbolizes hope, debt, and survival. The “Boy with the Bread” is a central figure in Katniss’s psyche. To understand the significance of this flashback, you must read the text. The movies touch on it, but the book explains it fully. A The Hunger Games pdf is a great resource for readers who want to trace the symbolism of bread throughout the novel. https://thehungergamespdf.ru/ The Hunger Games Catching Fire Book Pdf Free Download

  13. There is no safety in the skies anymore. The aerial combat scenes are written with a kinetic energy that makes your heart race. The Onyx Storm epub captures this energy perfectly on the digital page. Violet and Xaden must navigate trust issues while fighting a war they are losing. It is a compelling narrative of love and war. The ebook is the perfect solution for readers who want to save shelf space but still experience the epic scale of the story. https://onyxstormepub.ru/ Onyx Storm Chapter 49 Pdf

  14. The struggle against the venin is a fight for the soul of the world. The characters must give everything they have. The Onyx Storm epub is the record of their sacrifice. The pacing is perfect, keeping you on the edge of your seat. The digital copy is a great way to support the author. It is a story of hope in the darkness.

  15. The reaping scene is one of the most memorable openings in young adult literature. The sheer terror of Prim’s name being called and Katniss’s immediate reaction defines the bond between the sisters. It is the heart of the story. If you haven’t read this scene in the original text, you are missing out on the raw, visceral power of Collins’ prose. Accessing a The Hunger Games pdf allows you to read this pivotal moment exactly as it was written, capturing the desperation of District 12.

  16. Xanathar’s Guide to Everything is a testament to the longevity of 5th Edition. It aggregates the best content from “Unearthed Arcana” playtests. If you are looking for a PDF comparison of the playtest vs. published versions, our retrospective articles are fascinating. We show how classes evolved from draft to final print. Understand the design history of your favorite classes by exploring the development of this book.

  17. Katniss’s father died in a mining accident, a tragedy that haunts her and shapes her protective nature toward Prim. The flashbacks to her father provide emotional context for her skills and her stoicism. The backstory is woven seamlessly into the main plot. To get the full picture of Katniss’s motivations, you need to read the novel. Digital formats are excellent for this; a simple search for a PDF version allows you to start the journey into her past immediately.

  18. Every choice has a consequence, and in this book, the bill comes due. The narrative explores the trauma of war and the resilience of the human spirit. If you are looking for the Onyx Storm epub, you are preparing for a deep emotional dive. The dragons are not just beasts; they are partners with their own agendas. The ebook format is perfect for highlighting the foreshadowing that you might have missed on the first read.

  19. Приветствую! В этой статье я расскажу — экономия на кровельных работах. Дело в том, что: демонтаж не всегда обязателен. Хочешь сэкономить — могу рекомендовать: [url=https://montazh-membrannoj-krovli-spb.ru]установка мембранной кровли[/url]. Как это работает: проверяют основание, если прочное — укладывают мембрану поверх. В общем основание ровное — так вот работы быстрее. На первом этапе разделительный геотекстиль. Что в итоге: это отличные параметры — без лишних расходов.

  20. Здравствуйте дорогие друзья! В этой статье я расскажу про крышу с террасой. Суть здесь в чем: крыша с нагрузкой — требует особой гидроизоляции. Нет желания рисковать — могу рекомендовать: [url=https://montazh-membrannoj-krovli-spb.ru]монтаж мембранной кровли[/url]. В большинстве случаев под террасную доску кладут ПВХ мембрану. Например планируешь зону отдыха — гидроизоляция должна быть идеальной. На первом этапе армированную мембрану, поверх — защитные слои. Что в итоге: удаётся достигать классных результатов — кровля которая работает.

Leave a Reply to anatomyofanalibipdPrins Cancel reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)