Tuesday, June 14, 2016

Integer , Long, Float, Dobule comparision

public class MyTestClassForInteger {
    public static void main(String[] args) {
        Integer i=10;
        Integer j=10;

        Integer k=100;
        Integer l=100;
        System.out.println(i==j);
        System.out.println(i==j);
    }
}
But the question is how compiler see this code . It compiles and make the above code as below 
After complication the code becomes as follows in MyTestClassForInteger.class file
public class MyTestClassForInteger {
    public MyTestClassForInteger() {         /// Fist difference - compiler adding a defualt constructor.
} public static void main(String[] args) { Integer i = Integer.valueOf(10); //// This is the second difference its calling valueof(int i) method of Integer Class to get the value. Integer j = Integer.valueOf(10); Integer k = Integer.valueOf(100); Integer l = Integer.valueOf(100); System.out.println(i == j); System.out.println(i == j); } }

Now look into Integer class .  Yo will see this 
1:public static Integer valueOf(int i) {
2:      final int offset = 128;
 3:      if (i >= -128 && i <= 127) { // must cache
 4:       return IntegerCache.cache[i + offset];
5:       }
6:      return new Integer(i);
7:   }
Inside method at line 3 first its checking value of i whethere its in between a range or not. then if its true its goes to line 4
Now at line 4 there is another class IntegerCache  . This is the static class inside Integer class. This class is declaring an 
array of size 256 which is storing value from -128 to 127. its like Integer cache[]={-128,-127,-126.....0,1.....127};
All these things are happening at the time of start of JVM and before even using of Integer anywhewre
You can say that value of -128 to 127 of int is already cached and present in cached array.
Whenever we are using Integer it's valueOf(int i) method is returning value from cache without creating any 
new Intger object (line nuumber 6).  But if value go beyond 127 or less than -128 then its creating a new object and returning 
a new intger object.
The purpose of putting int value from -128 to 127 into cache array is to improve performance. Because we heavling use int in that range .
It was the assumption made by JDK developers and I do not think its very good idea.
Thats why it it returing true for 10, 100 but not for 1000 because objects are not equal using == operator.

In Case of Long:
Same rule apply as above. Seee the valueOf(long L);
In case of Double , Float:   They will never be true in == comparision because they do not cache any value and 
they are returning a new object each time   valueOf(double d);

Thursday, May 12, 2016

ArrayList and LinkedList

get(int index) method:
ArrayList internally uses arrays to store elements so.
Retrieving any elements from ArrayList is faster because elements are stored bases on indexing and thus ArrayList is ordered.
Think about children standing in a row for Morning Prayer. Think that there is only single row of few children.  Each child has specific position according to their ordering.
Suppose I want to know that which child is at position 5 or 6, I can get it easily because I know the position. Same as in case of Java array. You can get element in O(1) time from an array (elementArray[position] will give the element).
 So get(int index) method in ArrayList is fast. O(1). Thus random access is faster.

LinkedList: LinkedList in java uses doubly linked list to store the elements.
You can think doubly-linked list as a group of children holding hand of each other and making a row.  First child holding the hand of second child and second child holding the hand of first and third. Similarly last child hold the hand of second last and second last hold  the last and third last .
Now If I want to get any element on the basis of position get(int index) then I have to start from that node which is defined as first node (first child ). Now after traversing to that position I will get that element so it’s slower. I need to traverse for getting the element.
Here there is no indexing of children like children stating in Morning Prayer (ArrayList).
Suppose the position is in last then it will take O(n) time for getting the element. Where n is number of elements.
So get(int index) method in LinkedList is slower . O(n).


add(E element) and add(int position, E element):

Adding element in the last of ArrayList is always faster.
Suppose I want to add one more child in Morning Prayer row (it’s not queue which is FIFO based) or in row of children where children or holding each other by hand. The child will go and stands at last position of the row or in holding hand row.
If I say that this particular child will stand at position 8th then he will stand there and the entire child after position 7th will move right and make a space for this new child. Thus add(int position, E element) is costly than add(E element) in both.
The only difference is that there is a capacity limit that how many children can stand in a row – ArrayList. But there is no such constraint in case of holding hand row – LinkedList.
Due to this difference add(E element) or add(int position, E element) will be in O(n) time if capacity of ArrayList is already full because
1: ArrayList will increase its capacity
2: Copy all the elements into this new capacity array
3: Now it will add the element in the last or specified position.
There will be no such above thing in LinkedList.
If you are iterating the LinkedList then you are adding elements using ListIterator.add(E element) method then LinkedList is much faster.

remove(int position) and remove(E element):

Removing element from the last of ArrayList is always faster.
remove(E element) method will give same performance in both cases.
If you are iterating the LinkedList then you are removing elements using Iterator.remove() method then LinkedList is much faster.

Method availability:
LinkedList has methods addFirst(E element), addLast(E element).  getFirst(), getLast(), offer(E element), poll(), peek()  . ArrayList does not need such methods.
LinkedList needs extra memory for  maintaining pointer to next and previous nodes.

New Method added in JDK 8 List:
spliterator(): Creates a late-binding and fail-fast Spliterator over the elements in this list.

Conclusion: Go with ArrayList in all scenario except one that is if you have to do addition and deletion  using iterator’s remove and add (ListIterator) method while iterating the list then go with LinkedList.


References:  Oracle ArrayList

Wednesday, May 11, 2016

Inversion of control, Dependency Inversion, Dependency Injection

Inversion of control: It is a principle in which custom written portion of computer program receives the flow of control from a generic framework.
Custom written portion of computer program:    Whatever the code we write using Spring framework is an example of custom written portion of computer program.
Receives the flow of control from a generic framework: Our custom written computer program is governed by Spring framework.  Example:   object creation, scope, defining their dependencies and some other main activities are defined by spring framework.
It means that reusable code and problem specific code developed independently even though they operate together in application.
IOC is based on one principle ‘Do not call us, we will call you back’.  Example: Spring framework defines when our custom classes will be created and injected.  There are many such examples available with Spring framework.
Purpose of IOC: Increasing the modularity, reducing coupling and increasing the extensibility of the application program.

Service locator pattern, Dependency Injection, template method design pattern are the examples of Inversion of Control principle.
Dependency Inversion and Dependency Injection:
Dependency Inversion is a principal while dependency Injection is a design pattern that follows the dependency inversion principle.
Dependency Inversion principle states that:
            a: High level modules should not depend on low level modules. Both should depend on abstractions.
            b: Abstraction should not depend on details. Details should depend on abstraction.

Dependency injection is a software design pattern that implements inversion of control for resolving dependencies. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it. The service is made part of the client's state. Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern.

References: Wikipedia

Thursday, May 5, 2016

Objects which are equal but have different hash code



We can have two objects which are equal but have different hash code.
But you want to store it as key in Map interface then hashcode and equals both must be equal for the equal object.

import java.util.HashMap;
import java.util.Map;

/**
 * @author Arun
 */
public class EqualObjectsWithDifferentHashCode {

  private String name;
  private int age;

  public String getName() {
    return name;
  }

  public void setName(final String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }

  public void setAge(final int age) {
    this.age = age;
  }


  public static void main(String args[]) {

    final EqualObjectsWithDifferentHashCode one = new EqualObjectsWithDifferentHashCode();
    one.setAge(1);
    one.setName("A");
    final EqualObjectsWithDifferentHashCode two = new EqualObjectsWithDifferentHashCode();
    two.setAge(2);
    two.setName("B");
    final EqualObjectsWithDifferentHashCode three = new EqualObjectsWithDifferentHashCode();
    three.setAge(1);
    three.setName("A");

    final Map ss = new HashMap<>();
    ss.put(one, "ABC");
    ss.put(two, "XYZ");
    ss.put(three, "KLM");

    // print hashcode of objects. Both object will have different hashcode.
    System.out.println("hashcode of One=" + one.hashCode());
    System.out.println("hashcode of Three=" + three.hashCode());

    // check equality of the objects
    System.out.println("Both objects are equal=" + one.equals(three));

    // now try to fetch object from the Map
    System.out.println(ss.get(three));
  }

  @Override
  public int hashCode() {
    // It is just for example. Do not follow it. It will always return different hashcode.
    return (int) Math.abs((Math.random() * 1000));
  }


  @Override
  public boolean equals(final Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    EqualObjectsWithDifferentHashCode other = (EqualObjectsWithDifferentHashCode) obj;
    if (age != other.age)
      return false;
    if (name == null) {
      if (other.name != null)
        return false;
    } else if (!name.equals(other.name))
      return false;
    return true;
  }

}

Monday, August 25, 2014

Default Method in Interface - JDK 8

Default method: An interface declaration can contain method signatures, default methods, static methods and constant definitions. The only methods that have implementations are default and static methods

Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces

Best practices : Use default methods only in rare case. We have to choose default method name carefully to avoid compile time error in case of one class implementing two interfaces and both interfaces have same default method name.

Static method : Static methods are similar to default method. The only difference is that static method can not be overridden like default method by implementing class.

Functional Interface: Functional interface has exactly one abstract method. @FunctionalInterface annotation can be used to mark it as functional interface.


Thursday, June 26, 2014

HashMap and ConcurrentHashMap

We can syncronize HashMap as follows:

1: Collections.syncronizedMap(hashMap);

2: We can also use ConcurrentHashMap  if we need syncronized HashMap.

What are differences in these two syncronized HashMap.?

In 1:  gives a thread-safe HashMap backed by original HashMap and for each operation entire HashMap will be locked so that only one thread can  access the map.

In 2:  all operations are thread-safe and retrieval operation does not require locking of map.  While updating, only that portion of map is locked which  is being updated.

So performance wise 2: option is better than 1:

ConcurrentHashMap does not allow null key or value like Hashtable. The reason is if multiple threads will access the Map then it’s difficult to predict why key or value is null because it may be modified by other threads.
ConcurrentHashMap differs from Hashtable:
1: Hashtable is based on synchronization while ConcurrentHashMap works on concurrency.
2: Retrieval operation generally does not need any locking
3: Multiple threads can modify ConcurrentHashMap. By default it has concurrency level 16. It means 16 threads can update the table concurrently given that no two threads are working on same bucket. If it is the case then those threads will access that bucket in sequence.
4: It locks the bucket and not the whole map. ConcurrentHashMap uses Reentrant lock internally.
5: ConcurrentHashMap’s iterator is fail- safe.  It means Map can be modified externally while iterating but not in case of Hashtable.
6: ConcurrentHashMap uses balanced tree to store the next key value in case of hash collision while Hashtable uses LinkedList (Separate Chaining)

7: There are many useful methods that are present in ConcurrentHashMap (searchKeys, searchValues, newKeySet ) but not in Hashtable.

Wednesday, December 2, 2009

Find the last updated row from MySql database

1. The Engine of the required tables must be MYISAM. If it is INNODB change it to MYISAM.


2. Now add an additional column in all required tables for timestamp.
MySQL query for this is:
ALTER TABLE table_name ADD COLUMN column_name ON UPDATE CURRENT_TIMESTAMP DEFAULT CURRENT_TIMESTAMP;


3. Now select the last modified table from all the tables:

SELECT TABLE_NAME FROM information_schema.TABLES WHERE table_schema =? AND TABLE_ROWS>0 ORDER BY UPDATE_TIME DESC LIMIT 1.
Note that you have to write only name of your database in place of question mark.

4. And finally select the latest modified row from that table:

SELECT MAX(time_stamp_column_name), row_id FROM table name GROUP BY row_id DESC LIMIT 1.