Saturday, November 8, 2008

Many Public Classes in 1 Java File !!

There is a popular misconception among the beginners that we can have multiple public classes in one java source file.
But the rule is that "we can have atmost one public class and any number of non-public classes in one .java source file". The public class must contain the main method, from where the execution begins. As i see it, this is so that JVM could access and call the main method from outside the class. 

However, there is one exception to this rule. I wrote this blog entry because i came to know about the exception :)
The exception comes when we deal with inner classes. You can have as-many-as-you-want public inner classes in your class. But, it is not desirable as it results in difficult-to-manage code and of decreases its re-usability. 

For example, the following code would compile and run successfully.
>
>  class tryme
>  {
>     public static class A
>   {
>   public void print()
>   {   System.out.println(" Print inside A ");   }
>   }
>
>   public static class B
>   {
>   public void display()
>   {   System.out.println(" Display inside B ");   }
>   }
>
>  }
>
>  public class test
>  {
>   public static void main(String[] args)
>   {
>   tryme.A ob = new tryme.A();
>   ob.print();
>
>   tryme.B ob2 = new tryme.B();
>   ob2.display();
>     }
>  }
>

Of course, the file must be named test.java. It compiles and produces the following output.
>
> Print inside A
> Display inside B
>

Another way of using public inner classes is by importing them in your program like
import packagename.tryme.*;
and then use classes A and B as they you like.

But, the recommended style of programming discourages use of more than one public class in one java file. Also, such behaviour is not supported on all compilers. Infact, for maximum optimization (by compiler) it is recommended that you should write one class per java file.

Comments and corrections are welcome. :)

Monday, November 3, 2008

Static Imports in Java

Java as a language, continues to evolve and amaze developers and students alike with new innovative concepts and features. Java 5 is a major release which includes various additions like Generics, Autoboxing, Enumerations, Enhanced for-loop, Static Imports, Var-args, Serialization, Covariant return types, Annotations etc. to name a few.

Discussing each one of them would span multiple blog entries. So let's start with Static Imports as of now. Hopefully, I will devote an entry to each one of these in the coming days. :-)

Before I begin with my explanation of Static Imports, I would like to ask you something..........
Are you sick and tired of using fully-qualified static members of some other class (can be a library class too) in your program such as Math.PI whenever you want to use 3.141592653589793.... or Math.sqrt() when you need to find out square root of any number ??

Of course, these are simple examples which are short and easy to remember, so they might not seem a headache. But things can get quite complex and it can turn out to be burdensome to repeat a long fully-qualified name time and again in your code. 
Static Imports come to your rescue. :-)

With the help of Static imports, you can very well use the static members of any other class (to which you have access) like the members of your class i.e. there is no need to fully qualify the name using package name and class name 

Normally an import statement would look like 
import packageName.className.memberName;

A static import would just add the word "static" after import 
import static packageName.className.memberName;

An example would make it more clear....

>  import static java.lang.Math.*;
>  public class tryme
>  {
>    public static void main(String[] args)
>    {
>      System.out.println("Square root of PI is "+sqrt(PI));
>    }
>  }

The advantage lies in the fact that you dont have to type Math.PI....a simple PI would work....
I agree that its a small feature and not as important as other features that Java 5 has introduced or enhanced, but then as they say "Boond boond se hi gaadha badhta hain"

Limitations :
It applies to only static members, not to instance variables 
It can make code un-readable and difficult to debug, if used unnecessarily and in excess

Application:
Mostly it is used to discourage the technique of declaring constants in interfaces and then implementing those interfaces by your class. An interface is a part of public API and it defines services that your class should provide, and so it is not recommended to make constants a part of your public API. Instead, it is always preferable to use Static Imports.

Thursday, October 30, 2008

equals() & hashcode() relation in Java

I assume that you have an idea about equals() and hashCode() methods present in Object class. What you may not know, is that a relation(or perhaps a contract) exists between them.

Remember the following points:
  • If you override equals(), then you must override hashCode()
  • equals() & hashCode() must be evaluated based on same fields
  • If two objects are equal using equals() then they must have same hashCode() value, but vice-versa need not be true.
Since hashCode() value of an object determines how it will be stored and located when it is used with collections like HashMap & HashSet, so it becomes necessary that equal objects must have same hashCode() value. 
So, implementing hashCode() when your program deals with collections become really important for reasons such as efficiency and correctness.

To give an analogy to this hashing process, imagine a sequence of buckets to be your hashtable. Now, to retrieve an element, we do
1. Locate the right bucket using hashCode() value
2. Search the bucket for the element using equals()

Now, if two equals objects (which would be present in one bucket) have different hashcodes, you would never be able to retrieve them back correctly, because you are not looking in the right bucket. 

Although, it is legal to have same hashCode() value for different (read unequal) objects, but it will hurt the efficiency as it would make it a bit slow to locate the correct bucket.

Also, if two objects have different hashCode() values, then they must not be equal using equals() i.e.
if x.hashCode() != y.hashCode() then x.equals(y) == false.

This also helps in clearing a popular misconception about hashcodes that they identify an element uniquely. They can be used as an object ID but they are not necessary unique.

Still interested in more details, read this article to get more insight. :-)

Monday, September 8, 2008

Google's Chrome - A Review

If you are here or if you are an aware IT professional/student, then there is no way that you haven't heard of Google's Chrome

For those, who still do not know what Chrome is, it is an open-source web browser that has been built from scratch by Google. Another feather in their cap, this browser promises a lot in its beta version that has been released for Windows Vista/XP SP 2 so far. The Mac and Linux versions of Chrome are under development and will be released soon.

Chrome offers you a world of rich features to play with. The major features are
  • OmniBar - The URL box in Chrome is called OmniBox as it shows you pages based on your web history, your bookmarks, popular searches, results of Google Suggest as you type words in the URL box. OmniBox can also be used to add a bookmark quickly. Thus, there is just "one box for Everything". Can be annoying sometimes, but if you do not delete your browsing history often, it tends to settle down the dust and offers you exactly what you want.
  • Incognito Mode - By default, Chrome saves all your web history on the local system and uses it for several purposes. The web history could be seen later also by anyone using your system. So, if you do not want your browser to keep a record of what you are surfing, then you can open a new window in Incognito Mode and the browser would not save any cookie related to that page. Looks useful, but there should be an option to configure Chrome to change this default behaviour of saving web history because some users might just not want to save all work they do because they work on systems that many people share.
  • Crash Control - Google claims Chrome to be more stable and safer than a lot others as a crash that occurs due to one tab would not effect other tabs of the same window. Traditionally, a browser creates a new thread when a user creates a new tab in a window. Chrome differs from the ordinary by creating a new process per tab. This means that separate data structures, more memory usage for each tab you open but that also means no dependence between various processes (or tabs). Google claims that it won't affect speed as much as we think it will because Chrome is based on WebKit, an open source rendering engine which uses memory efficiently. My experience with Chrome begs to differ with what Google has to offer. On my system, Chrome has CRASHED twice within a week of its usage and the fact that I was not running heavy web applications at that time is really scary. Also, I missed the restore session option that I have with Firefox.
  • Speedy - It is definitely faster than its counterparts like FF and IE. Firstly, it does not takes much time to open up and also the browsing experience for users with a slow net connection(like me) has improved with Chrome. Thanks to the new Javascript Engine V8, that Google has developed for the browser.
  • Chrome Task Manager - I do not know if such a facility exists with Firefox 3 or IE 8 beta version but it surely helps you to understand which tab is going "sad". It really treats each tab and plugins within a window as a separate process and shows the amount of memory used by each one of them.

Several things that don't work for me includes crash control and inability to scroll up when i use the scroller of my laptop. However, scrolling down works very fine. It gets a bit frustating not being able to scroll up and using the keyboard to achieve the effect.

The best thing that I like about Chrome is the comic book that they have released. The comic book proves the saying that "A picture is worth a thousand words". Its not only simple and easy to gather concepts but also entertaining, even for a layman like me, who is unaware of functioning of a web browser.

One thing that I fail to understand about Google chrome is that inspite of being Open Source, it is released for Windows first(something that can never be open source) and the Mac & Linux versions are still in the making...

It would have been definitely better, had Google released it for all OS's at the same time.
Perhaps the product was such that, Google could not hold it any longer after working so hard to develop it. They were desperate to release it and see the feedback and wild reactions. Still they wil miss out the feedback from the real open source community, which i believe do not use much of windows :-)

But one thing is for sure, Chrome is here to stay, no matter how many times it crashes....I won't stop using it :-)
And if you still haven't tried it yet, go here and download it right now. Happy Chroming !!