Sunday, October 28, 2012

New Thread implement Runnable or extend Thread

One of the most fundamental design question which is often asked in Java interviews is, if you were to create a new thread, would you extend Thread class or would you choose to implement Runnable and why.

Answer to this question is implement Runnable and the reason provided in most cases is that the class can extend any other class in future, if required. Though the answer is correct but, is that the good enough design consideration to create a new thread this way.

The actual design consideration is you should only extend Thread when you are "extending (enhancing)" the functionality provided by the Thread class and not for providing your business functionality. For instance, if you want to provide a Thread Class which can be Serialized(I don't know why and how you want to do that, this is just a hypothetical situation) and then this class can be used elsewhere as way to spawn serializable threads, then you should actually go ahead and extend thread but, if purpose to create a thread is to execute some business functionality, always go about implementing Runnable.

Saturday, May 05, 2012

How To : All Permutations of a String

This is one question you will come across in one or the other java interviews. Though it sounds very difficult when you hear it for the first time, but actually this can be achieved quite easily if you think about it a little in terms of recursion.

Lets take a simple example of a string "ABC" to understand and see how this can be done.

Here, we will see how to approach the problem and try to reach a solution .

Solution:

We start the solution with 2 Strings one given as input and other empty which we call as the output. Then we start creating all the permutations of the string iteratively and recursively.

What need to do is take a character out from the given string, populate it in the output string. All we need to do now is to do this step again with these updated string. Here is the Java code snippet to do the same.



1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
 public void permute (String output, String input){
  String temp = null;
  if(input.length() > 1){
   for(int i = 0; i < input.length(); i++){
    temp = removeCharacter(input, input.charAt(i));
    permute(output+input.charAt(i), temp);
   }
  } else {
   System.out.println(output+input);
  }
  
 }
 
 public String removeCharacter(String input, char c){
  StringBuilder temp = new StringBuilder(input);
  int index = input.indexOf(c);
  temp.replace(index, index+1, "");
  return temp.toString();
 }


For generating all permutations of a String "ABCD", we need to a call to the method permute like

1
permute("", "ABCD");


Below is the diagram which depicts how each string varies after each iteration and each recursive call. Each level in the tree represents represents a recursive call whereas siblings in the tree represents the iteration.


This code will work only if all the characters in the input string are unique, but will generate some repeated permutations if some or all of the characters are repeated.

Now the question arises, how to handle the scenario where characters are repeated? What you can do is instead of displaying a permutation as and when you get it, you can store it in HashSet. This will eliminate all the duplicates. At the end you can display the entire content of the set. Though this approach works there are memory implication if your input string is really large. To handle those scenarios the algorithm in itself needs to be enhanced to take care of duplicates strings, without using extra memory to the extent of storing all the strings created.

Sunday, March 04, 2012

Custom Java Immutable Object

All of us know String is Immutable and so are other wrapper class instances like Integer, Double etc. Here, we will primarily talk about how to create a custom Java immutable bean/object. We will start with basic bean and develop the concept as we move. So here is the most basic Java bean.

1
2
3
4
5
class Person {
        private String name;
        private int age;
        //getter and setter methods.
}

Now to make this class immutable all you have to do is to remove all the setter methods, add a public constructor which will set the values for name and age for the person and you are done. You have your first basic immutable class.

Here is the immutable person class

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Person {
        private String name;
        private int age;
        public Person(String name, int age){
                this.name = name;
                this.age = age;
        }

        public String getName(){
                return this.name;
        }

        public int getAge(){
            return this.age;
        }
}

Now once the Person object is constructed it cannot be changed. Reason being there are no setter for the attributes of Person and the attributes themselves are private, so you cannot change them.

The question now is what if the Person Class consisted of another member variable called address which is not an immutable object. Will the person class still continue to be an immutable class. Answer is no. Here is the reason.

Lets create an address class first.

1
2
3
4
5
6
7
8
9
class Address {
        private String city;
        private String country;
        public Address(String city, String country){
            this.city = city;
            this.country = country;
        }
        //getter and setter methods.
}


Assume that the one more attribute 'address' has been added to the person class and the constructor takes one more parameter of type Address. Below code shows how person class is no more a Immutable class.

1
2
3
4
5
6
7
8
9
class CheckImmutable{
        public static void main(String args[]){
                Address a = new Address("city", "country");
                Person p = new Person("test", 12, a); //According to above explanation p should be immutable.
                Address b = p.getAddress();
                b.setCity("cityChanged");
                System.out.println(p.getAddress().getCity());
        }
}

Output of this will be 'cityChanged'. So somehow we managed to change on of the attributes of Person class despite being the fact that person was an immutable class.
Immediate answer to this problem will be make changes to address class to make it immutable as well. What if Address class is in a third party API and you cannot change this class. Or may be Address class is being used in thousand other places in your code and you cannot afford to make changes everywhere. There a simple solution to this just by changing the Person class a bit.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Person {
        private String name;
        private int age;
        private Address address;
        public Person(String name, int age, Address address){
                this.name = name;
                this.age = age;
                this.address = new Address(address.getCity(), address.getCountry());
                //Create a new address object using the one provided as parameter
        }

        public String getName(){
                return this.name;
        }

        public int getAge(){
            return this.age;
        }

        public Address getAddress(){
                //Return a new address object instead of the one which is member of the Person object
                return new Address(address.getCity(), address.getCountry());
        }
}

What we have done here is while creating the person object using constructor, we have created a new Address object and assigned that in the attribute instead of using the one passed as parameter. Similarly, when returning the address object from the getAddress() method, we are creating a new address object and returning it back. Hence any class outside Person will never have access to the address which is inside the person object. Now if you again run the CheckImmutable class with the new Person class, you will see the address has not changed.

Is an instance of Person Class now Immutable. Answer is still a BIG "NO". And as expected the question is how. This time the properties of object person can be modified using Reflection.

Is there a way to stop that, if yes How. Answer to this is yes, using SecurityManager class in Java.
Let's not get into the details of SecurityManager now as this in itself calls for another round of discussion. So we will cover it some other day, in some other question dedicated to SecurityManager itself (well maybe).