Design Patterns

Design patterns are common practices which are used to solve problems which are similar in nature. More »

Algorithms and Data Structures

Data structures are basic building blocks of any computer program. Algorithms are used to solve any real life program programatically. More »

Java programming language

Java is one of the most popular and advanced programming language which is used to create many enterprise level solutions. More »

Fun Stuff

Kool and fun side of technology. More »

Other stuff

Random posts More »


Call by Value

We know that in Java everything is pass by value. But the interesting thing is that in case of Objects, the reference of the Object is pass by value.

Lesson learned while testing previous method for reversing link list.

If I call the method just like


All I get in n1 is 1.

So correct way to make the call is

n1= reverseLinkedList(n1);

Reverse a Link List

private static Node reverseList(Node head){
Node temp=null;
Node temp2=null;
//Initial state- set temp pointer at head->next
//Set null as this will eventually become last node;
//Temporary pointer 2 to be placeholder of;;
return head;

Handling Null Values in SQL- ISNULL, NVL2, IFNULL, Coalesce

There can be situations when if a value is null in sql query, you want to replace it with something else. Different DBs provide you different options

Oracle- PLSQL
select NVL2(teamid, teamid, deptid) allocationid, empid, name from employee; //If team id is available that is returned as allocation id else deptid

select ISNULL(teamid, deptid) allocationid, empid, name from employee;

Similarly MySQL has IFNULL

Another option is COALESCE, this works for both Oracle and MS-SQL. This is slightly different from others in implementation that it makes columns to be skipped unless first non-null value is found

select COALESCE(teamid, deptid, organizationid) allocationid, empid, name from employee;

Find Unique Rank for a String

Problem Statement: For each String we need to assign a unique rank.

B will Have higher rank than A
Z Will have higher rank than B
Z will have higher rank than AA
KAMAL will be higher than AMIT (K>A)
KAWAL will be higher than KAMAL (W>A)
and so on

Solution: Assign a numeric value to each character in string and then add them in a way to create a rank.
Value assigned to characters (A is lowest)
A=0.01, b=0.02.. and so on


1. Loop The characters in string
1a. Assign Face weight to current character (A= 0.01, B= 0.02 etc)
1b. Assign Position Weight to current character (first char is multiple of 0.01, second of 0.0001 and so on)
1c. update totalweight by adding character weight calculated in 1a and 1b
2. Return totalweight

public static double getRank(String str)
char arr[]=str.toCharArray();
double rank=0;
double multiplier= 0.01;
for(int i=0;i {
rank+=getCharVal(arr[i])*multiplier;// getCharVal return values like A=0.01, B=0.02..
return rank*100;


Algorithm Complexity:
Though if you look closely it might give impression of O(N) complexity, where N is characters in destination string. But as if are dealing with controlled input and string can be of average length 6-10 characters, we can easily confirm the algo to be of constant complexity.

Forgot password for Oracle accounts

I have a oracle installation on my windows machine but that was done a few months back and I could not recollect passwords for default sys and sysadmin records. The following trick helped reset passwords for these accounts

1. Go to Command prompt and type sqlplus /nolog. It should open SQL/> prompt.
2. On SQL/> prompt, type connect /as dba
Now you are logged in as dba, changing password is simple matter of
SQL> alter user sys identified by “newpassword”

Template method pattern vs Strategy Pattern

Template method pattern and Strategy pattern can appear quite similar in nature as both help us execute an algorithm/ code steps and define executions differently under different circumstances.

The major difference is that Strategy pattern let you decide complete different strategy i.e. set of algorithm(s) based on requirement at the run time, for example which tax strategy to be applied Indian or Chinese. On the other hand, Template pattern puts in some predefined steps (of a algorithm), out of which some are fixed and others can be implemented differently for different usages, say read data from file, parse data, write data to file- parsing might be done differently based on kind of data we are dealing with, but reading from and writing to file will be fixed.

More here -

Template method design pattern

Template method design pattern allows one to create a template of code or algorithm which will provide guidelines for other developers on how to write the solution for different implementations.

To keep it simple, let’s go back to HTML template. HTML template lets you define overall look and feel of page without getting into details. For example, I want all my pages to have a header, a footer, left panel, right panel, middle content panel. I might want to add some parts are fixed, say header and footer will always looks same, but center, right and left can be customized by users.

Same principle is used in template design pattern. Say I have to implement a template reading data from database.

Step 1: get database connection
Step 2: create query
Step 3: Execute Query
Step 4: Parse Data
Step 5: Close connections

Here Step 1, 3 and 5 are common for all type of queries but Step 2 and 4 will be data dependent. This can be achieved by Template Method pattern.

A good explanation can be seen here


Image from

Spring Framework- Basics

The question which I asked 4 years back when I was to use Spring framework for project was- Why Spring? I was using Struts for few years and was in love that, so why to try something new.

Over the time I have found a very convincing answer which I will share.

    1.Empowering POJO’s
    2.Dependency Injection
    3.It is more than web application development framework
    4.Support for Aspect oriented programming

1. For me most important feature which Spring provides is use of POJOs (Plain Old Java Objects). Working with frameworks like Struts, you need to follow a very strict format, for example for each controller servlet you need to extend action class and override execute method with fixed number of parameters. Even if you are creating simple servlet you need to have get and post methods to handle client requests in a particular format. Spring finally gives you freedom to use plain java classes and convert to controllers or request handlers using simple annotations.

2. Dependency injection is implementation of inversion of control principle which helps maintain loose coupling and move away dependencies from the current class and let it focus on its real goal. Read more on dependency injection-,,

3. As I said, Spring is not just for handling request response or implementing MVC like struts, it goes much beyond that. It is kind of a bouquet providing end to end solution for an application like it provides Spring Security for controlling access to application, provides Spring MVC for handling request/ response in MVC mode, provide Workflow to handle control flow, support for webservices through Spring Restful templates etc.

4. Finally support for aspect oriented programming (AOP). Spring supports AOP, that means you can separate some aspects of code so that your classes can focus on the responsibility given to them. For example creating logs is one aspect of a code, which we need to write in every class to make sure proper logs are maintained. Spring helps you pull this aspect out of the code and handle through some configuration making sure logging occurs whenever required.

Maximum Subarray Problem- N log N solution

For algorithm and explanation, read here.

Code implementation

public class MaxSumTest
* Main method
* @param s
public static void main(String s[])
int[] arr=new int[10];
arr=new int[]{10, -19 , 8 , 4, -5, 2, -1, 3, 8,-9};

int arrlength=arr.length/2;
int[] arr1=createarr(0,arrlength,arr);
int[] arr2=createarr(arrlength, arr.length,arr);
int sum=maxsum(arr1,arr2);

* To find out maximum sum subarray, following divide and conquer technique is used
* 1. Divide the array in 2 equal parts, now there are 3 possibilities.
* a. Max sum subarray crosses the mid of original array, i.e. a part of solution is in left array and other in right. Finding this is simple as we just need to move backword on left subarray to find the maximum sum, and then move fwd on right array to find max, and finally add the two
* b. The other possibility is that max subarray is completely on left array. This means left subarray becomes main array and we discard right array. We will repeat the steps from 1.
* c. The last possibility is that max subarray is completely on right array. This means right subarray becomes main array and we discard left array. We will repeat the steps from 1.
public static int maxsum(int[] arr1, int[] arr2)
int sum1=0;
int maxsum1=0;
int sum2=0;
int maxsum2=0;
int maxsum=0;

//1.a. Find maximum sum crossing the the mid of original array.
for(int i=arr1.length-1;i>=0;i–)
if(maxsum1 }

for(int i=0;i {
if(maxsum2 }

//1.b. Find maximum sum in left subarray
int arrlength=arr1.length/2;
if(arr1.length==1) return arr1[0];
if(arr1.length==2) return (max(arr1[0], arr1[1],0));
int[] arr11=createarr(0,arrlength,arr1);
int[] arr12=createarr(arrlength, arr1.length,arr1);

//1.c. Find maximum sum in right subarray
if(arr2.length==1) return arr2[0];
if(arr2.length==2) return (max(arr2[0], arr2[1],0));
int[] arr21=createarr(0,arrlength,arr2);
int[] arr22=createarr(arrlength, arr2.length,arr2);

//Repeat steps and return final max sum value
return max(maxsum, maxsum(arr11,arr12), maxsum(arr21,arr22));


* Method to return max of 3 integers
* @param x
* @param y
* @param z
* @return
public static int max(int x, int y, int z)
return x;
return z;
return y;
return z;

* Create a subarray from start to end
* @param start
* @param end
* @param arr
* @return
public static int[] createarr(int start, int end, int[] arr)
int[] myarr=new int[end-start];
for(int i=start,j=0;i {
return myarr;


eCommerce: A view from the backend

Apart from features mentioned in my last post, which were directly related to commerce part of business, following are other important parts of an ecommerce system

Content: Your system will need to display items like News on products, Stock prices, policies etc.The content might be product related like images or videos for promotion.

Community: For customer to make an educated guess, it is desirable that he should know what others are talking about product and services. Product reviews, comparisons, chat messages, forums can be helpful for this.

Some other features which are actually invisible to end users, but business needs to take care while setting up ecommerce system

Load Handling: How much concurrent load can your website handle? The ecommerce site needs to be load tested to understand its behavior with increasing load.

Scalability: The website today might be designed to handle 10K users, but in future we might have 100K users. Can our website (technology we used) will scale up to handle increased user base.

Search Engine Optimization (SEO): This is another important aspect of an ecommerce system. Say we have a website selling mobile phones. We would like to make sure that search engines rank our site high whenever a mobile related query like “Android smartphone”, “Nokia phone” etc is searched for.

To support all the features mentioned for ecommerce site, we need to have some services working at backend to fill in manage the data

Content management: How the content is to be managed on user interface. What all items will be displayed and their organization at UI. This means creation and maintenance of pages and templates to be shown on website.

Product management: To add and manage product details.

Catalog management: As mentioned earlier, catalog will create list of products in a categorized manner. There can be different version of catalogs created and maintained by business.

Order management (workflow): An order management process needs to be defined and maintained.

User management: This is for both end user (making purchase) and business user (managing the system). We need to make sure no one gets unauthorized access to the system. For end user we need to make sure if user is active, and maintain user purchase history.

Offers Management: Various offers are provided by business in form of discounts and personalized deals. Business needs to monitor these offers and when an offer is active (season based/ holiday season etc).

In addition to above mentioned components, a true ecommerce system might also have

Suppliers and supply chain management: From where we will get the products? How much inventory is available and how much time will it take to be delivered (or how many tickets are left).

Shipping management: How shipping is handled (mostly outsourced). How products which are returned to company are handled?

Customer Relationship management: How do we make sure customer keeps coming back. You need to maintain the customer purchase history so you can recommend the most suited products. Also returns and complaints needs to handled gracefully to avoid any bad publicity and encourage customer loyalty.