Email validation using Java Regex

📧 Email Validation Using Java Regular Expressions (Regex)

Topic: Java Regex Pattern for Email Validation


🧩 Overview

In this post, we’ll explore how to validate email addresses in Java using Regular Expressions (Regex).
The regex pattern enforces strict rules for valid email structures — ensuring only properly formatted email IDs are accepted.


🧠 Regex Pattern

^[A-Z0-9._]+@[A-Z0-9-]+\.[A-Z]{2,6}$

🔍 Pattern Breakdown

SymbolMeaningDescription
^Start of the patternEnsures the match begins from the start of the string
[A-Z0-9._]+First partThe local part (before @) must contain uppercase letters (A-Z), digits (0-9), and . or _
@SeparatorSeparates the username and domain parts
[A-Z0-9-]+Second partThe domain name (after @) must contain letters, digits, or hyphens (-)
\.[A-Z]{2,6}Third partThe domain extension must begin with a . followed by 2 to 6 letters (A-Z)
$End of the patternEnsures the match ends at the end of the string

🧩 In simple terms:

The email must look like USERNAME@DOMAIN.TLD,
where:

  • Username = letters, numbers, dots, or underscores

  • Domain = letters or numbers

  • TLD (Top-Level Domain) = 2–6 letters only (e.g., .com, .org, .co.in)


🧰 Java Implementation

Here’s the complete Java example to validate emails using this regex pattern.

package com.vinod.test; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author vinod.kumaran * * Simple email validator using Java Regular Expressions. * * Pattern: ^[A-Z0-9._]+@[A-Z0-9-]+\.[A-Z]{2,6}$ * * ^ = Start of pattern * [A-Z0-9._] = First part: allowed characters before '@' * @[A-Z0-9-] = Second part: allowed characters after '@' * \.[A-Z]{2,6} = Third part: domain extension with 2–6 letters * $ = End of pattern */ public class EmailValidator { // Compile the regex pattern (case-insensitive) public static final Pattern EMAIL_REGEX = Pattern.compile("^[A-Z0-9._]+@[A-Z0-9-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE); public static void main(String[] args) { // Valid email System.out.println(validate("kkvinod@pretechsol.com")); // Invalid email: first part contains '%' System.out.println(validate("kkvin%od@pretechsol.com")); // Invalid email: second part contains '_' System.out.println(validate("kkvinod@prete_chsol.com")); // Invalid email: domain extension > 6 characters System.out.println(validate("kkvinod@pretechsol.comcomcom")); } // Validation method public static boolean validate(String emailAddress) { Matcher matcher = EMAIL_REGEX.matcher(emailAddress); return matcher.find(); } }

🧪 Sample Output

true false false false

✅ Explanation of Results

EmailExpected ResultReason
kkvinod@pretechsol.com✅ trueValid format
kkvin%od@pretechsol.com❌ false% not allowed before @
kkvinod@prete_chsol.com❌ false_ not allowed in domain name
kkvinod@pretechsol.comcomcom❌ falseTLD (extension) exceeds 6 letters 


How to get current GMT and Current Local time in java?

Example

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class GMTExample {
public static void main(String[] args) throws ParseException {

SimpleDateFormat gmtDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss.SSS Z");
gmtDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
String currentGMTDateString = gmtDateFormat.format(new Date());

SimpleDateFormat gmtDateFormat1 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss.SSS Z");
String currentDateString = gmtDateFormat1.format(new Date());

System.out.println("Current GMT=" + currentGMTDateString
+ " Current Local" + currentDateString);

}

}

Output

Current GMT=04-06-2014 07:18:25.939 +0000 Current Local04-06-2014 12:48:25.940 +0530
 

Spring Asynchronous Execution Example

Some situations we required asynchronous executions in our applications, for example sending an email, file transfer these kind of scenarios we no need to wait until all the process are completed. In order to achieve this spring provides API to execute methods asynchronously .
In this example we will use @Async annotations to execute method asynchronously.

1. Create a Component class

package com.vinod.test;

import java.util.concurrent.TimeUnit;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class SendEmail {
@Async
public void sendEmail() {
System.out.println("Send email started::::");
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Send email completed::::");

}
}

2. Create a Service class

package com.vinod.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class EmailService {
@Autowired
private SendEmail sendEmail;

public void sendEmailviaService() {
sendEmail.sendEmail();
}
}

3.Spring configuration xml

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd">

4.Create a Main class

package com.vinod.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AsynchTest {

public static void main(String[] args) {

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"springcontext.xml");
System.out.println("Calling send mail bean");
EmailService es = ctx.getBean(EmailService.class);
es.sendEmailviaService();
System.out.println("Called send mail bean and request for send email");

}

}

4.Output

Calling send mail beanCalled send mail bean and request for send emailSend email started::::Send email completed::::

Spring NamedParameterJdbcTemplate Example

NamedParameterJdbcTemplate has basic set of JDBC operations and allowing the use of named parameters rather than traditional '?' placeholders.
We have to set all params in a map and pass the param map while executing the query.

Spring configuration

 	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName"  value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3306/springschema"></property>
		<property name="username" value="root"></property>
		<property name="password" value="root"></property>
	</bean>
	
  	<bean id="namdjdbctemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
     <constructor-arg>
        <ref bean="dataSource"/>
     </constructor-arg>    
     </bean>

Main class

package com.pretech.jdbc;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
public class NamedParameterJdbcTemplateExample {
	public static void main(String args[]) {
		ApplicationContext appContext = new ClassPathXmlApplicationContext(
				"SpringConfig.xml");
		NamedParameterJdbcTemplate namdjdbctemplate = (NamedParameterJdbcTemplate) appContext
				.getBean("namdjdbctemplate");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("name", "Shiva");
		paramMap.put("standard", "2st standard");
		List<Map<String, Object>> students = namdjdbctemplate
				.queryForList(
						"select * from student where name=:name and standard=:standard",
						paramMap);
		System.out.println(students);
	}
}

Spring BeanPropertyRowMapper Example

BeanPropertyRowMapper implementation that converts a row into a new instance of the specified mapped target class. The mapped target class must be a top-level class and it must have a default or no-arg constructor.

Spring configuration

	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName"  value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3306/springschema"></property>
		<property name="username" value="root"></property>
		<property name="password" value="root"></property>
	</bean>
 	<bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
     <constructor-arg>
        <ref bean="dataSource"/>
     </constructor-arg>    
     </bean>

Main class


ApplicationContext appContext = new ClassPathXmlApplicationContext(
"SpringConfig.xml");
JdbcTemplate template = (JdbcTemplate) appContext
.getBean("jdbctemplate");
Student st = template.queryForObject(
"select * from student where name=?",
new BeanPropertyRowMapper<Student>(Student.class), "Shiva");
System.out.println(st);

Chain of responsibility design pattern example

📦 Chain of Responsibility Pattern in Java — Step-by-Step Guide

The Chain of Responsibility (CoR) is a behavioral design pattern that allows a request to pass through a chain of handlers.
Each handler decides either to process the request or pass it to the next handler in the chain.

This pattern helps in decoupling senders and receivers — the sender doesn’t need to know which handler will eventually process the request.


🧠 Concept

  • A chain is a series of objects (handlers) connected together.

  • Each handler knows only about the next handler in the chain.

  • When a request comes in:

    • The current handler checks if it can handle it.

    • If yes → it processes it.

    • If not → it forwards it to the next handler in the chain.


🚚 Real-World Analogy — Parcel Delivery Service

Imagine a parcel service with branches in:

Bangalore → Bombay → Delhi

When a parcel is sent:

  • A Bangalore branch first receives it.

  • If the parcel is for Bombay, Bangalore forwards it to Bombay.

  • If it’s for Delhi, it goes from Bangalore → Bombay → Delhi.

Each branch only handles parcels for its location, and passes others onward.
That’s exactly how the Chain of Responsibility Pattern works!


⚙️ Implementation — Step by Step


🧩 Step 1: Create the Chain Interface

This defines the contract for all handlers.

package com.vinod.design.chain; public interface Chain { // Sets the next handler in the chain void setNextDestination(Chain nextDestination); // Processes the incoming parcel void processParcel(Parcel parcel); }

🧩 Step 2: Create Handler — Bangalore

package com.vinod.design.chain; public class Bangalore implements Chain { private Chain nextDestination; @Override public void setNextDestination(Chain nextDest) { this.nextDestination = nextDest; } @Override public void processParcel(Parcel parcel) { if (parcel.getDestination().equalsIgnoreCase("Bangalore")) { System.out.println("Processing parcel in Bangalore: " + parcel); } else { // Forward to next branch if not for Bangalore if (nextDestination != null) { nextDestination.processParcel(parcel); } } } }

🧩 Step 3: Create Handler — Bombay

package com.vinod.design.chain; public class Bombay implements Chain { private Chain nextDestination; @Override public void setNextDestination(Chain nextDest) { this.nextDestination = nextDest; } @Override public void processParcel(Parcel parcel) { if (parcel.getDestination().equalsIgnoreCase("Bombay")) { System.out.println("Processing parcel in Bombay: " + parcel); } else if (nextDestination != null) { nextDestination.processParcel(parcel); } } }

🧩 Step 4: Create Handler — Delhi

package com.vinod.design.chain; public class Delhi implements Chain { private Chain nextDestination; @Override public void setNextDestination(Chain nextDest) { this.nextDestination = nextDest; } @Override public void processParcel(Parcel parcel) { if (parcel.getDestination().equalsIgnoreCase("Delhi")) { System.out.println("Processing parcel in Delhi: " + parcel); } else { System.out.println("No branch found for destination: " + parcel.getDestination()); } } }

🧩 Step 5: Create the Parcel Class

package com.vinod.design.chain; public class Parcel { private String source; private String destination; private String details; public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getDestination() { return destination; } public void setDestination(String destination) { this.destination = destination; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } @Override public String toString() { return "Parcel [source=" + source + ", destination=" + destination + ", details=" + details + "]"; } }

🧩 Step 6: Set Up the Chain (Main Class)

package com.vinod.design.chain; public class ParcelService { public static void main(String[] args) { // Create handler objects Chain bangalore = new Bangalore(); Chain bombay = new Bombay(); Chain delhi = new Delhi(); // Build the chain: Bangalore → Bombay → Delhi bangalore.setNextDestination(bombay); bombay.setNextDestination(delhi); // Create test parcels Parcel parcel1 = new Parcel(); parcel1.setDestination("Bombay"); parcel1.setDetails("Parcel to Bombay"); Parcel parcel2 = new Parcel(); parcel2.setDestination("Delhi"); parcel2.setDetails("Parcel to Delhi"); // Send parcels through the chain bangalore.processParcel(parcel1); bangalore.processParcel(parcel2); } }

🧾 Output

Processing parcel in Bombay: Parcel [source=null, destination=Bombay, details=Parcel to Bombay] Processing parcel in Delhi: Parcel [source=null, destination=Delhi, details=Parcel to Delhi]

🧠 How It Works (Step-by-Step Flow)

StepActionExplanation
1️⃣ParcelService sets up the chainBangalore → Bombay → Delhi
2️⃣A request (parcel) starts at BangaloreBangalore checks if destination matches
3️⃣If not, forwards to next handlerThe parcel moves along the chain
4️⃣Handler matches parcel destinationProcesses it and stops the chain
5️⃣If no handler matchesRequest is ignored or logged

🔍 Benefits of Chain of Responsibility

  • Loose coupling — Sender doesn’t need to know which handler will process the request

  • Extensibility — Add new handlers easily without changing existing code

  • Flexible processing — Handlers can process partially or pass along

  • Separation of concerns — Each handler focuses on one specific job


⚠️ Things to Watch Out For

  • 🚫 The chain must be properly linked (missing setNextDestination() can break flow).

  • ⚙️ Handlers should ideally stop propagation once a request is processed.

  • 🧩 Avoid creating circular chains — can cause infinite loops.


🧩 UML-Like Text Diagram

+-------------+ +------------+ +-----------+ Request --> | Bangalore | --> | Bombay | --> | Delhi | +-------------+ +------------+ +-----------+ | | | | | | [Can process?] [Can process?] [Can process?] | | | v v v [Yes → Handle] [Yes → Handle] [Yes → Handle] | | | +------ No ---------+------ No ---------+

💬 Real-World Applications

Use CaseExample
Web request filteringServlet Filters in Java EE (FilterChain)
Logging frameworkDifferent log handlers (Console, File, DB)
Event handling systemsUI event bubbling or middleware
Authorization pipelinesRequest passes through validators or access checkers

java.util.concurrent.TimeUnit Example

A TimeUnit represents time durations at a given unit of granularity and provides utility methods to convert across units, and to perform timing and delay operations in these units. Here is one example to do the following

Days to Hours

Hours to Minutes

Minutes to Seconds

Seconds to Milliseconds

Milliseconds to Micro seconds

Example

package com.pretech;
import java.util.concurrent.TimeUnit;
public class TimeUtilTest {
	public static void main(String[] args) {
		try {
			// Days to hours
			System.out.println("Total Hours" + TimeUnit.DAYS.toHours(1));
			// Hours to minutes
			System.out.println("Total Minutes" + TimeUnit.HOURS.toMinutes(24));
			// Minutes to Seconds
			System.out.println("Total Seconds"
					+ TimeUnit.MINUTES.toSeconds(1440));
			// Seconds to Mill seconds
			System.out.println("Total Milli seconds"
					+ TimeUnit.SECONDS.toMillis(86400));
			// Milli seconds to micro seconds
			System.out.println("Total Micro seconds "
					+ TimeUnit.MILLISECONDS.toMicros(86400000));
			// TimeUnit to sleep
			System.out.println("Before sleep ");
			TimeUnit.SECONDS.sleep(5);
			System.out.println("After sleep ");
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

Output



Total Hours24
Total Minutes1440
Total Seconds86400
Total Milli seconds86400000
Total Micro seconds 86400000000
Before sleep
After sleep


Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts