Monday, January 19, 2009

Bits – Eclipse, Java.

In most of our programs, we used to start with hardcode string values and debug or test. If that work fine only we used to move to re-factor the code into more general program. I think that is easy also, because at first we don’t need to worry about other than the logics and necessary API calls. Here is a way to easily construct the strings with eclipse which I normally use when I am writing in Java.
Say for example I want to print some thing like this: “Hello user_name, you are user_age years old”, where user_name and user_age suppose to enter by the user from command prompt.

We will start with following:
System.out.println(“Hello Nimalan, you are 25 years old.”);//hardcode strings
We have to end with this:
System.out.println(“Hello ” + args[0] + “, you are ” + args[1] + “ years old.”);

So, in between the above string we have to put quotation markers and plus signs if we go and edit directly. But with out doing that try out following: 

First move the curser before N of Nimalan and press enter. Eclipse will add necessary quotation marks and plug signs for you. You will get like this: 
System.out.println(“Hello ”+
                                           “Nimalan, you are 25 years old”);
Now do the same after n of Nimalan then you will get following:
System.out.println(“Hello ”+
                                         “Nimalan” + 
                                         “, you are 25 years old”);
Ok now you can replace the “Nimalan” with args[0]. Can’t you do the same for 25 too?
This is just a small example, but this will be very useful in changing hardcode strings into variables, constants or into properties files. Enjoy! :).

No comments: