Java Tip: Who called me?

This can be a handy tip if you are debugging some java application which cannot be run in single step debug for some reason. Suppose you have a method which is called from many places and you need to know the current caller.
Just capture the current stack trace by making a Throwable object. Now get the 2nd stack trace element from t.getStackTrace() which will have the caller details.

A small example..

public class test {

public static void main(String[] args) {
caller1();
caller2();
}

private static void caller1() {
method();
}

private static void caller2() {
method();
}

private static void method() {
Throwable t = new Throwable();
StackTraceElement ste = t.getStackTrace()[1];

System.out.println(ste.getMethodName() + " called me.");
System.out.println("File Name :"+ste.getFileName());
System.out.println("Line Number :"+ste.getLineNumber());
}

}

Quick Sort in Java

This is an easy verion of the popular quick sort algorithm implemented in Java.  Since the main aim is to keep it simple, this does not use the in-place partitioning algorithm.

package quicksort;

/**
 *
 * @author a435104
 */
public class Main {

	static int callCount = 0;
	
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        int[] array1 = {9,11,2,5,3,1,12};

        quicksort("main", array1);
        
        System.out.print("Sorted Array : ");
        printArray(array1);
    }

    /**
     * From - http://en.wikipedia.org/wiki/Quicksort
     * 
     * Quicksort sorts by employing a divide and conquer strategy to divide a list into two sub-lists.
     * The steps are:
     * 
   	 * 1. Pick an element, called a pivot, from the list.
     * 2. Reorder the list so that all elements which are less than the pivot come before the 
     *    pivot and so that all elements greater than the pivot come after it (equal values can go either way). 
     *    After this partitioning, the pivot is in its final position. This is called the partition operation.
     * 3. Recursively sort the sub-list of lesser elements and the sub-list of greater elements.
     *  
     *  
     */
    public static int[] quicksort(String debugString, int array[]) {
    
    	callCount++;
    	
    	System.out.println("\nQuickSort -> callCount :" + callCount + " arrayName :" + debugString);
    	System.out.print("Array Elements    -> ");
    	printArray(array);
    	
    	//base case 
        if (array == null || array.length  " + pivot);

        // Create two arrays, one to hold the elements lesser than pivot
        // another to hold elements greater than pivot.
        int[] lesserArray = new int[array.length];
        int[] greaterArray = new int[array.length];

        int gndx = 0;
        int lndx = 0;
        
        // Next two for loops performs the partition operation.
        // Rearranges elements around pivot such that,
        // elements greater than or equal to pivot goes to greaterArray and
        // elements less than pivot goes to lesserArray.
        
        for (int ndx = 0; ndx = array[pivotNdx]) {
                greaterArray[gndx] = array[ndx];
                gndx++;
            } 
            else {
                lesserArray[lndx] = array[ndx];
                lndx++;
            }   
        }
        
        for (int ndx = pivotNdx + 1; ndx = array[pivotNdx]) {
                greaterArray[gndx] = array[ndx];
                gndx++;
            } 
            else {
                lesserArray[lndx] = array[ndx];
                lndx++;
            }   
        }
        // end of partitioning.
        
        // trim lesserArray
        int[] tempArray = new int[lndx];
        System.arraycopy(lesserArray, 0, tempArray, 0, lndx);
        lesserArray = tempArray;
        
        // trim greaterArray
        tempArray = new int[gndx];
        System.arraycopy(greaterArray, 0, tempArray, 0, gndx);
        greaterArray = tempArray;
        
        System.out.print("After partitioning, lesserArray -> ");
        printArray(lesserArray);
        
        System.out.print("After partitioning, greaterArray -> ");
        printArray(greaterArray);
        
        // recursively call quicksort on lesserArray and greaterArray.
        return concatenate(quicksort("lesserArray", lesserArray), pivot, quicksort("greaterArray", greaterArray), array);
        
    }
    
    private static int[] concatenate(int[] lesserArray, int pivot, int[] greaterArray, int[] array) {

        System.arraycopy(lesserArray, 0, array, 0, lesserArray.length);
        
        array[lesserArray.length] = pivot;
        
        System.arraycopy(greaterArray, 0, array, lesserArray.length + 1, greaterArray.length);
        
        return array;
    }
    
    private static void printArray(int array[]) {
        for (int i=0;i<array.length;i++) {
            System.out.print(array[i] + ", ");
        }
        
        System.out.println("");
    }
}

Marking methods final.. will it increase speed?

I had a misconception about final keyword that, it will speed up method calls if methods are marked as final. My thought was that, this will allow javac compiler to do static binding instead of leaving it to late binding at runtime. May be I might have got this point from some java performace tip articles. But the truth is that, java uses late binding even when methods are marked as final.


class test1 {
public void m1() {
System.out.println(m2());
}
public int m2() {
return 5;
}
}


class test2 extends test1 {
public int m2() {
return 10;
}
public static void main(String args[]) {
test1 t = new test2();
t.m1();
}
}

run “java test2”. This will print 10 as expected.

Now change m1() of test1 to final and compile test1.java alone.

This time when you try to run test2, java throws run time exception, java.lang.VerifyError.

This exercise shows/confirms that java does late binding even for methods marked as final.

So the conclusion is : Poor javac (Java compiler) can’t do static binding even for final methods. There is no way for the compiler to find if a sub class has already overridden a method, when it was not final.

ResourceBundle file lookup order

While developing Java programs which uses ResourceBundle to load properties files, a common pratice is to put all your English locale content into the default properties file XXX.properties. Till recently I did’nt know that it is important to ship your English locale files in XXX_en.properties file also. Problem arises when the user of your program runs the
program with a different locale other than English as platform default locale.

Let’s try one example to make the problem clear.

Consider the following program,

import java.util.*;

class TestBundle {

public static void main(String args[])
{

String baseName = “MyResources”;

try {

// Get the resource bundle for a specific locale
ResourceBundle rb = ResourceBundle.getBundle(baseName, Locale.ENGLISH);

String key = “hello”;
String s = rb.getString(key);
System.out.println(s);

key = “bye”;
s = rb.getString(key);
System.out.println(s);

} catch (MissingResourceException e) {
e.printStackTrace();
}

}
}

This is a standard program used to load a resource “MyResource_en.properties”.
My expectation is that if “MyResource_en.properties” is not there the program will load
“MyResource.properties”.

We will create two properties file, “MyResource_fr.properties” and “MyResource.properties”.

MyResources.properties:

hello=Hello
bye=Goodbye

MyResources_fr.properties:

hello=Bonjour
bye=Au Revoir

Now lets run our program in the following way,

java -Duser.language=fr TestBundle

We expect Hello and Goodbye to get printed.
Oops!! but it is actually Bonjour and Au Revoir that get printed.

The secret lies in the way ResourceBundle looks for files. ResourceBundle.getBundle generates a sequence of names to find the correct translation. To explain in a simplified way, if we assume that the server or machine on which your program runs uses French locale as default locale and the your program looks up English locale, following names will be generated,

MyResource_en.propertes -> User/Program locale.
MyResource_fr.properties -> The server/machine locale.
MyResource.properties -> Default if nothing matches.

MyResource_en.propertes does not exist, so MyResource_fr.propertes gets loaded.

A more detailed explanation of the file lookup order can be found in JavaDoc.

In Solaris platform, you can set the machine default locale to fr in the following way,
In bash prompt type,

LANG=fr
LC_ALL=fr
export LANG
export LC_ALL

In windows platform use the -D option.

So the important learning is, better ship your english content both XXX.properties and XXX_en.properties files rather than tracing bugs on weekends.

Does Java have a primordial interface?

Every Java developer knows that java.lang.Object serves as the root class for all Java class hierarchies. In that case, does java have a root interface for all interfaces ? If not, then how does java allow us to invoke equals method (or any other method defined in java.lang.Object) on an Interface reference ?

interface MyInterface {

}

class MyClass implements MyInterface {

public static void main(String[] args) {

MyInterface myInterface = new MyClass();

MyInterface yourInterface = new MyClass();

System.out.println(myInterface.equals(yourInterface));

}

}

In the above code snippet how am I able to call equals method on myInterface reference ?

Java Language Specificion says,

If an interface has no direct superinterfaces, then the interface implicitly declares a public abstract member method m with signature s, return type r, and throws clause t corresponding to each public instance method m with signature s, return type r, and throws clause t declared in Object, unless a method with he same signature, same return type, and a compatible throws clause is explicitly declared by the interface.

Interestingly, if you try to declare an equals method like the following in an Interface, javac will complain.

interface test {
public int equals(Object o);
}
[root@unnisworld:/unni] javac test.java
test.java:4: equals(java.lang.Object) in test cannot override equals(java.lang.Object) in java.lang.Object; attempting to use incompatible return type
found : int
required: boolean
public int equals(Object o);
^
1 error

Easiest way to browse and search Open Source code

Jsourcery  – You are in the middle of coding something and want to see how that functionality is implemented in one  of the open source projects that you know. Then this site is for you. This site has an impressive list of java open source projects to browse through.

If you are looking for a google search like functionality that can search through open source code repositories, then check out these sites,

Two interesting java questions

Q1. Can we write constructors in servlets ?

Ans. Container creates servlet instances using its no-argument constructor.  So the answer is, You can write constructor but, if you write a constructor with arguments, you need to provide a no-arg constructor also.

Q2. Why do we use init method to initialize a Servlet ? Why can’t we use constructor ?

Ans.  B’cose interfaces don’t allow to specify constructor signatures.  This is a bit high level answer. All servlets either directly or indirectly implements the GenericServlet interface.  In other words, you define the rules that a servlet should follow using the GenericServlet interface. But, how do you specify that a ServletConfig object should be passed as argument when creating a Servlet instance. You can’t declare a constructor rule in interface.
You can’t do this,

public interface GenericServlet {

public GenericServlet(ServletConfig sc) {

}

}
So the only way is to define a seperate init method. The name init is arbitrary, just a meaningful name.
public interface GenericServlet {

public init(ServletConfig sc) {

}

}