Category Archives: Java

Java Best Practices- String Literal Comparison

Whenever we create a String literal or a String constant, Java searches its String pool and if string is found, it will give reference to the String variable. Please note this is true only when we create a literal and not the object, i.e you do String str=”hello” and not String str=new String(“hello”);

Another point of importance is that if you compare string literals using ==, it might work because as mentioned above both the Strings might be refering to same object.


String str=”hello “+”kamal”;
String str1=”hello”;
str1+=” kamal”;
String str2=”hello kamal”;
String str3=”hello kamal”;

// all above prints hello kamal

System.out.println(str==str1); //false
System.out.println(str==str2); //true
System.out.println(str==str3); //true
System.out.println(str.equals(str1)); //true
System.out.println(str.equals(str2)); //true
System.out.println(str.equals(str3)); //true

Java Best Practices- String literals at left

It is always a good practice in Java to place String literals at left while comparing a String lteral with a String variable using equals or equalsIgnoreCase. The idea is if you keep variables at left, it might result in null pointer exception.

For example

String a=null;
System.out.println("0".equals(a)); //works fine
System.out.println(a.equals("0"	)); //results in null pointer exception

Initialize a matrix – efficiently

A simple code to initialize a matrix of N*N elements with all same number can be to create 2 for loops from 0 to N and set element to the required number. A silght improvement can be done to this code by

 for (int i = 0; i < N / 2; i++)
      for (int j = i; j < N - i; j++) {
        arr[i][j] = 0;
        arr[j][i] = 0;
        arr[N - 1 - i][N - 1 - j] = 0;
        arr[N - 1 - j][N - 1 - i] = 0;

Using CheckStyle with Eclipse

CheckStyle is a development tool which helps you format your Java code with respect to industry accepted standards. You can create your own check list to format and check style of code, or simply use one provided by checkstyle.

For eclipse it is easy to install plugin that is available. Go help->Eclipse MarketPlace-> serach for checkstyle.

Once eclipse plugin is added, you will see option on right click of project or a file to run a checkstyle which will show error messages in panel (Window->Show View-> Others-> Search Checkstyle).

If you want eclipse to format (Ctrl+Shift+F) the code in desired format, you can add formatter XML by Project->Properties->Formatter->Import. One such default XML can be found at –

Using Mockito with Spring

Junit testing is an integral part of unit testing while developing any application. It makes sense at times to separate out testing of Business layer from DAO layer to avoid generation of test data everytime or may be DAO layer is being developed independently.

Frameworks like Mockito or Easymock comes handy when dealing with such situations where you only want to test one class or one method and mock any other dependencies by dummy objects.

Here is a simple example

public class UserManagerTest{
	private static final String userName="kamal";
	private UserManager userManager=new UserManager();
	private UserDAO userDAO;

	public void initMocks() {
	//Remove the Ignore tag to execute the test case
	public void addUserTest()
		try {
			Mockito.when(userDAO.getUserDependencies(userId)).thenReturn(new UserDependencies("temp"));
		} catch (Exception e) {
			fail("Test case failed");
			// TODO Auto-generated catch block


We are calling userManager.addUser(userName), but at the same time we are telling JUnit to do nothing (do not call the DAO layer), when you see this call to avoid data insertion. In addition there is another method which will check user dependencies (may be after adding user it check if there are some default depenedencies), where we tell Junit to instead of calling real DAO method and fecthing an objects, lets return a dummy object.

Mybatis- Using SelectProvider and ResultMap

I recently wrote about how a basic mybatis application can be set with Spring.

But there are situations when queries can be a bit complex than a simple insert or select. In such cases


can help us build a dynamic query.

For example, in my user mapper, I need to search based on Id OR status.

@SelectProvider(type = UserSQLBuilder.class, method = "getUsersProvider") 
public List searchUser(@Param("id") String id,@Param("status")  String status);

My UserSQLBuilder class would have a method called getUsersProvider which will create a dynamic query based on paramaters I am passing here.

public class UserSQLBuilder {

	public String getUsersProvider(Map parameters) {
		String id = (String) parameters.get("id");
		String status = (String) parameters.get("status");
		StringBuilder query = new StringBuilder();
		query.append("select id, user_name, user_address, status from users");
		if (status.equals("NA") && !id.equals("NA")) {
			query.append(" where id like '%" + id + "%'");
		} else if (!status.equals("NA") && id.equals("NA")) {
			query.append(" where status ='" + status + "'");
	        return query.toString();

Another important thing to note here is that I am using @ResultMap to map result of query to my User (List) object. If we look at the query, it returns user_name, user_address etc. Whereas in my User class I have userName, userAddress and so on. The challenge is to map query values to object values.

There are actually multiple ways.

1. I can simply modify my query – select user_name as userName, user_address as userAddress from users.
2. Explicitly tell my mapper to map the values from column to object like

@SelectProvider(type = UserSQLBuilder.class, method = "getUsersProvider") 
@Results({ @Result(property = "userName", column = "user_name"),
@Result(property = "userAddress", column = "user_address") })
public List searchUser(@Param("id") String id,@Param("status")  String status);

3. Create a @ResultMap which can be reused, useful in cases when same mapping has to be done more than once.
statement tells the mapper to look for a map in config file.

in, I will define

public static final String REPORT_MAP = "com.test.mapper.UserMapper.user";
//code here

private void registerUserMap(org.apache.ibatis.session.Configuration config) {
		// registering result maps
		List flags = new ArrayList();
		List resultMappings = new ArrayList();

		org.apache.ibatis.mapping.ResultMapping.Builder resultBuilder = new org.apache.ibatis.mapping.ResultMapping.Builder(
				config, "userName", "user_name", String.class);

		resultBuilder = new org.apache.ibatis.mapping.ResultMapping.Builder(config, "userAddess",
				"user_address", String.class);

		Builder resultMapBuilder = null;
		resultMapBuilder = new Builder(config, "", Report.class, resultMappings, true);

And while defining my session factory, I will register this Map.

		public SqlSessionFactory sqlSessionFactory() throws Exception {
			org.apache.ibatis.mapping.Environment environment = new org.apache.ibatis.mapping.Environment("",
					new JdbcTransactionFactory(), getDataSource());
			org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration(environment);


			return new SqlSessionFactoryBuilder().build(config);

HTTP verbs implementation for REST webservices

A REST webservice would normally support four HTTP verbs GET, POST, PUT and DELETE.

Simply putting, the verbs have following function.

GET: requests some information from server.
POST: sends/ posts some data to application.
PUT: requests that sent data to be put under given URI location.
DELETE: Deletes the given entity.

Most common of these are GET and POST, as they can mostly handle all the requests.

Another interesting debate is when to use PUT and POST as both tend to send some data to server. Ideally, when we know exactly where to add the data, we will use put, and if we want application to take a call, we will use post. For example if I want to add/ edit user id 112, I will use PUT. But if I just say add a user and let application assign the id, I will use POST.

More on PUT vs POST-

A simple Email Validator Java Utility

public class EmailValidator {

	private static Pattern pattern;
	private static Matcher matcher;

	private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
			+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
		pattern = Pattern.compile(EMAIL_PATTERN);

	public EmailValidator() {

	 * Validate hex with regular expression
	 * @param hex
	 *            hex for validation
	 * @return true valid hex, false invalid hex
	public static boolean validate(final String hex) {

		matcher = pattern.matcher(hex);
		return matcher.matches();


Using Mybatis with Spring

Mybatis is Java Persistence framework, build upn JDBC. I look at it mostly as a bridge between conventional JDBC and an ORM solution like hibernate. The flexibility Mybatis provide is to write queries similar to JDBC, yet takes away all the complexity and boilerplate code for creating and maintaining connections and transactions. It can also map your objects to Tables like ORM solution, without getting into complexities of an ORM fraework, but at a cost of some additional code.

Mappers: Mappers are core of Mybatis implementation. A Mapper class would contain queries to be executed by mybatis. A good practice is to create a mapper for each table in database.

Here is a simple Mapper class

public interface UserMapper {

	 * This method validates the credentials for any user.
	 * @param userName
	 * @param password
	 * @return
	@Select("select id from myuser where username=#{userName} and password=#{password}")
	public Integer verifyAdminUser(@Param("userName") String userName,
			@Param("password") String password);

	 * This method returns list of all users.
	 * @return
	@Select("select username, password from myuser")
	public List getUsers();

In the getUsers method, you can see mybatis will automatically convert the results into a Java List with User objects.

Coming to Setting up Mybatis with Spring, if you are using Java based configuration, all you need to add is


and tell location of your mappers package(s).

In addition you would want spring to manage transactions for you by

public class MyConfig implements TransactionManagementConfigurer{

//JNDI lookup for database
private DataSource getDataSource() {
		InitialContext ic;
		DataSource ds = null;
		try {
			ic = new InitialContext();
			String jndiName ="jndi";
			ds = (DataSource) ic.lookup(jndiName);
		catch(Exception e)
		return ds;

		public SqlSessionFactory sqlSessionFactory() throws Exception {
			org.apache.ibatis.mapping.Environment environment = new org.apache.ibatis.mapping.Environment("",
					new JdbcTransactionFactory(), getDataSource());
			org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration(environment);

			return new SqlSessionFactoryBuilder().build(config);

	public PlatformTransactionManager annotationDrivenTransactionManager() {
		return  new DataSourceTransactionManager(getDataSource());

You are all set to use Mappers just by Autowiring in any class.

Spring Security- with Java Configuration

Recently I wrote about getting started with Spring Security. In that, I used XML configurations for spring security. As a Java developer, I normally prefer Java configuration with Spring than XML. So here is how we can move from XML configuration to Java configuration.

Firstly I tell my web.xml that I want to use Java file based configuration and provide configuration class.

<?xml version="1.0" encoding="ISO-8859-1" ?>

<web-app xmlns="" xmlns:xsi=""







Here is a simple contoller path which I need to secure

package com.myapp.test;


import javax.servlet.ServletException;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

public class SampleService {
	@RequestMapping(method = RequestMethod.GET, value = "/hello")
	public ModelAndView LepService(@PathVariable("id") String id)
			throws ServletException, IOException {

		ModelAndView mv = new ModelAndView("hello");
		// Do something here
		return mv;

As you can see this simply redirects to hello view (hello.jsp).

And here the configuration file.

@ComponentScan(basePackages = "com.myapp.test")
public class MyConfig extends WebSecurityConfigurerAdapter {

	public UrlBasedViewResolver urlBasedViewResolver() {
		UrlBasedViewResolver res = new InternalResourceViewResolver();

		return res;

	public void configure(WebSecurity web) throws Exception {

	public void configureGlobal(AuthenticationManagerBuilder auth)
			throws Exception {

	protected void configure(HttpSecurity http) throws Exception {