Cash Retraction ends in India

October 10, 2012 Leave a comment

India’s ATM users may need to pay closer attention to their ATM transactions from now on. In response to a National Payments Corporation of India’s request, the Reserve Bank of India has told banks to shut down cash-retraction facilities at their ATMs.

The Retraction facility means that cash not picked up by the customer after 10-15 seconds was sucked back into the ATM and the customers account was credited again.

The Times of India reported that the NPC request came in the wake of a major ATM swindle. In the scheme, an individual would make a withdrawal, leaving a few notes for the cash machine to retract. Then the customer would report to the bank that the ATM had taken back the entire amount. Using this ploy, a gang of at least six men carried out a fraud operation that netted more than $350,000 in ill-gotten funds.

Banks have let customers know that henceforth, their money will not be retracted into the ATM if they forget to retrieve it. Instead, it will remain in the open for the next ATM user potentially to collect. Despite this, Indian banks told the BBC they believe the new policy will serve their customers’ best interests.

Categories: Uncategorized

Java 7 Awesome Aspect-Automatic Resource Management

December 19, 2010 7 comments


In my previous article,” Java 7 Awesome Features” I had missed one of the greatest aspect of Java 7.That is nothing but “Automatic Resource Management”. This article deals with the same.

Managing Resource is one of the keen thing in development. Because if we don’t manage the resource effectively it will cause lot of issues like PermGen Space Error, TooManyConnections Error etc.

For avoid those problems Java 7 introduce the great aspect “Automatic Resource Management”. By this feature java can automatically manage the resources effectively. So java frees the developer from lots of overhead. Lets have a prolix look on this.


try(Resource 1;Resource 2;Resource 3….)


//block of statements


catch(Exception e)


//block of statements


Here is simple code snippet which shows you the typical try-catch-finally block. In the code we create the jdbc connection for access the data from database.

Connection connection = null;

Statement statement = null;



connection =    DriverManager.getConnection(“databaseurl”,”username(opt)”,”password(opt)”);

statement = connection.createStatemnet();

boolean executionStatus= statement.execute(“query”);


catch(Exception e)


//Block of code for handle the exception










catch(Exception e)


//block of statements for handle exceptions.



In the above snippet, suppose we forget to close the statement and connection, what happened? May be after some operations (which also open the connection) “Too Many connection error” will occurred.

But java 7 keeps us in safe zone from those kinds of errors by mange the resource automatically. In java 7 we can write the above snippet like this,

Connection connection = null;

Statement statement = null;

try(connection =    DriverManager.getConnection(“databaseurl”,”username(opt)”,”password(opt)”);

statement = connection.createStatemnet())


boolean executionStatus= statement.execute(“query”);


catch(Exception e)


//block of statements for handles the exceptions


In the above snippet, there are no overheads like close the connections and statements properly. Java 7 can manage those things automatically for us.


Java 7 mange the resources which are sub interfaces and implementing classes of AutoCloseable.So we can pass the resources which are extends or implements the interface AutoCloseable.

That’s all folks, I think this article makes you bit more knowledgeable about java 7 awesome aspect “Automatic resource Management”, If you feel the same, please leave your footprints(comments) here. Joyous coding day…..

Simple JPA Application with Hibernate

December 5, 2010 6 comments

Now I am the newbie to JPA.I learn some thing about JPA. So I wanna share that with you all. So only I am here to do the same. This article deals with how to develop the simple JPA application using hibernate vendor support. Let’s get into that.


  • JDK 1.5 and above
  • Your favourite IDE.
  • HibernateJPA Library.
  • Mysqljdbc.jar

After create the Project we have to add above required libraries and jars into our library folder.

  • Table Creation.
  • Creation of  Persistence.xml
  • Creation of  Entity class
  • Creation of  Entity Manager class
  • Creation of  Test class.
1. Table Creation:

Create table named “Department”, which contains two columns “departmentId” and “departmentName” by executing the following script,

CREATE TABLE `Department` (
`departmentId` int(10) NOT NULL,
`departmentName` varchar(10) default NULL,
PRIMARY KEY  (`departmentId`))
2. Persistence.xml:

This persistence.xml file is act like configuration file for JPA.

<?xml version="1.0" encoding="UTF-8"?>

<persistence version="1.0" xmlns="" xmlns:xsi="" xsi:schemaLocation="">

<persistence-unit name="JPASamplePU" transaction-type="RESOURCE_LOCAL">




<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>

<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/jpadb"/>

<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>

<property name="" value="update"/>

<property name="hibernate.connection.username" value="root"/>

<property name="hibernate.connection.password" value="root"/>




Persistence-unit: used to represent the persistence unit.

Transaction-type: type of transaction

There are two type of transactions are avail.

Resource-local: Transactions have to be managed by developer locally.

JTA: Transactions are managed by application server.

Class: Represent the entity. used to perform the action in the database when the SessionFactory is created.

All the others are basic things.

3. Creation of Entity Class:

Entity class is used to represent the table in class format.

package com.bsj.entities;


import javax.persistence.Basic;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.NamedQueries;

import javax.persistence.NamedQuery;

import javax.persistence.Table;

@Entity//Represent the class entity class

@Table(name = "department")//Represents the table name



@NamedQuery(name = "Department.findAll", query = "SELECT d FROM Department d"), @NamedQuery(name = "Department.findByDepartmentId", query = "SELECT d FROM Department d WHERE d.departmentId = :departmentId"), @NamedQuery(name = "Department.findByDepartmentName", query = "SELECT d FROM Department d WHERE d.departmentName = :departmentName")


public class Department implements Serializable


private static final long serialVersionUID = 1L;


@Basic(optional = false)

@Column(name = "departmentId")

private Integer departmentId;

@Column(name = "departmentName")

private String departmentName;

public Department()



public Department(Integer departmentId)


this.departmentId = departmentId;


public Department(Integer departmentId, String DepartmentName)


this.departmentId = departmentId;

this.departmentName = departmentName;


//Getter setter method of variables

Annotation used in Entity Class:

@Entity – used to represent the class as Entity class. By using this annotation only we can make simple POJO class as Entity class.

@Table – used Represent the table name which the entity class points out.

@Id – Used to represent the primary key field.Only one primary key is allowed in the entity class.

@Column – used to represent the column details such as name, nullable etc.


There are two types of query is avail.
1. Static (Named) Queries: defined statically with the help of annotation (or XML) before the entity class.

A name of the Query  is usually given to the query definition so that other components in the same persistent unit can refer the query by the name.
2. Dynamic queries: are nothing but whose query strings are provided at run-time

4.Creation of Entity Manager Class:

The constructor has the Entity Manager Factory as argument and it allows us to create the Entity Manager.

The Entity Manager class is transaction scoped bean so we have to begin transaction before each action and commit transaction after each operation.

package com.bsj.entities;

import java.util.List;

import javax.persistence.EntityManager;

import javax.persistence.EntityManagerFactory;

import javax.persistence.Query;

public class DepartmentManager


private EntityManager em;

public DepartmentManager(EntityManagerFactory emf)


em = emf.createEntityManager();



* Method used to create department.

* @param department


public void createDepartment(Department department)


//Begin Transaction

System.out.println("Creation : ");


em.persist(department); //Persist entity in persistence context.

//Commit Transaction


System.out.println("Department Created SuccessFully");



* Method used to search department Name by id.

* @param id

* @return


public Department searchById(Integer id)


//Method used to find data

return em.find(Department.class, id);


public void updateUser(Department department)


System.out.println("Update : ");




System.out.println("Update successfully.");


public void removeUser(Department department)





System.out.println("Remove department successfully");


public List getAll()


Query query = em.createQuery("select a from Department a");

List list = query.getResultList();

return list;


public void close()





Methods used in Entity Manager:

Persist(entityObject)-Used to persist entity in the persistence context.
Find (Entityclass,value) – Find the datas regarding the input passed as argument.
merge(entityobject) : Update the database regarding to the passing details.
5.Creation of Test class:

We can get the entity manager factory by the  createEntityManagerFactory method of the class Persistence,
createEntityManagerFactory(persistence unit name);
This method has the persistence unit name as argument.
Call the entity manager methods by using the reference of entity manager.

package com.bsj.tester;

import com.bsj.entities.Department;

import com.bsj.entities.DepartmentManager;

import java.util.Iterator;

import java.util.List;

import javax.persistence.EntityManagerFactory;

import javax.persistence.Persistence;

public class TestJPA


private DepartmentManager departmentManager;

private EntityManagerFactory emf;


* Method to setup basic thing need for implementation like entiny manager

* factory,entity manager etc.

* @throws Exception


protected void setUp() throws Exception



* Create the entity manager factory with the help of persistence.

* @Param NameofPersistence unit form Persistence.xml


emf = Persistence.createEntityManagerFactory("JPASamplePU");


* create Departmanager

* @Param Entity Manager Factory


departmentManager = new DepartmentManager(emf);



* Method to close entity manager and entity manager factory.

* (i.e) Remove from the persistence context

* @throws Exception


protected void close() throws Exception






* Method for test the application.


public void test()



* Create the Entity by using constructor of Entity.


Department department = new Department(10, "Chemical");


System.out.println("Before Update :");

Department searchDepartment = departmentManager.searchById(50);

System.out.println("Department Name of Id 50 : " + searchDepartment.getDepartmentName());



department = departmentManager.searchById(50);

System.out.println("After update.");

System.out.println("Department Name of Id 50 : " + searchDepartment.getDepartmentName());

List list = departmentManager.getAll();

System.out.println("Number of Departments: " + list.size());

System.out.println("List of Departments : ");

Iterator iterator = list.iterator();

while (iterator.hasNext())


Department department3 = (Department);

System.out.println("Id : " + department3.getDepartmentId());

System.out.println("Name : " + department3.getDepartmentName());



public static void main(String args[])


System.out.println("Inside TestJPA main");

TestJPA testJPA = new TestJPA();







catch (Exception e)




System.out.println("End of TestJPA main");



Thats all folks.If you found this article was helpful to you,don’t forget to leave your valuable comments here.Happy coding….

Spring’s Before and After Advice

November 30, 2010 1 comment


This article makes you bit more knowledgeable in one of the spring’s Aspect Oriented Programming concept advice. In this article we see the simple example for the advice aspect of Spring AOP framework. Before that we have a brief look at some AOP concepts that enrich your understanding.


It’s just like a class in OOPs concepts.

Joint point:

A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution.

In real world example, it’s just like a menu items in the menu card.


Combination of joinpoints which are chosen for execution.

In real world example, it’s just like a meal which is combination of items chosen from menu card.


The class which is going to be advised.


Actions taken by an aspect at a particular joinpoint.The advices are classified into three major groups.

  • Before advice
  • After advice
  • Around advice
Before advice:

Before advice is executed before the execution of methods in the target.

After advice:

After advice is executed after the execution of methods in target. Normally before advice and after advices are used to logging feature. It’s classified into three subgroups.


  • After returning advice
  • After throwing advice
  • After (finally) advice
Around Advice:

Around advice is executed before and after execution. Its the powerful form of advice. We have a explanation in our next meet.

It is also responsible for choosing whether to proceed to the join point or to block the advised method execution by returning its own return value or throwing an exception. All other advices cannot block the execution flow.

Lets see the example for before and after returning advices.


JDK 1.5 and Above

Your favourite IDE

spring latest  jars



An ordinary interface.

public interface SpringAopInterface
public void sayHello(String name);

An ordinary implementation class of an interface SpringAOPInterface

public class SpringAopImpl implements SpringAopInterface{
 public void sayHello(String name)


System.out.println("Hello ,"+name);


A class which represent the before advise.By implementing the MethodBeforeAdvice interface make the POJO class as a before advisor class.

The action which is wants to perform in the before advise class is define in the override method before().

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

public class BeforeAdvisor implements MethodBeforeAdvice

 public void before(Method method, Object[] os, Object o) throws Throwable


System.out.println("Before Advisor called");


A class which represent the after advise.Like a before advisor  class by implementing the AfterReturningAdvice interface make the POJO class as a after advisor class.

The action which is wants to perform in the after advise class is define in the override afterReturning().

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;
public class AfterAdvisor implements AfterReturningAdvice

 public void afterReturning(Object o, Method method, Object[] os, Object o1) throws Throwable


System.out.println("After advisor called");


IOC Container Configuration:

This is the context configuration file of the application.Its have to be stored in META-INF folder in src package.

Target: represents the bean class which is going to be advised by the advisors.

Interceptor Names: Represent the advisor classes list.

advice: Represent the advisor class and the pattern of the bean classes which are going to be advised.


&lt;beans xmlns=""

xmlns:xsi="" xmlns:p=""
xmlns:aop="" xmlns:tx=""

&lt;!-- Bean configuration --&gt;
&lt;bean id="businesslogicbean"&gt;
&lt;property name="proxyInterfaces"&gt;

&lt;!--Target : Reprsent the bean class which is going to be advised--&gt;
&lt;property name="target" ref "beanTarget" /&gt;
&lt;!--Denotes the list of advices--&gt;
&lt;property name="interceptorNames"&gt;

&lt;!-- Bean Classes --&gt;
&lt;bean id="beanTarget" class=""/&gt;

&lt;!-- Advisor pointcut definition for before advice --&gt;
&lt;bean id="beforeAdvisor" class=""&gt;
 &lt;!--Property which represent the advice--&gt;
 &lt;property name="advice" ref="beforeAdvice"/&gt;

 &lt;!--Pattern fot the class which is going to be advised.
 Here any kind of classes are going to be advised.--&gt;
 &lt;property name="pattern"&gt;
&lt;!-- Advisor pointcut definition for before advice --&gt;
&lt;bean id="afterAdvisor" class=""&gt;
 &lt;property name="advice" ref="afterAdvice"/&gt;
 &lt;property name="pattern"&gt;

  &lt;!-- Advice classes --&gt;
&lt;bean id="beforeAdvice"
&lt;bean id="afterAdvice"

By passing the path of the applicationcontext file to theclass ClassPathXmlApplicationContext,  we can get the instance of Application context.

By the method of getBean() of ApplicationContext,we can retrieve the instance of the bean’s interface.We have to pass the id of the bean as the argument to the method getBean().By using the instance of the bean’s interface we can call the method of the interface which is defined in the bean class.

import org.springframework.context.ApplicationContext;

public class Tester

 public static void main(String[] args)


// Read the configuration file

ApplicationContext ctx = new ClassPathXmlApplicationContext("META-INF/applicationContext.xml");

 // Instantiate an object

SpringAopInterface springAopInterface = &nbsp;(SpringAopInterface) ctx.getBean("businesslogicbean");
 // Execute the public method of the bean



Thats all folks,I think its give some idea about the spring AOP’s advice aspect.If you feel this article is helpful to you,Don’t forget to leave your footprints(comments) here.

Spring Bean Automatic Detection using context:component-scan element

November 27, 2010 8 comments


In Spring 3.0, the IOC container can be configured in two ways, They are

  • XML Based Configuration
  • Java Based Configuration.

If we go for XML Based Configuration, the sizes of the xml configuration file is so excess for large applications. But we can reduce the size of the xml configuration file by using Spring’s one of the greatest aspect, automatic detection of Spring beans(classes).

This can be achieved by using context:component-scan element in xml configuration file and @component annotation in bean classes. This article deals with spring bean automatic detection using context:component-scan element. Let’s get over that.


JDK 1.5 and Above

Your favourite IDE

spring latest  jars



Creation of component using @Component annotation:

By using @component annotation,we can make the bean class as component.By the same way,the below operator bean class make it as component.

package com.bsj.componentscan;

import org.springframework.stereotype.Component;

 * @author Jhothi
public class Operator
 public int add(int i,int j)
 return i+j;
 public int subtract(int i,int j)
 return i-j;

 public int multiply(int i,int j)
 return i*j;

 public int divide(int i,int j)
 return i/j;

By using auto wired feature of spring we can represent our Operator class as dependency of Calculator class.

By using @Autowired annotation we can make the dependency Operator class as Auto wired one.

package com.bsj.componentscan;

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

 * @author Jhothi
public class Calculator
 private Operator operator;
 public void calculation(int i, int j)
 System.out.println("i+j : " + operator.add(i, j));
 System.out.println("i-j : " + operator.subtract(i, j));
 System.out.println("i*j : " + operator.multiply(i, j));
 System.out.println("i/j : " + operator.divide(i, j));

 * @param operator the operator to set
 public void setOperator(Operator operator)
 this.operator = operator;

The component annotation has the name of the component with in the bracket with quotes. The component name is used for detect the bean by the method getBean() of ApplicationContext.For ex,In @Component (“calculator”), calculator is the name of the component.

Container Configuration:

The IOC container configuration xml file is shown below,The container has the <context:component-scan> element and <context:annotation-config/>

<context:annotation-config/> used to intimate the beans of this IOC container are annotation supported.

By pass the base path of the beans as the value of the base-package attribute of context:component-scan element, we can detect the beans and registering their bean definitions automatically without lots of overhead.

The value of base-package attribute is fully qualified package name of the bean classes. We can pass more than one package names by comma separated like the below one.

<context:component-scan base-package="package1, package2"/>


<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns=""
 xmlns:xsi="" xmlns:p=""
 xmlns:aop="" xmlns:tx=""

 <context:component-scan base-package="com.bsj.componentscan"/>

Finally the @component is one of the stereotype annotations. Some other stereotype annotations are avail. They are @Repository, @Service, and @Controller. The next article deals the stereo type annotaions.Before that if you feel this article is helpful to you doesn’t forget to leave your valuable comments.

Java 7 awesome Features

November 15, 2010 38 comments

Whenever, I am crawl through the web i notice the word java 7.Then,I really found out java 7 is today’s hot topic. So i googled it for know something about java 7.At that time i found out some thing interested and useful features in java 7.Thats push me here to share something to you all folks.Lets get into the topic.

The project name of java 7 development is Project Coin.I have listed some of the features below.

Null-safe Method invocation:

This is the greatest feature which is going to added in Java 7.NullPoniterException is one of the most common exception encountered in Java programming.

When I searched “NullPointerException” in Google, it gave about 5,570,000 results! This proves how pervasive the exception is and how much effort a developer has to put in writing java code free from null pointer exception.

Suppose if java has a feature to keep us in safe zone from null pointer exception, how is it? It happens.

Suppose we have a method to fetch postal code of a person’s address:

public String getPostcode(Person person)
if (person != null)
Address address = person.getAddress();
if (address != null)
return address.getPostcode();
return null;

Now check the above syntax. We have done lots of if (null! = object) checks to avoid NullPointerException.

public String getPostcode(Person person)
return person?.getAddress()?.getPostcode();

Null-ignore invocation is concerned with dealing with possible null values in calling one or especially a chain of methods. Check the syntax?. while calling method on an object. This is Null-safe operator in Java 7. Thus, you can avoid lots of if (null!= object) checks in Java 7.

Strings in Switch Statements:

Whenever i am working with switch-case i felt, if the case allowed the string as a case variable we feel so comfort on that. Because the switch case allows only the primitive data types as variable such as integer, char etc.

Whenever i working with the methods that returns status of the operations like succesful, failed like that. At that time i need to convert that in to constants. Then only i can move on switch statements.

But java 7 offers the Strings as case variables in Switch Statements, So we are free from the conversion process.

Multi-Exception Catch:

Another awesome update is Multi-Exception Catch, that means a single catch can handle multiple exceptions. The syntax is

block of statments
block of statements.

It save lot of spaces in the code.

Bracket Notation for Collections:

This feature refers to the ability to reference a particular item in a Collection with square brackets similar to how Arrays are accessed. Collection is one of the key concepts in java.

But when i was a student, I feel so discomfort with collections because of its strutcture.Thats some thing different from basic things in java.

But now its also be like a simple things like array etc. For ex, a Collection class we might consider something similar to arrays.

Instead of:

Collection<String> c = new ArrayList();
Collection<String> c = new ArrayList {“one”, “two”, “three” };

Thats all folks.If any important updates are missing don’t hesitate to add that as comments.

Java code to Wrap and Rotate image in PDF File

August 2, 2010 2 comments


Now-a-days if we wanna develop an application, that application must have the capability to prefer the Reports. All the reports are  favour to PDF format. If we develop a report for a particular concern the client needs to place their logo in the report. For that we need to insert the image in PDF file. This article deals the same.

The itex.jar makes it most simple and elegant.


JDK 1.5 and Above

Jar : itext.jar(Download here)

To make a program over this, firstly we need to import some packages. Remember to make this program the first and foremost thing to remember is to place the iText.jar in WEB-INF/lib of your web application.

Without this .jar the application will not run.

Steps involved in Insert image in PDF File:

Create Document :

This class describes a PDF file’s page size, margins, and other important attributes. It works as a container for a document’s chapters, sections, images, paragraphs, and other content.

Create PdfWriter:

This class is used to create the pdf file.

By using the method getInstace we can create pdf file from the given output stream.

Open pdf File:

Now open the document by using open() method in document class.

Get the Image content:

By using the method getInstace() of image class we can get the image content.

The method has the image filename as argument.

Add contents to Pdf File:

By using add method in document class we can add paragraph and image in the pdf file.

Resize the image:

By using the scaleAbsolute() method we can resize the image. We can pass the width and height as the argument to resize the image.

Rotate image:

By using setRotationDegrees() method of image class we can set the degree which we want to rotate the image.

After rotate the image we add the image into the pdf file by using add method of document class.


package com.bsj.itext;

import com.lowagie.text.*;
import com.lowagie.text.pdf.*;

 * @author Muneeswaran
public class WrapImageinPdf
 public static void main(String arg[]) throws Exception
 //Create Document
 Document document = new Document(PageSize.A4.rotate());
 //Create PdfWriter:
 PdfWriter.getInstance(document, new FileOutputStream("imagePdf.pdf"));
 Font font = new Font(Font.TIMES_ROMAN, 18, Font.BOLD);
 //Open pdf File:;
 Paragraph paragraph = new Paragraph("Original:", font);
 Paragraph par = new Paragraph("After rotate:", font);
 //Get the Image content:
 Image image = Image.getInstance("2.jpg");
 //Add contents to Pdf File:
 //Resize the image:
 image.scaleAbsolute(500.0f, 500.0f);
 //Rotate image:


I hopes this helps.Go ahead to prefer report and inserting logo in pdf.Before that,if you feel it useful,leave your foot prints here[Comments].

Execute Javascript from Java

June 20, 2010 24 comments

After a small gap,I am back to here for share something to you all.A week before i have stuck with execute javascript from java.I google it for this.Finally i found my way to achieve this.

Java provides the way to execute JavaScript also.The solution is come along with ScriptEngineManager.This article deals the same.

The ScriptEngineManager comes along with the package javax.script.

This is a relatively small, simple API. A ScriptEngineManager object can discover script engines through the jar file service discovery mechanism. It can also instantiate ScriptEngine objects that interpret scripts written in a specific scripting language. The simplest way to use the scripting API is as follows:

  • Create a ScriptEngineManager object.
  • Get a ScriptEngine object from the manager.
  • Evaluate script using the ScriptEngine’s eval methods.

Now we look at the sample code.

import javax.script.*;
public class ExecuteScript {
 public static void main(String[] args) throws Exception {
 // create a script engine manager
 ScriptEngineManager factory = new ScriptEngineManager();
 // create a JavaScript engine
 ScriptEngine engine = factory.getEngineByName("JavaScript");
 // evaluate JavaScript code from String
 engine.eval("print('Welocme to java world')");

Executing a Script from .js File:

In this example, we can execute JavaScript which is from .js file.This can be achieved by the eval method of ScriptEngine Class.
The eval method have the FileReader object as argument.

we can create the ScriptEngineManager and get the ScriptEngine from the above code(line 4-7).

Then we add the eval method which is used to execute script from .js file.

// evaluate JavaScript code from given file

Let us assume that we have the file named “welcome.js” with the following text:

println("Welcome to java world");

If we will run the code,this yields the output as

Welcome to java world.

I hopes this helps.Then Go ahead to execute your JavaScript by using your java code.Before that,if you feel it useful,leave your foot prints here[Comments].

Regular Expression Symbols

April 17, 2010 Leave a comment


“Regular expressions” are combination of special characters and symbols used for pattern matching. i.e., you specify a particular combination of such characters and symbols (= regular expression) and the compiler will search for that string of words through the text data. The following is a very short, and hopefully easy-to-follow, introduction to some of the most useful regular expressions.

1. Common matching symbols

Table 1.

Regular Expression Description
. Matches any sign
^regex regex must match at the beginning of the line
regex$ Finds regex must match at the end of the line
[abc] Set definition, can match the letter a or b or c
[abc[vz]] Set definition, can match a or b or c followed by either v or z
[^abc] When a “^” appears as the first character inside [] when it negates the pattern. This can match any character except a or b or c
[a-d1-7] Ranges, letter between a and d and figures from 1 to 7, will not match d1
X|Z Finds X or Z
XZ Finds X directly followed by Z
$ Checks if a line end follows

2. Metacharacters

The following meta characters have a pre-defined meaning and make certain common pattern easier to use, e.g. \d instead of [0…9].

Table 2.

Regular Expression Description
\d Any digit, short for [0-9]
\D A non-digit, short for [^0-9]
\s A whitespace character, short for [ \t\n\x0b\r\f]
\S A non-whitespace character, for short for [^\s]
\w A word character, short for [a-zA-Z_0-9]
\W A non-word character [^\w]
\S+ Several non-whitespace characters

3. Quantifier

A quantifier defines how often an element can occur. The symbols ?, *, + and {} define the quantity of the regular expressions

Table 3.

Regular Expression Description
* Occurs zero or more times
+ Occurs one or more times
? Occurs no or one times, ? is short for {0,1}
{X} Occurs X number of times, {} describes the order of the preceding liberal
{X,Y} .Occurs between X and Y times,
*? ? after a qualifier makes it a “reluctant quantifier”, it tries to find the smallest match.
Categories: 1

Pattern class of Regular Expression in Java

April 17, 2010 2 comments


This article makes you bit more knowledge in java regular expressions. For manage the regular expressions, the java have the three classes in java.util.regex package. But in this article we focused only Pattern class.

A regular expression is a pattern of characters that describes a set of strings. We use the regular expressions to find, display, or modify some or all of the occurrences of a pattern in an input sequence.

Java.util.regex classes:

The package java.util.regex contains three classes such as,

  • Pattern Class
  • Matcher Class
  • PatternSyntaxExcpetion

Let us take a look at Pattern class.

Pattern Class:

A regular expression which is specified as a string that should be first compiled into an instance of Pattern class. The resulting pattern can be used to create an instance of  Matcher class which contains various in-built methods that helps in performing a match against the regular expression. Many Matcher objects can share the same Pattern object.

Create Pattern using compile():

Pattern class doesn’t have a public constructor. So by using the static method compile we can create the pattern.

Pattern p = Pattern.compile("my regexp");

For Regular expression symbols,click here

Important Note:

The backslash is an escape character in Java Strings. i.e., backslash has a predefine meaning in Java. You have to use “\\” instead of “\”.

If you want to define “\w” then you must be using “\\w” in your regex like this.

Pattern r = Pattern.compile(“\\w+”); //Place your pattern here

“\w“ represents a word character, i.e., short for [a-zA-Z_0-9]

We can create the Pattern with flags.


Pattern pattern=Pattern.compile(regex,flags);

For ex, If we want to neglect the case sensitive we can achieve by using below one,

Pattern pattern = Pattern.compile(“\\w+”,Pattern.CASE_INSENSITIVE);

Validate pattern using matches():

The matches() method is used to check whether the given input is match with the pattern. This method returns true only if the entire input text matches the pattern.

boolean isMatch = Pattern.matches(“\\w+”,”Welcome to java world”);

Get the Pattern using pattern():

The pattern() method is used for find out the pattern of the given string. This method returns the regular expression as a string from which this pattern was compiled.

Pattern p=input.pattern();

Split input using split():

The split() method is used to split the given input text based on the given pattern. It returns a String array. There are two forms of split() method,

  • split(String input)
  • split(String input, int limit)

In the second form, we have an argument called limit which is used to specify the limit i.e. the number of resultant strings that have to be obtained by split() method.

String[] str = pattern.split(input,3);

Sample code for Pattern class and methods:


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

 * @author Home
class MailIDValidation
 public static void main(String args[])
 //Input the string for validation
 String email = "";

 //Set the email pattern string
 Pattern p = Pattern.compile(".+@.+\\.[a-z]+");

 //Match the given string with the pattern
 Matcher m = p.matcher(email);

 //check whether match is found
 boolean matchFound = m.matches();

 if (matchFound)
 System.out.println("Valid Email Id.");
 System.out.println("Invalid Email Id.");

I hope it offer bit more knowledge in Regular Expressions. The next article makes you clear in Matcher class in regular expression.Please leave your footprints (comments) here.