Visualization of Few Data Structures and Algo’s using JavaScript.

Hello Readers,

I am currently working on a small fun type project to setup visualization of Few Data Structures and Algo’s using JavaScript. The project is hosted on Github, Feel free to fork and suggest. Thanks stay blessed!!

Link can be found here.

Bubble Sort

It’s really been a very long time since I had wrote something, So many things were going which were kind of keeping me very busy, But I finally managed to get some time.. yay!!! yepeee!!, So to continue my journey towards CS algorithms,  I had tried the Bubble Sort with single loop.

Steps are like:
For any given Array:
Take the first two elements and move the largest to the right, and keep doing that unless the largest reached at the position where either its the last position of array or the the position where its right is already the largest and then again repeat and do until all the largest values moves to the right side of array.

Here is the example: Your inputs are highly appreciated 🙂

import java.util.Arrays;

import java.util.Random;

public class BubbleSortV1 {

public static void main(String[] args) {

int[] arr = fillArray();

System.out.println(“Unsorted Array :: “ + Arrays.toString(arr));


System.out.println(“Sorted Array :: “ + Arrays.toString(arr));



private static void verifyArray(int[] arr) {

booleans = true;

for (int i = 0; i < 99; i++) {

if (arr[i] > arr[i + 1]) {

System.out.println(“not sorted…”);

s = false;




if (s) {

System.out.println(“all sorted;”);



static int[] fillArray() {

int[] arr = new int[100];

Random r = new Random();

for (int i = 0; i < 100; i++) {

arr[i] = r.nextInt(500);




// read from left to right and

// move the largest item to the right

// that way all large would be on right side and small on left side

static void bubbleSort(int[] arr) {

// store the last unsorted index

int sortedPartIndex = arr.length;

// first bucket

int leftBucketIndex = 0;

// second bucket

int rightBucketIndex = 1;

// keep running until sorted index reaches 0 (right to left)

while (sortedPartIndex > 0) {

if (arr[leftBucketIndex] > arr[rightBucketIndex]) {

int tempBucket = arr[rightBucketIndex];

arr[rightBucketIndex] = arr[leftBucketIndex];

arr[leftBucketIndex] = tempBucket;




if (rightBucketIndex >= sortedPartIndex) {

// decrement the sorted part index

sortedPartIndex = sortedPartIndex – 1;

// reste the left and right bucket index to default, to start

// over

leftBucketIndex = 0;

rightBucketIndex = 1;





Random Shuffle of Array

Example of how to do a random shuffle of any Given Array. This example is based on a very famous shuffle algorithm knows as Fisher Yates Shuffle. Could be useful to implement in Poker Game to shuffle cards in Java.

Main Steps are:

1. loop from n to 1

2. generate the random index number k such that  0 <= k <= the length of array

3. swap the values between the random index and current iteration index

See below link for more details on this.

private static int[] shuffle(int[] a) {

Random rand = new Random();

for (int lc = a.length – 1; lc > 0; lc–) {

    int shuffleIdx = rand.nextInt(lc + 1);

    int v = a[shuffleIdx];

   a[shuffleIdx] = a[lc];

   a[lc] = v;


return a;


Code Bubble IDE


I have worked on many different IDE’s (Integrated Development Environment) like Eclipse, Intellij, Jboss Studio, JCreator and few others, but working on code bubbles programming environment is unbelievable. Its pretty awesome…

Here is the video link on You Tube. Check this out.. if you really love to code on Java. Really hats off to the Code Bubble team.



Phases of Java Class loading

Hi All,

This post is regarding the phases of class loading in any java based application.  I came across a very good write up material, and thought of sharing with all my blog users.

The loading of a class can essentially be broken down into three phases:
1. Loading
2. Linking
3. Initializing.

Most, if not all, problems relating to class loading can be tracked down to a problem occurring in one of these phases. Therefore, a thorough understanding of each phase helps in the diagnosing of class loading problems. The phases are illustrated in Figure 2

class loading

The loading phase consists of locating the required class file (by searching though the respective classpaths) and loading in the bytecode. Within the JVM, the loading process gives a very basic memory structure to the class object. Methods, fields, and other referenced classes are not dealt with at this stage. As a result, the class is not usable.

is the most complicated of the three phases. It can be broken down into three main stages:

  • Bytecode verification. The class loader does a number of checks on the bytecodes of the class to ensure that it is well-formed and well-behaved.
  • Class preparation. This stage prepares the necessary data structures that represent fields, methods, and implemented interfaces that are defined within each class.
  • Resolving. In this stage, the class loader loads all the other classes referenced by a particular class. The classes can be referenced in a number of ways:
    • Superclasses
    • Interfaces
    • Fields
    • Method signatures
    • Local variables used in methods

During the initializing phase, any static initializers contained within a class are executed. At the end of this phase, static fields are initialized to their default values.

At the end of these three phases, a class is fully loaded and is ready for use.

Note that class loading can be performed in a lazy manner and therefore some parts of the class loading process may be done on first use of the class rather than at load time.

Hope this helps.

R Vashi

Using Log4j to log Hibernate queries with values

Hi All,

Hibernate is one of most used ORM framework across the J2EE Applications, It provides many features which helps us to organize the SQL queries in a very easy manner just by playing with java entity bean properties. In this post I will explain the way we can display the named queries in log file including the run time value bindings,

In bigger applications debugging SQL queries is a very crucial thing came into picture, a query containing more SQL Joins is not that easy to debug in case if some misalignment in data found.  To ease that just follow the below steps to enable this sort of hibernate logging in logger(LOG4J).

In Log4j properties add the below two category entries. STDOUT // this is as equivalent hibernate.show_sql=true DEBUG// this basically prints the bound parameters among other things.

Output in Logger file

Hibernate: select emp0_.dept_id as dept2_1_, emp0_.emp_id as emp1_1_, emp0_.emp_id as emp1_0_0_, emp0_.dept_id as dept2_0_0_, emp0_.emp_join_date as emp3_0_0_, emp0_.emp_name as emp4_0_0_, emp0_.bank_name as bank5_0_0_, emp0_.salary as salary0_0_ from Employee emp0_ where emp0_.dept_id=?
2011-12-03 13:08:50,031 DEBUG [main] AbstractBatcher – preparing statement
2011-12-03 13:08:50,031 DEBUG [main] NullableType – binding ‘1’ to parameter: 1
2011-12-03 13:08:50,031 DEBUG [main] AbstractBatcher – about to open ResultSet (open ResultSets: 0, globally: 0)

Hope this helps 🙂

R Vashi

Configure Log4j in simple steps

Hi All,

The logging framework always plays a crucial part in your application. In this post i will explain how to configure Log4J in simple steps.

Put the Log4j jars file in classpath.

Step 2:
Create a log4j properties | xml file.

# Set root logger level to INFO

log4j.appender.STDOUT.layout.ConversionPattern=%d %p [%t] %C{1} - %m\n STDOUT STDOUT


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

Step 3:
Write a program to load and start the logging in application

private static Logger logger = Logger.getLogger(TestJPAConfiguration.class);

public static void main(String[] args) {

//this is for basic loading

//Use property configurator to explicit load the log4j properties file.

//in case of using XML config, Use DOM Configurator
// DOMConfigurator.configure(“log4j.xml”);“Log4J Configured  successfully”);


Hope this helps. 🙂

R Vashi

Using ValidationEventHandler while converting XML to Java object in JAXB

Hi All,

JAXB as we know is an API  for XML Binding. It is heavily used in JAX-WS web services as a binding standard. XML Data binding describes the conversion of data between its XML and Java representations.

So this post talks about the phase when we convert the XML Data to its corresponding Java objects. It seems easy as just by calling the unmarshaller.unmarshal method. But what goes behind the scene is not that quite easy.

And think about a scenario where you have data payload in XML format of more than 3mb and just seeing some “NullPointerException” during un-marshalling will make you go mad(specially which I had felt so many times 🙂 ).

So to tackle this lets first of all understand what JAXB does during un-marshalling. JAXB reports validation of data through events.  It uses a handler called as “ValidationEventHandler“, And this handler represent an instance of “ValidationEvent” and provides many details about the un-marshalling related issues.

Lets see in an example(I am taking the base example I have posted in this post)

Step 1: Create a Custom Handler Class

import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;

public class CustomValidationEventHandler implements ValidationEventHandler {

    public boolean handleEvent(ValidationEvent event) {
        System.out.println("Severity:  " + event.getSeverity());
        System.out.println("Message:  " + event.getMessage());
        System.out.println("Linked Exception:  " + event.getLinkedException());
        System.out.println("    Line Nbr:  " + event.getLocator().getLineNumber());
        System.out.println("    Column Nbr:  " + event.getLocator().getColumnNumber());
        System.out.println("    Offset:  " + event.getLocator().getOffset());
        System.out.println("    Objct:  " + event.getLocator().getObject());
        System.out.println("    Node:  " + event.getLocator().getNode());
        System.out.println("    URL:  " + event.getLocator().getURL());
        return true;


Step 2: Register the Handler with the Unmarshller

unmarshaller.setEventHandler(new CustomValidationEventHandler());

Now run the program and you will see the somewhat similar output.

Severity:  1
Message:  cvc-maxLength-valid: Value 'TESTPRODUCT' with length = '10' is not facet-valid with respect to maxLength '8' for type 'stringWithMaxSize8'.
Linked Exception:  org.xml.sax.SAXParseException: cvc-maxLength-valid: Value 'TESTPRODUCT' with length = '10' is not facet-valid with respect to maxLength '8' for type 'stringWithMaxSize8'.
    Line Nbr:  3
    Column Nbr:  12
    Offset:  -1
    Object:  null
    Node:  null
    URL:  null

One thing which I have observed is that the Node and URL properties are not always available to be set on the locator. This is something which I am investigating will sure post the reasons on the same, would appreciate if somebody share the reason.

Please do share your thoughts about this Post 🙂

R Vashi