Tuesday, July 1, 2008

On the nature of things (By Lucretius 94-55BC)

Lovely it is, when the winds are churning up the waves on the great sea, to gaze out from the land on the great efforts of someone else; not because it's an enjoyable pleasure that somebody is in difficulties, but it's lovely to realize what troubles you are yourself spared..

Wednesday, June 18, 2008

A nice haiku from FightClub

worker bees can leave
even drones can fly away
the queen is their slave
- Fight Club

Completeness in Incompleteness

Everyday reminds me of my Incompleteness.
The more I try to complete it, the more incomplete it gets.
But I try and try and try,
Only to realize that the Incompleteness is just a part of my Completeness.

Tuesday, June 10, 2008

Forward Referencing

The following notes are taken from Java Language Specification in reference to forward referencing of variables.

The declaration of a member needs to appear before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:
1. The usage occurs in an instance (respectively static) variable initializer of C
or in an instance (respectively static) initializer of C.
2. The usage is not on the left hand side of an assignment.
3. C is the innermost class or interface enclosing the usage.
Example where it needs to be taken care of

public class ForwardReference
{
int j = i;
int i = 10;
}
Here in this example all the above three conditions are met because i is used in the instance variable initializer, i is not on the left hand side of the assignment and the usage of i belongs to the ForwardRef which is the innermost class holding the variable i.

Examples where it need not be taken care of:

Example1:
public class ForwardRef
{
int j;

ForwardReference()
{
j = i;
}

int i = 5;
}

Here the usage is in the constructor and not in instance varialble initializer or instance initializer so the first rule is violated.

Example2:
public class ForwardReference
{
{
i = 9;
}
int i = 8;
}
Here second rule specified in JLS is violated, so we need not worry about it appearing before it is defined. We should be worried if i is used on the right hand side of the assignment.

Example3:
public class ForwardReference
{
class InnerForwardRef
{
int j = i;
}

int i = 5;
}
Here the usage of i is in a inner class so the third rule is violated, so the compiler will not create a problem for this.

Now we come to a very strange example where forward referencing is allowed..
public class X
{
private static int x = getValue();
private static int y = 5;

private static int getValue()
{
return y;
}
public static void main(String args [])
{
System.out.print(x);
}
}

The code above prints..zero which is quite weird in fact. Here the compiler is tricked making it think that it is a valid forward reference.

Monday, May 26, 2008

Daemon threads in Java

Threads that work in the background to support the runtime environment are called daemon threads. For example, the clock handler thread, the idle thread, the screen updater thread, and the garbage collector thread are all daemon threads. The virtual machine exits whenever all non-daemon threads have completed.

public final void setDaemon(boolean isDaemon)
public final boolean isDaemon()

By default a thread you create is not a daemon thread. All the user applications are generally started off as non-daemon threads. However you can use the setDaemon(true) method to turn it into one.

Thursday, May 22, 2008

Covariant return type

A covariant return type means changing a method's return type when overriding it in a subclass. Covariant return types were allowed in the Java language since the release of JDK5.0. I will try to illustrate the use of covariant return type using the following example.

class A
{
public List test()
{
return null;
}
}
class B extends A
{
public ArrayList test()
{
return new ArrayList();
}
}
Here we can see that the return type of the method test() in subclass B is the subclass of the return type of method test() in the superclass A.

Wednesday, May 21, 2008

Contract between the subclass and superclass

The following is an excerpt from the book 'The Java FAQ' .. "An API (application programming interface) establishes a contract of intent, not just of form or interpretation. To borrow terminology from linguistics and philosophy, an API contract involves both extension and intension: the boundaries of the current state of the world (extension) as well as the intended boundaries for other possible states of the world (intension: possible future implementations). In object-oriented programming, a common source of "possible future implementations" is subclassing from an existing class in an API.
A method defines a contract for any subclass method that would override it; it constrains possible implementations that a subclass could provide. In Java, the bare minimum contract for a method's inputs and outputs is the following:

* A method's parameter list is fixed; an overriding method in a subclass must declare precisely the same number and types of arguments.
* A method's return type is fixed; an overriding method in a subclass must declare precisely the same return type.
* The set of checked exceptions a method can throw (the method's declared exception classes and all their subclasses) establishes an upper bound. An overriding method in a subclass cannot throw any checked exceptions outside of that; it can, however, throw fewer exception types, or even none at all.

Note that the contract on exceptions concerns only checked exceptions; errors and runtime exceptions (that is, Error, RuntimeException, and their subclasses) are always permitted.
If a method, such as Object's toString method, is declared as throwing no checked exceptions, any overriding method you define must live within those bounds. You cannot define your own subclass of Exception and have your toString method throw that. In such a case, if you really need some exception to be thrown, you can resort to a subclass of RuntimeException, which is not checked or constrained by the compiler."

This description basically covers all the rules that a subclass must follow when overriding a method from superclass.

Tuesday, May 20, 2008

What does a constructor do?

The constructor helps initializing the state of the object. So initially the implicit or the defined no-argument constructor of the super class is called so that the parent gets initialized in a proper manner.


One more restriction that is being imposed when a constructor is being defined is that call to any explicit super class constructor must be the first statement of all the constructors. So this might sound like a weird restriction at first but this rule guarantees the parent object to be in a valid state before the child object gets operational. This would help in avoiding the situations like this :


class Date{
public Date(){ date = setDate... }
String date;
}

// what if?
class DateViewer extends Date{
public DateViewer(){
System.out.println("The Date: " + date);
super();
}
}

Another thing that must be kept in mind while dealing with the constructors is that once you define a non-default constructor with non-zero arguments then and there the implicit constructor's definition inserted is removed from the code. So now if you have two classes X and Y such that
class Y
{
Y(int x,int y)
{

}
}

class X extends Y
{

}

Now this will result in a compilation error in the class X..Because the JVM tries to call the super() method while initializing the child object but since there is not implicit constructor for the parent class, this results in a error. Also see this amusing thread on sun forum:

http://forum.java.sun.com/thread.jspa?threadID=731805&start=0&tstart=0

Tuesday, May 13, 2008

About null in Java

In Java(tm), "null" is not a keyword, but a special literal of the null type. It can be cast to any reference type, but not to any primitive type such as int or boolean. The null literal doesn't necessarily have value zero. And it is impossible to cast to the null type or declare a variable of this type.

Friday, May 9, 2008

Implementation of a multithreaded singleton in Java


package yn.graph;

/**
* @author ny
*
*/
public class MultithreadedSingleton {
private static final MultithreadedSingleton singleton = new MultithreadedSingleton();

private MultithreadedSingleton() {
synchronized (MultithreadedSingleton.class) {
//initialize the variables
}
}

public static MultithreadedSingleton getSingleton() {
return singleton;
}

private static class TestMultithreadedSingleton implements Runnable {
@Override
public void run() {
MultithreadedSingleton sgt = getSingleton();
System.out.println(sgt);
}
}

/**
* @param args
*/
public static void main(String[] args) {
new Thread(new TestMultithreadedSingleton()).start();
new Thread(new TestMultithreadedSingleton()).start();
new Thread(new TestMultithreadedSingleton()).start();
new Thread(new TestMultithreadedSingleton()).start();
new Thread(new TestMultithreadedSingleton()).start();
}
}

Monday, April 21, 2008

Does Java pass by reference or pass by value?

A compact answer to this question will be

"Java passes the reference of the object by value".
So what does it mean to pass the reference of the object by value.
It means that if an object is passed to a method, then the object itself can be altered but not its reference. Because the reference of the object is passed by value. For example consider a object O and let the reference of the object O be x. Now when you pass the object O to a method, the VM internally makes a copy of x, that means there is another reference y which points to the same location as x does.
But x >< y. Now this means whenever you pass a object to a method, the object has atleast two references. Thus objects in java can be altered by passing to a method but they cannot be swapped with another object or assigned to some other object or something like that.

Thursday, April 3, 2008

Useful Firefox Addons

Here I would like to mention some of the Addons to Firefox that I find very useful.
1. Many of the people would like to restore their browser session once they boot their personal computer. So that they need not open each and every tab once they start their browser. There are session restoring features in Firefox but they are not upto the mark. So the best session restoring addon according to me is Tab Mix Plus and it can be found at the Tab Mix Plus
2. For those who are into web development there are two addons that I wud like to suggest. The first and the most notable addon being firebug. This addon is available at the Firebug
This addon has a long list of features. But I would like to point out my favorite features. First being the inspect element feature that will enable you to see the html source of any element that you want to locate. For this you need to right click on the element and select the Inspect Element option. Now many people want to look at the contents of the response that has come back and also check whether the request made is proper or not. For this you need to select the Net tab of firebug and then inspect the contents of request and response. One can also view the contents of the XHRs that are being made. Viewing the contents of XHR is a pretty nifty feature of Firebug.
The second addon that is not very popular being Web Developer. This is at the Web Developer. The feature of this addon which is not present as it is in Fire Bug being the View Layout option. This option enables one to view the layout of the page properly. Fire Bug also has this option but not as sophisticated as Web Developer.
3. The third addon being the stumble upon addon which is my favorite addon. Now this addon not only allows you to stumble but also record any pages that you want to record. This is much more useful for me because I visit certain pages and I dont want to loose their pointer at any cost. So as soon as I find any page that needs to be stored I wud mark it as thumbs up. Then later in time I can retrieve the list of pages that I liked and I can easily search for the wanted pages. This addon however is present in the stumble upon home page from where one can obtain and install stumble upon add on.

I will be adding to this list as soon as I find any new and useful addons..

Tuesday, April 1, 2008

Precision Vs Recall

In all the applications involving Information Retrieval one of the main concerns would be to balance Precision and Recall parameters. The general application involves a scenario where a query is submitted by the user and the documents that match the query in the corpus are retrieved using some information retrieval model. Well known information retrieval models include Vector Space model, Latent Semantic Indexing and several other Probabilistic models.

Precision refers to the ratio --> Number of relevant documents retrieved / Total number of retrieved documents.
Recall refers to the ratio --> Number of relevant documents retrieved / Total number of relevant documents.

Now one can observe that Recall will be 1 if one returns all the documents in the corpus but the whole application's performance will be in jeopardy if one returns all the documents in the corpus thus rendering the application useless. On the other extreme is when we return no documents, then the Precision is infinity. But even then the application is unusable because no documents are rendered to the user.
So the balance between precision and recall has to be established in the applications involving the Information Retrieval. Due to the ambiguities in the natural language many irrelevant documents are returned resulting in a text search applications with low precision. One of the main reasons that Google has established its ground as a giant is due to its Page rank algorithm which increases the precision a lot. So while developing the applications one can improve the performance by giving the proper weights to precision and recall as required by the specifications of a particular application.
For example there might be some applications where all the relevant documents need to be displayed irrespective of the total number of the retrieved documents. In this case one needs to give a high weight to the recall parameter while designing the search query. Commercial search engines require a high degree of precision because the number of web pages (each web page can be viewed as a document and the set of all web pages is the corpus) is in zillions. There are several measures like F1 measure in which precision and recall are evenly weighted.