Tuesday, July 31, 2012

Eclipse Starting with a Specific workspace


As I am working for different client at one given point of time, so sometimes it becomes cumbersome to switch the workspaces for different clients. Even sometime it is mandatory to open more than one eclipse and work with them in parallel. So managing them and switching between workspaces not only consumes times but also irritates.

I wanted to tackle this issue by creating different shortcuts for each workspace. Eclipse has easy solution for my problem.

To create shortcut to open eclipse with a particular workspace follow the steps mentioned below.

1. Browse to eclipse installation folder and right click on eclipse.exe.


2. You will see a shortcut at your desktop. Open the shortcut properties menu which pops up a shortcut properties.

3.In the target add the following text -data <YOUR_WORKSPACE_LOCATION>


4.Click on OK.

Now once you click on the shortcut, it would not prompt you to select the workspace and it will open the workspace associated to the location specified.
Now you can create as many as shortcut you want and refrain from switching between the different workspaces.

Sunday, July 29, 2012

Enable/Disable Quick Launch Bar in Windows 7

This article is just a memory references. Whenever I install/upgrade windows 7, I miss quick launch from my system. So I end up searching from Google and going through different unsatisfactory/non-informative links.

In this article, enabling quick launch has been demonstrated well.
http://www.mydigitallife.info/how-to-enable-or-disable-quick-launch-bar-toolbar-in-windows-7/

In most of the other articles people are selling their own software which is not required to enable and disable the quick launches. Beware of such people and use this article.

Saturday, May 12, 2012

Remote Debugging

Coding is simple, but it get tougher when something does not work as our normal human mind expects it to work. We wonder in woods, we shut the mind and go out for smoke, then we go to seniors to test their potential to attack and solve the problem and if every door closes on you then debugging comes to rescue each of us.
Now problem and tension aggravate when we could not find any issue on local machine whereas same code bombs at production environment. Oh god, no-one can really rescue the server and customer as some witch has modified the computer language to perform it abruptly.
Again we have rescuer. Different IDE can rescue us from this situation by using remote debugging. Local debugging is not as cumbersome as remote debugging. It takes few configurations to enable remote debugging.
Lets look into remote debugging configurations.

Configure Eclipse Project for Remote Debugging

Open Debug configurations under Run menu.

This will open a dialogue as shown below

Right click on REMOTE JAVA APPLICATION and click on new. It will open an editable box to configure properties for remote debugging.

Enter the name of the debug configuration. Do not forget to change the Host and port properties. Make the changes and click on apply button. Make sure to remember port number as this port number will be used at the time of configuring java application at server.

Apply the setting and closed the window.

Configure Java Application Running at Server
Actually you do not need any configurations. To run the java application you need to pass following JVM Options.
-Xdebug -Xrunjdwp:transport=dt_socket,address= {PORT_NUMBER_PASSED},server=y,suspend=y

 If earlier the command used to run java application was
java testJava
Now it will be modified to
java testJava -Xdebug -Xrunjdwp:transport=dt_socket,address={PORT_NUMBER_PASSED},server=y,suspend=y

Explanations
All options mentioned above will decide how application will run in debug mode.

Make a note of following points below:
* jdwp- (Java Debug Wire Protocol) this protocal enable your debugger(eclipse) to debug remote VM.
-Xrunjdwp: enables the jdwp for u
* -Xdebug  will start java application in debug mode .

Remaining jdb parameters will specify how application will run.
* suspend = y - Applicaion will not start until eclipse remotely connect to it.
* suspend =n - Application will start normally and it will stop at breakpoints
* transport = dt_socket will instruct jvm that debugger connections will be made through a socket
* server = n Attach to the debugger application at the specified address.
* server = y listen for connection at this address.
* 1044 is default port, this is transport address for connection.

This was simple but it may take some time to configure the application if you are running it for the first time. Have patient and try again it will work. There is not anything else you need to do. Configuring remote application has troubled me in the past and gives scare now also. But believe it is not rocket science.

Sunday, December 18, 2011

Static Block of a Class

This post intended to be a quite quick. So let's begin. Could you tell me the output of the code written below?


public class EmptyClass {

static{
System.out.println("Hello World.");
}

}

There can be following options
A. It will not compile.
B. It will compile but it will not run and it will just print exception.
C. It will compile and it will not run but it will print "Hello World" and then will print the exception.
D. It will compile and Run without issues.

After seeing the choice, answer looks quite simple. Is not it?
Anyways lets analyze.
A. It will compile as static blocks are allowed in java and java does not force you to write main method in each and every class. So there are not any issues while compiling the class. So A is not the right option.

B. It will not run, true. As java says, there should be main method to run an application. There is not any run method is the application. But there is a static block in the application. What will happen to this static block? This options seems to correct but puzzle has not completely solved yet. Lets move forward and see if B is correct or there is any other better option available.

C. We accept it will compile but it will not run as main method is not available in the class or JVM. But as java say, before as soon as it loads any class in memory it executes all its static blocks first. So to run the application class will be loaded into the memory so static block exists in the class will executed which in turn will print "Hello World". So it seems to be most appropriate answer.

D. Do we have any scope and requirement left to discuss last options. No

I learnt this lesson while discussing few basic java questions with my friend. Nice but tricky is not it... Anyways will stop here. B bye.

Tuesday, December 13, 2011

Problem with Class Downcast

Sometime I think, I have gained a lot of knowledge in Java and I know lot of things in Java, but once in a while Java keeps pushing my believes to the corner and demonstrates it's superiority. Most of times it is basic java which deceives me. Here is my story.

Today one of my colleague asked one question and I did not have any answer for his question. The issue in concern belongs to the program written below.


class SuperClass {

void display(){
System.out.println("SuperClass Display.");
}

}

class SubClass extends SuperClass{

void display(){
System.out.println("SubClass Display.");
}


public static void main(String[] args){
SuperClass superClsInstance = new SuperClass();
SubClass subClsInstance = (SubClass) superClsInstance;
subClsInstance.display();
}

}

In this case I assumed downcast should happen without any issues and it should print message based on object instance. So in this case subClsInstance is referring to Object of SuperClass and it should print message mentioned below.
SuperClass Display

But no. It is not so simple.

It will throw ClassCastException. Heck Why? What have I done which made it throw such stupid and merciless exception? I am devastated and I do not even know basic of DownCasting, shame on me a 5 year experience java developer do not know such small thing. Anyways let me find out the reason for this behavior.

Hmmm, Interesting na.... I always knew that I am not very good in java and google and Sun have proved me right. As per the information available downcast is possible if and only if object created is a type of Class reference being downcasted to..

Lets take few example... Dog is an animal and An animal is dog only if it is a Dog. If you write same thing in the code so it would be...

Animal ani = new Dog();
Dog dg = (Dog) ani;

So in example listed above, Dog is an animal and it will down cast without problems as code is saying Dog is Dog...


Animal ani = new Animal();
Dog dg = (Dog) ani;
So here in example listed above, here Animal is an animal and it will not down cast as code is saying Animal is Dog...It can not be, we do not have information about Animal. This can be some other animal so Java can not assume anything. It will say that it does not have any idea about this animal so Buzz off.

In our case same thing is happening.We have created an object of SuperClass and asking it to tie up with SubClass. Java says no, do not bog me out with such stupid things and take care of your code better.

Oops java is right and I am wrong. Cool then I learnt something today and shared with you all. Hope you will learn and will not cause such stupid problems in code and will not screw up your interview. 


PS: Stay away from downcasting it is not only but also venomous and code safe.

Tuesday, October 4, 2011

Override Annotation JDK 5 v/s JDK 6

Sometime problems are way beyond your understanding and you could not find the solution for them.

Problem 1

I faced one such problem while I was working on eclipse and JDK5. I created a derived class extending the abstract class. Following is the definition of my abstract class.


public abstract class test {
public abstract void unimplementedMethod(Object[] params);
}

I overrode my abstract class in the class mentioned below.

public class ImplementedTest extends Test{
@Override
public void unimplementedMethod(Object[] params) {
// TODO Auto-generated method stub
}
}

Eclipse was showing a red around the method I had implemented and it was displaying error mentioned below. 
The method unimplementedMethod(Object[]) of type ImplementedTest must override a superclass method

As I see I have not done anything incorrect, I took the exact signature required and pasted in the derived class. After couples of hours of brain storming I found out a import definition of Object. 

import org.omg.CORBA.Object;
public class ImplementedTest extends Test{
@Override
public void unimplementedMethod(Object[] params) {
// TODO Auto-generated method stub
}
}

So how did It manage to sneak into my class? Sometimes eclipse assist you to add required import statements. This time also it appended the import statements, but it appended one additional statement which was not required, and to figure out such a small thing( From the code of 2k lines) it took hours of efforts.

Problem 2
In JDK5, @Override annotation was not working for me. I had an interface and one of my class was implementing the interface.

public interface Test {
public void unimplementedMethod(Object[] params);
}

Class implementing the interface is as follows:

public class ImplementedTest extends Test{
@Override
public void unimplementedMethod(Object[] params) {
// TODO Auto-generated method stub
}
}

Eclipse shows the error mentioned below:
The method unimplementedMethod(Object[]) of type ImplementedTest must override a superclass method

If I remove @override from here it works fine.
If I change my JDK to JDK6, it works without showing any error.
If I change Test interface to test abstract class, it works.

public abstract class Test {
 public abstract void unimplementedMethod(Object[] params);
}

Class implementing the interface is as follows:

public class ImplementedTest extends Test{
@Override
public void unimplementedMethod(Object[] params) {
// TODO Auto-generated method stub
}
}

It works fine. This was non-understandable behavior along with sun has not provided any information about such behavior.

But this behavior has been encounter by different individuals and according to them, in JDK5 when you are implementing the interface then JDK5 do not understand it is override and @Override annotation does not work whereas when you are overriding the method from other class then @Override annotation work without any problem. This confusion was removed later in JDK6. In JDK @override works for interface and general classes.

Source of Reference:

Thursday, September 22, 2011

Eclipse/ANT Error Specified VM install not found



My company provided me new laptop and happily I moved from my old rusted desktop to new shining, powerful and portable laptop. Everything was copied without problem and I started working. But is not it strange to see everything working perfectly fine? I was stunned but happy as well. 

I started using the installed application. Eclipse was working fine until I tried building (Using ant) my application. Ant showed me a scary popup displaying "Specified VM Not found..." 



Simple solution, there is JDK/JRE problem with the system. Correct the JRE and JDK of the project. I did, but it did not work. I googled and found following 2 solutions.

You might even face this problem when you upgrade ant plug-in.

Solution 1
Remove the file which stores build information about the project and restart the eclipse. You can find the respective file in "${PROJECT_WORKSPACE}/.metadata/.plugins/org.eclipse.debug.core/.launches/${PROJECT_NAME} build.xml.launch"

Solution 2 (Location and Screen Shot may differ for different Eclipse Version. Following screen shot and paths are valid for Eclipse Version 3.7)

Go to RUN->External Tools ->External Tools Configurations… 


It will open console below. Select your build.xml(in my case it is abc build.xml). Move to JRE tab. 



Select the appropriate JRE.



Apply the changes and run the build xml. No need to restart eclipse, and you will not face the problem again.

Bmmm, Solved. Saved time.

Friday, September 16, 2011

Immutable Classes

Class whose instance object can not be modified are called immutable classes. In Java, Strings are best example of immutable classes. Though Java tackles Strings in differently manner but still they maintain the immutability of String class. In more technical terms, Immutable object are the objects whose state can not be changed.

What is the state of the object?
State of the object is value of its fields.

public class User {
String firstName;
String lastName;
public User(String firstName, String lastName, int identitiNumber) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

If you create instance of User class with Java as first name and Developer as last name, then userObject state is Java Developer.

But later you can change the last name to Programmer. So latest state would be Java Programmer. So in this case our class is mutable and it can alter the state based on the requirement.

What is an Immutable Object?
As mentioned earlier object whose state can not be altered is immutable object.

In Effective Java, Joshua Bloch makes this compelling recommendation :
"Classes should be immutable unless there's a very good reason to make them mutable....If a class cannot be made immutable, limit its mutability as much as possible."

How to create Immutable object/class?
To create immutable object prototype should be such that it should not provide a way to change the value once object has been created. Sun has defined one contract which should be followed to create immutable classes. Sun Immutable class contract.

Remove the setter methods.

public class User {
String firstName;
String lastName;
public User(String firstName, String lastName, int identitiNumber) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}

Lets analyze if this solution will make the class immutable completely. Actually it will not. Because by default fields are visible to the class existing in same package. firstName and lastName are still exposed to classes in the same package. So it is still not safe.

Make all fields as private to the class


public class User {

private String firstName;

private String lastName;

public User(String firstName, String lastName, int identitiNumber) {

this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}

Looks like we are safe now. But it does not look like. Though in our strings are immutable objects but lets say firstname and lastname are mutable objects. Then some one can take the reference of the object and change its property. So to by pass this problem, we will not return reference of the object but we will return cloned object.

Get should return cloned object


public class User {

private String firstName;

private String lastName;

public User(String firstName, String lastName, int identitiNumber) {

this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName.clone();
}
public String getLastName() {

return lastName.clone();

}

}



Make the class prototype final and all the final


Seems like class is safe and will do great. But to secure class/code secure from security threats and reflection uses we should mark class and its fields final. Generally class is marked as final so that any developer should not create any mutable class extending immutable class. If you are leaving this class non-final then java docs should provide basic purpose of leaving this non-final, so that developer extending the class should be sure about the complete feature of the class. For more information

Make the class prototype final and all the final


public final class User {
private final String firstName;
private final String lastName;
public User(String firstName, String lastName, int identitiNumber) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}

What are the advantages of Immutable object?
Okay, I have created immutable object. What next? How will it help me to improve my application? There are lot of questions that bugged me after creating first real immutable object. I search a little bit and most of the places suggest me thread safety is the biggest advantage of immutable classes. Lets figure out all possible advantage of immutable classes over mutable classes.

Thread Safe
When threads are sharing objects then it is mandatory to synchronize the shared object when state of shared object is changed by . In case of immutable objects we do not have any ways with which state of the shared object can be modified. So if multiple threads are sharing the same object, even then we do not have to worry about changes in shared data. As data for all the threads will remain consistent so there will not be any reading issues. So while writing thread code, we can use immutable object without any issue.

As immutable objects do not need additional protection at the time of thread handling, so additional efforts of synchronization will be by-passed. So application will become little faster than synchronized application.

Simple to construct, test, and use
Due to immutable behaviour of the object, these object are less error prone and can be tested easily. They are safe in threads so there are less complexity involved with the threads.

Do not need a copy constructor and clone
It is not required to create copy constructor for any immutable classes, because reference of the class will solve the purpose of copying.
For mutable classes copy constructor creates the copy of the existing object and later this copy can be altered as per the business need. Whereas in case of Immutable object user can not change the object, so instead creating the same object again, it is more advisable to return the same object.

Allow hashCode to use lazy initialization, and to cache its return value
Lazy initialization is the process to delay the process of instantiate/process something until it is necessary. So in case of immutable objects compiler need not to use hash code operation for each and every object until it is necessary. As hash code of the object will not change until the object remains in the memory, so hash code for the object can be cached for future references.

Do not need to be copied defensively when used as a field
It is not required to copy all the fields of the immutable object. As everything is unshakable so it is okay to return the reference of the object instead copying it deeply.

Make good Map keys and Set elements
As caching of the object's hashcode is possible so it makes better performing Maps and sets which internally uses hashing for faster access.

Always have failure atomicity
The transaction subtracts 10 from A and adds 10 to B. If it succeeds, it would be valid, because the data continues to satisfy the constraint. However, assume that after removing 10 from A, the transaction is unable to modify B. If the database retains A's new value, atomicity and the constraint would both be violated. Atomicity requires that both parts of this transaction complete or neither.

If an immutable object throws an exception, it's never left in an undesirable or indeterminate state.

What are the disadvantage of Immutable object?
So many advantage, then why caring about disadvantage. Why does every java developer not make all classes immutable? Why do we need mutable class when immutable are solving all the earthly and programmatic complexities. Anyways I believe we should know it. Following are few problematic areas of immutable objects.

Memory requirement

With immutability, any time you need to modify data, you need to create a new object. This can be expensive. Imagine needing to modify one bit in an object that consumes several megabytes of memory: you would need to instantiate a whole new object, allocate memory, etc. If you need to do this many times, mutability becomes very attractive.
Conclusion
As it is evident immutable object has lot of advantage over mutable object.Immutable objects (and more particularly, immutable collections) avoid all of these problems. Once you get your mind around how they work, your code will develop into something which is easier to read, easier to maintain and less likely to fail in odd and unpredictable ways. Immutable objects are even easier to test, due not only to their easy mock ability but also the code patterns they tend to enforce. In short, they're good practice all around!

Source/References(Used to write this post)


http://www.javalobby.org/articles/immutable/index.jsp

http://www.informit.com/articles/article.aspx?p=20530

http://www.javapractices.com/topic/TopicAction.do?Id=29

http://www.ibm.com/developerworks/java/library/j-jtp04223/index.html
http://www.javaranch.com/journal/2003/04/immutable.htm
http://www.javalobby.org/articles/immutable/index.jsp
http://www.ibm.com/developerworks/java/library/j-jtp02183/index.html
http://en.wikipedia.org/wiki/Immutable_class
http://stackoverflow.com/questions/5652652/java-advantages-of-of-immutable-objects-in-examples

Sunday, September 4, 2011

Why do we need Good API design?

I am not gonna write down some document on this. I am just giving you a video where Josh is describing the requirement of having good API infrastructure.

http://www.youtube.com/watch?v=aAb7hSCtvGw

Friday, August 5, 2011

Java: Pass by Value

I was in an interview and interviewer asked me the following question.

public static void main(){
          String s1 = "A";
          s1 = s1 + 1;
          System.out.println("Before function call S1 is:" + s1);
          modifyString(s1);
          System.out.println("After function call S1 is:" + s1);
}

String modifyString(String a){
          a = a + 2;
          return a;
}

What is the output of the following problem?

Though I knew Java is pass by value but at the time of function call Java passes memory reference of the objects. So with the conviction I wrote the output of the program.

Before function call S1 is: A1
After function call S1 is: A12

Interview was over, I returned home, wrote the program and ran it in my eclipse. Bomb... It exploded. Results were not as I expected. WTF, why are those results not the same as I expected? I am the Java bond I can not be wrong. Instantaneously I pinged for an assistance. I wanted to hear "there is a problem with my eclipse instance. I should dump the current eclipse and take the latest eclipse soon." But instead hearing those words  I got following response.

Before function call S1 is: A1
After function call S1 is: A1

My expectation were shattered and I started arguing. Argument ended with my broken believe and I figured out "I have to cover a lot more about java fundamentals".

Anyways let me tell  you how does java pass the object to the function. In general java do not differentiate between Objects and primitive data type. It uses copy operation to pass the value of both type of data types.
If you have overridden copy method of your class then java will copy the object based of your implementation otherwise it will copy the object shallowly, in other words we say java uses shallow copy functionality of the objects. In case of shallow copy it creates a new reference to the object passed to the method. Now whenever you change in this method, are reflected back in the mutable classes, whereas in case of immutable classes it is not possible to change the object so we refrain ourselves to changing anything in those classes.

Lets review the following program.


public class PassByValueInJava {

int xy = 0;
private static void modifyPav(PassByValueInJava pav3 ,PassByValueInJava pav4) {
int temp  = pav3.xy;
pav3.xy = pav4.xy;
pav4.xy = temp;
}

public static void main(String[] args) {
PassByValueInJava pav1 = new PassByValueInJava();
PassByValueInJava pav2 = new PassByValueInJava();
pav1.xy = 10;
pav2.xy = 20;
System.out.println("Before Modify:::: pav1 x:" + pav1.xy + "   pav2 x:" + pav2.xy);
modifyPav(pav1, pav2);
System.out.println("After Modify::::pav1 x:" + pav1.xy + "   pav2 x:" + pav2.xy);
}

}


Can you guess what is the output of the program written here?
After seeing the above example I thought it should not switch the values. So results should be the following
Before Modify:::: pav1 x:10 pav2 x:20
After Modify:::: pav1 x:20 pav2 x:10

Now it is strange. Why did swapping happened? Was there something different?

Okay, lets analyze what has happened in this program? Main function calls the modify function and providing them the copy of pav1 and pav2. As copy is a shallow copy, so in this case Java will create a reference which will point to the same memory location of the previous object. Memory location depicts the situation well here.

Why did not same thing happened when string object was passed to the method.
As string in java are immutable so java deals with string in a different manner. Initially when S1 = A then string was pointing to one memory location and as soon as S1 = S1 + 1, it creates new string object and S1 was assigned to it.

Now when Main called modify function s1 was pointing to A1 memory location whose reference was passed to modify function. When string s2 got changed, then it started pointing to the A12 string object's memory location. But s1 is still pointing to the A1 string object's memory location. That is why value for s1 did not modify.

So it is clear that java always uses pass by value and as java tackles string in a complete different way, this is the reason we see such a huge difference between objects and strings.

Program mentioned above could enhance with the following


public static void main(){
          String s1 = "A";
          s1 = s1 + 1;
          System.out.println("Before function call S1 is:" + s1);
          s1 = modifyString(s1);
          System.out.println("After function call S1 is:" + s1);
}

String modifyString(String a){
          a = a + 2;
          return a;
}

It will result in the expected output.