Monday, January 29, 2007

Featured in member spotlight at ITVidya

Last week featured me in their member spotlight. Many thanks to Ajay, and the team at

Notes: This text was originally posted on my earlier blog at

How do exceptions work?

Now let us understand how Exceptions work. The code shown below is a simple program that shows how to use Exceptions. Listen to the audio below as you view the code.


public class LearningExceptions {
  public static void main(String args[]) {
    LearningExceptions le = new LearningExceptions();
    System.out.println("Hello, this is a test program to
      understand Exceptions");
    try {
      System.out.print("Please enter your name: ");
      String name = le.getName();
      System.out.println("Hey " + name + " how are you doing?");
    catch(IOException ioe) {
      System.out.println("Looks like the standard input
        stream does not like you!");

  private String getName() throws IOException {
    BufferedReader br = new BufferedReader
      (new InputStreamReader(;


Now let us compare how error handling is done with and without Exceptions. The PSEUDOCODE shown below has two methods: the first one is called aFunctionWithoutExceptions(), and the second one is called aFunctionWithExceptions(). As their names suggest the first method does error handling, the old way, by inspecting return values, and the second method does error handling with Exceptions.

aFunctionWithoutExceptions() {

aFuntionWithExceptions() {
  try {
  catch(ExceptionTypeA e1) {
    handle the exception
  catch(ExceptionTypeB e2) {
    handle the exception


When inspecting return values: 

  • We have to check for the return value after every function call. This increases code and also reduces readability of the code .
  • Error handling code is interspersed with program code.
  • Checking for the meaning of an error code will usually require long if...else statements.

When using Exceptions:

  •  We do not have to inspect the return value after every method call. We just invoke the method and if an Exception is thrown, control will automatically transfer to the appropriate Exception handling code.
  • Error handling code is in a distinct region (the catch block) and is not interspersed with program code.
  • We do not need to specifically check what an error code means. Since we throw unique Exceptions for unique problems, control will automatically be trasnferred to the appropriate catch block.
Note that we have two catch blocks in the second method. Whenever the statements in the try block are capale of throwing multiple Exceptions, we must catch all of them, either in a generic catch block that catches the superclass of all Exceptions "java.lang.Exception", or in individual catch blocks. It is advised to adopt the latter style.

Notes: This text was originally posted on my earlier blog at

Wednesday, January 24, 2007

Blogging for learning professionals

Today Ajay and me completed a workshop on New Media for students at SCIT. I absolutely love talking about the potential of New Media, specifically blogging, and podcasting. Now it's not that blogging and podcasting are going to change the world, but the underlying concept of participatory media WILL. Blogging is a mechanism to achieve the vision of participation. Maybe over time it will evolve, maybe it will be replaced with something else, but the vision of grassroots participation is so powerful, that it cannot and should not be ignored.

Here are the slides from the presentation, followed by links to some blogs and websites we spoke about. 


UPDATE: If you live in Pune or can travel there, be sure to come to BlogCampPune. It is going to be the first BlogCamp in Pune, and I'm sure it will be a great event. Many thanks to Tarun for taking the initiative to organize it.


  • Stephen Downes' website on learning... this is a must read for those who believe that the current teaching scenario needs a lot of improvement, and would like to strive for a system of learning which will enable each person to rise to his or her fullest potential.
  • Joel Spolsky's blog. He writes about many issues related to computing, software development, and sometimes whatever he feels like. His blogs are almost always very insightful and well written.
  • Steve Pavlina writes an excellent blog on personal development for smart people.
  • Guy Kawasaki would like to change the world 25,000 people at a time through his blog. He writes about many things, and always in a very engaging and insightful manner.
  • Jon Udel was one of the very early bloggers.
  • Kathy Sierra writes an awesome blog on improving the user experience of your product. It inspires it's readers to excel.
  • The Long Tail is a blog that evolved into a book (or maybe a book that started of as a blog).
  • Jonathan Schwartz, Sun's CEO also blogs.
  • Some blog feed readers: Google reader, and Bloglines.
  • Ranjan Jha, my student from 2 years back at SCIT. I enjoy reading his blog a lot.
  • Blog feeds: RSS, and Atom.
  • All about Blog linkbacks.
  • Free blogging services: Wordpress, and Blogger.
  •, a portal for the IT knowledge, networking, and opportunities.
  • Some paid blogging services: Typepad, Radio Userland, and Square Space.
  • Free blogging software: Movable Type, WordPress, and Roller Weblogger.
  • Search blog content on Google blog search and technorati.
  • Some blogging best practices and ethics from Rebacca Blood.
  • A blog/podcast on educational technology and new media in learning.
  • A teacher's blog. Very well written, and insightful. He often writes on his experiences of using blogging in the classroom.
  • If you are already suffering from information overloaded, you might want to go here.

Notes: This text was originally posted on my earlier blog at
Here are the comments from the original post

AUTHOR: Tarun Chandel
DATE: 01/27/2007 02:26:19 PM
Hi Parag Sir

A very good presentation, it's really important to realize that something very interesting is changing the people learn and share. It's great that SCIT had such a good workshop, I remember that you were the one who introduced me and Ranjan to blogs and to podcasts. For me these two has been major source of learning in past one year.

It was really good move from you to bring Ajay from IT Vidya to SCIT, as it always inspiring to listen from the people who have actually done something good in the particular field. I am sure that we will see a lot more SCITians in the blogosphere.

Ajay is a very good speaker, I met him at BarcampPune2, I liked the way he presented in a simple manner a very important thought, "How blogging can be helpful?" That got me thinking and I was planning to conduct a <a href="">BlogCamp</a> in Pune. If the idea interests you do get back to me so that we can take this idea further. I will also be discussing this idea with Ajay and let's see how he responds.

DATE: 01/29/2007 07:10:27 AM
Hey Tarun,

I am glad I was able to inspire you and Ranjan to start blogging. I too have benefited in many ways since I started blogging.

I will be glad to help out in organizing BlogCampPune.


Monday, January 22, 2007

Why does Java support exception handling?

Here's a nanocast on why we should we use use exceptions to handle error conditions in programs. I hope you enjoy it :-)

This is the first episode in a multi-part series on Exception handling in Java.

DATE: 01/23/2007 10:24:36 AM
Hi There,

Greetings and Wish you a Happy New Year. I am following your website for the past couple of months and I liked it very much.

Are you planning to put the mp3 version of this series as well on the website? It will help the users to load it to their mp3 player and listen to them.

You are doing a great job.
DATE: 01/24/2007 03:26:09 PM
Hi Azagu,

Thank you for your kind words and a very happy new year to you too. Most of the mp3's heavily depend on some code or an example also posted as part of the blog post. I am not sure if the mp3 will be very useful independantly. Also, once I make them downloadable, my hosting bandwidth requirements will increase significantly, and I am not sure if my current plan will support that. I am talking to some people about sponsorships. Once that works out, bandwidth will not be an issue, and I can make a lot of material available for download as a podcast.

I have also been thinking about how I can improve the readers experience and help them understand programming best practices in a better way. After some thoughts I feel that these MP3's are a bit limiting because you have to also look at the accompanying code sample.

Very soon I hope to start a series of screencasts, which will show code being written in an IDE along with an audio explanation of the code. I also have plans to record my dojo sessions and upload them as 'Flash' videos.

Thank you for your comments... feedback helps me understand if I am able to help people improve their skills... so keep the feedback coming and also suggest the kind of samples you would like to see on the website in future.


Friday, January 19, 2007

JDBC transaction rollback

We are advised to rollback a JDBC transaction in the catch block that handles SQLException, just as shown in the code below. But what if a runtime exception is thrown while after midway in the transaction? Control will never go to the catch block and the transaction will never be rolled back.


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class UnderstandingJdbcTransactions {

  public static void main(String[] args) {
    Connection conn = null;
    Statement stmt = null;
    String jdbcurl = "jdbc:derby:testdb;create=true";
    try {
      conn = DriverManager.getConnection(jdbcurl);
      stmt = conn.createStatement();
      int rowsPopulated1 = 
        stmt.executeUpdate("INSERT INTO PEOPLE VALUES
         (01, 'Raja', 'Chandrashekhar')");
      int rowsPopulated2 = 
        stmt.executeUpdate("INSERT INTO PEOPLE VALUES
         (02, 'Mike', 'Russell')");
    catch(SQLException sqle) {
      System.out.println("Caught Exception: " 
      try {
        System.out.println("Transaction rolled back");
      catch (SQLException e) {
        System.out.println("Could not rollback 
          transaction: " + e.getMessage());
    catch (ClassNotFoundException e) {
      System.out.println("Could not find the database 
        driver class");
    finally {
      if(conn != null) {
        try {
        catch(SQLException sqle) {
          System.out.println("Could not close 
          connection: " + sqle.getMessage());
There are two ways to handle this issue. The first is to explicitly set a flag in this class if the transaction commits. In the finally block we should check the flag. If it has not been set, it means that the transaction could not be commited and must be rolled back. Another way is to catch 'Exception' after 'SQLException'. If a runtime exception is thrown we will handle it in the catch block by rolling back the transaction and rethrowing the RuntimeException.
What do you think? Is this a workable solution? Which os the two approaches would you favor? 

Monday, January 15, 2007

Coding conventions - class and method structure in Java

It is very important to follow a consistent coding structure in classes and methods. Following a consistent structure will increase the readability of your programs. Very often companies have their own set of guidelines for namng and coding conventions. If the company you work for has it's own standards then you should follow those. All team members should ideally adhere to the same standards to make the code more readable. If everyone follows their own individual standards, the developers who have to maintain the code will find it very difficult to understand the code, as they navigate from one class to another. It is like driving on a street where everyone drives on the left till you reach a stop light, after which everyone is driving on the right.  Most people will manage, but it will be difficult and slow.

I have shown a simple class below with all the elements that a class usually comprises of. Click on the play button to hear an explanation of the class structure.

01 public class ClassStructure {
02   //we first declare constants
03   public static final int MAX_VALUE = 10;
05   //then public attributes
06   public String someString;
07   public int someValue;
09   //then private attributes
10   private String name;
11   private long salary;
13   //then constructors
14   public ClassStructure(String name) {
15 = name;
16   }
18   //then public methods
19   public void parseClass() {
20     parseElement();
21   }
23   protected void updateSalary() {
24     //do something
25   }
27   //then private methods
28   private void parseElement() {
29     //do something
30   }
31 }

Notes: This text was originally posted on my earlier blog at
Here are the comments from the original post

DATE: 01/16/2007 05:09:54 AM
Hi Parag,
that was a pretty good introduction.Only thing i had to add is that i think we should be declaring unmodifiable attributes as final.For example in the sample attribute "name" could be declared as final as it is not getting updated after being initialized in the constructor.

DATE: 01/17/2007 05:34:29 AM
Hey B.M.
That is a good suggestion.

AUTHOR: Supriya Shinde
DATE: 02/02/2007 02:16:49 PM
Hi Parag Sir,
Being a beginner readability forms an imporatant part for understanding the codes. But, i would also like to know if for IT audits there are some particular or standard conventions that are used for the auditing purpose. That is, on what basis are the codes exactly audited. Are these conventions important for auditing purpose or only for readability convinience?

AUTHOR: Mitesh Desai, SCIT
DATE: 02/02/2007 02:20:06 PM
Hello sir,

I would like to add upon your coding convention that we can also have conventions for public and private variables and objects. like we can have following variable names:

if x is an object of a class: - o_x
if x is a private variable: - p_x
if x is a public variable: - m_x

we can have similar conventions for more efficient and readable codes.

DATE: 02/02/2007 05:32:34 PM
Supriya, these conventions are used purely for readability. Audits are done on various factors, and code conventions may be one of them... however the primary reason is to make the program more readable for those who will maintain it.


DATE: 02/02/2007 05:37:00 PM
Mitesh, using special variable names to add extra meaning to the variable should be avoided. In fact many people prefer not to do that because if you change the variable from let's say protected to public, you must change the name also. This can break a lot of programs that depend on that name. We should avoid adding metadata to variable names.


Friday, January 05, 2007


I just heard a podcast from Podcast Academy by Kevin Crossman on how to produce podcasts on a low budget. Overall a good podcast, with some useful links:

The Java Classpath


Many developers who are new to Java often have trouble with the CLASSPATH. It may seem complex, but once you understand the underlying concept, it is not difficult at all. 

If you have programmed in C++, you will probably know that the PATH environment variable is used to locate dependencies. However, Java uses the CLASSPATH environment variable to locate dependencies. Take a look at the program below.

1 public class StudentRegistrationSystem {
2   public static void main(String args[ ]) {
3     ...
4     edu.scit.studentreg.Student st =
5       new edu.scit.studentreg.Student();
6     ...
7   }
8 }


Notice that this program needs a class called 'Student'. The compiler as well as the runtime will need the Student class. The question is, how do they find it? They use the CLASSPATH environment variable.

The CLASSPATH is a list of directories, zip files or jar files.

Let us now understand how a JVM locates a class using the CLASSPATH. The Java runtime iterates through all entries in the CLASSPATH and searches for the class file in every directory, zip or jar file until the class is found. If it is not found, a ClassNotFoundException is thrown. If we put a class file in a directory not listed in the CLASSPATH, then as far as the Java runtime is concerned, it does not exist.

But wait, this is not the full story. Given a particular directory in the CLASSPATH, how does the JVM locate a class that it is searching for? Does it look for the class only in that directory, or does it look for the class in all sub-directories also? To help the JVM, we must follow certain conventions. I am assuming that you are familiar with the concept of packages in Java. If you are not, then you can read a simple explanation at The convention used is to match the directory heirarchy in which a class file is put, with the package name of the class.

Let us understand this concept with an example we have used above. Where will the runtime find the class edu.scit.studentreg.Student? When the JVM needs to locate the class edu.scit.studentreg.Student, it will look at the first entry in the classpath. Suppose it is c:/scit/classes. The JVM will now try to locate the class by zeroing in to the appropriate location based on the package name of the class. First it looks for a directory 'edu' in c:/scit/classes, if it finds the directory then it looks for 'scit' inside 'edu' and 'studentreg' inside 'scit'. Once in the 'studentreg' directory it looks for a file called Student.class. If the JVM finds the file using this algorithm, it is loaded, othewise it goes to the next entry in the classpath and tries to locate the file using the same mechanism. If the file cannot be found in any of the directories specified in the classpath, then a ClassNotFoundException is thrown.

The animation below explains how the JVM locates a class. Right click on area below and select "play" to start the animation.


So now you know, if you get a NoClassDefFoundError, it is because the Java runtime cannot locate your class file from entries in it's classpath. If the CLASSPATH variable has not been set, the current directory is used as the only classpath entry. If it contains any entries, then the current directory will not be considered part of the classpath, unless it is explicitly added.

Recommended Books:

Monday, January 01, 2007

Moving from 2006 to 2007

In 2006 I did a lot research on elearning, instructional technology, and psychology of learning. After much deliberation I came to the conclusion that learning is all about taking in new information, reflecting upon it, practicing it, conversing with others and then sharing. This entire process not only strengthens the learners own understanding of a topic, but also helps the community by knowledge sharing.

Learning can be very effective when done as a conversation, rather than a monologue (with either a teacher or a book). Which is why some experts suggest that you should talk to your book while learning, by making notes. Having a conversation helps the learners derive knowledge rather than just having it spoonfed to them.

New media technology gives us an entire new way to have these conversations, by blogging and podcasting. I have written here, and here about the benefits of blogging. In the spirit of enabling learning through conversations, I created a website - Adaptive Learning Solutions, in Jne 2006. For most of 2006, I posted articles on learning and how the internet can be leveraged for information and to create a personal learning environment. This was to create a base for the readers to understand how to effectively use the net. Now the time has come to focus on posts for the people I set out to help - senior students of computer science and fresh employees working in software development. In 2007 you will mainly see articles that explain best practices in software design and development in Java. This will be the primary focus, however I will from time to time also write about Agile methodologies, and extreme programming. I hope to publish at least 2 posts every week and even start a screencast, which will be a video of a program being written in Eclipse, while I explain principles and best practices of software development.

All of you who would like to improve your software development skills are welcome to visit the website, and post your questions, comments, and suggestions.

Wishing everyone a very a happy and prosperous new year.

New Year Resolutions

ok so new year resolutions are meant to be broken. This year I resolve not to break my resolutions. So I'll keep it simple.

  • I will exercise everyday
  • I will publish 2 blogs and 1 podcast every week on my elearning website
  • I will prepare for all workshops and teaching events well in advance... no more last minute preparation
  • I will utilize my time judicously
Well, this much I am sure I can manage.

final Methods In Java

  • what are final methods
  • benefits
    • design
    • efficiency
      • no choice to be made for overriden methods
      • can be inlined
  • making methods final for efficiency is not a good idea...
    • limiting without significant gain
    • example Vector... and then the new collection classes

String vs. StringBuffer vs. StringBuilder

We all know that using StringBuffer to perform String concatenations is far more efficient than conctenating strings using the '+' operator. Since JDK 1.5 a new class called StringBuilder has been added. StringBuilder is just like StringBuffer, except that it's methods are not synchronized. You should use StringBuilder to improve your performance if you do not need thread safety.

Shown below is an example that concatanates 10000 strings using the '+'  operator, StringBuffer, and StringBuilder, and prints the operation time in nanoseconds. The ability to get time in nanoseconds is another feature that was added in JDK 1.5.

package biz.adaptivesoftware.examples.string;

public class StringConcatanations {
  public static final int MAX_ITER = 10000;
  public static void main(String[] args) {
  public static void concatenate() {
    System.out.println("Concatanating using the + operator");
    String s1 = "";
    long s1Time = getNanoTime();
    for(int i=0;i<MAX_ITER;i++) {
      s1 = s1 + "abc";
    long e1Time = getNanoTime();
    System.out.println("Time: " (e1Time - s1Time));
  public static void concatenateWithStringBuffer() {
    System.out.println("Concatanating using StringBuffer");
    StringBuffer sb = new StringBuffer();
    long s2Time = getNanoTime();
    for(int i=0;i<MAX_ITER;i++) {
    long e2Time = getNanoTime();
    System.out.println("Time: " (e2Time - s2Time));
  public static void concatenateWithStringBuilder() {
    System.out.println("Concatanating using StringBuilder");
    StringBuilder sBuilder = new StringBuilder();
    long s3Time = getNanoTime();
    for(int i=0;i<MAX_ITER;i++) {
    long e3Time = getNanoTime();
    System.out.println("Time: " (e3Time - s3Time));
  public static long getNanoTime() {
      return System.nanoTime();



Concatanating using the + operator
Time: 744597428
Concatanating using StringBuffer
Time: 1685131
Concatanating using StringBuilder
Time: 1317206
As you can see, if you do not need thread safety, StringBuilder yeilds the best result, followed by Stringuffer, followed by the '+'  operator. However, if you do need thread safety, then StringBuffer is your natural choice.
Recommended Books:

Notes: This text was originally posted on my earlier blog at