Saturday, October 19, 2013

Inheritance prevention mechanism in java..

Inheritance prevention mechanism :

As of my knowledge, I got two mechanisms to prevent inheritance in java.

1) Using final keyword
2) Using private keyword


1) We know the usage of final keyword.

- If we use 'final' for any variable, that variable can't be changed later.
- If we use 'final' for any instance method, that method can't be overridden.
- If we use 'final' for any class, that class can't be inherited or extended.

example code:
public final class A{

}//end class

public class B extends A{ // can't be done

}//end class

- we will get compilation error stating that the class A is final and can't extend.



2) We know that we can't write private in front of the class.

But we can write this private keyword in front of the constructor. ( used in singleton class)
- It means, once we specify the constructor as private, no one can call that constructor from outside of that class.
- So by using this logic, we can say that we can't extend that class.

explanation: 

- If we see constructor chaining, the child class constructor should call its parent class constructor then only the object creation will be done. If the child class is unable to call its parent class constructor then we can't use that class to create an object.
- From the above logic, once the constructor is declared as private then No other class can extend this class.



example code:

public class A{
      //private constructor
      private A(){
      }
}//end class

public class B extends A{
   //public constructor
   public B(){
    }
}//end class


If we try to compile class B, we will get compilation  error that ....

A() has private access in A
public class B extends A{
       ^
1 error

Can a Singleton class can be inherited?


Please read Inheritance prevention mechanisms at javaojava.blogspot.in/2013/10/inheritance-prevention-mechanism-in-java.html

Can constructor throws Exception?

Constructors also can throw exceptions like methods: 

Let us take an example


CException.java :
public class CException{

        //Constructor 
        public  CException()throws Exception{
               //.....
        }
}

From the above code snippet, 
      A constructor also can throw an exception like a method, and the object creation logic has to handle this exception. The handling will be done using try, catch block as we use for methods..

If we try to write object creation code to the above class, we will get compilation error like..

unreported exception java.lang.Exception; must be caught or declared to be thrown
CException ce=new CException();
             ^
1 error

...So be careful in the interview...


Wednesday, October 16, 2013

Hashtable imp methods

Hashtable:


- It doesn't allow null keys and null values. But it already has one null key and one null value in it , And we are no more able to insert null keys and null values.

-It is Synchronized object.

- Since it extends Dictionary, There are two important metthods
abstract  Enumeration<V>elements()
          Returns an enumeration of the values in this dictionary.
abstract  Enumeration<K>keys()
          Returns an enumeration of the keys in this dictionary.

So HashTable has to implement there methods...
These two methods are not there in HashMap class because it implements Map interface and extends AbstractAMap class so no more methods it has to implement.

- Since it implements  Map interface, There are three important methods
 Set<Map.Entry<K,V>>entrySet()
          Returns a Set view of the mappings contained in this map.
 Set<K>keySet()
          Returns a Set view of the keys contained in this map.
 Collection<V>values()
          Returns a Collection view of the values contained in this map.

So, here you can do both iterate and enumerate keys as well as values.

- Since Hashtable implements Serializable, we can serialize this object. 
- Since Hashtable implements cloneable, we can get the shallow copy of the object.

HashMap imp methods


Spring MVC workflow..

Spring MVC: 

The main components in spring-mvc are front controller, handler mappings, controllers, view resolvers, and views.


work flow:

- First a web request is submitted to the application.

- The FrontController receives the request and interprets it to find the appropriate handle mapping. The handle mapping maps the request to an appropriate Controller object.

- The front controller forwards the request to the controller object.

- The controller receives the request, processes it, and returns a Model and View object to the front controller.

- The front controller uses View Resolvers to find the appropriate View object.

- The view object is used to render the result which then sends it back to the client.





Using HIBERNATE with SPRING (HibernateTemplate)

HibernateTemplate:

      Spring offers HibernateTemplate to simplify implementation of the Hibernate data access code.
HibernateTemplate includes various methods that reflect the Hibernate Session methods.

- It takes the responsibility to manage the Hibernate Session making the application free from implementing the code for opening and closing the Hibernate session accordingly.
- It provides a service - to convert the HibernateException's into DataAccessExceptions.

Spring framework includes two HibernateTemplate classes
1) org.springframework.orm.hibernate.HibernateTemplate  -  to work with hibernate2.1
2) org.springframework.orm.hibernate3.HibernateTemplate  - to work with hibernate3

Note: spring framework from its 2.5 version onwards supports to work with Hibernate3.1 or higher version only.

To use HibernateTemplate object, you must pass SessionFactory object to it and then use.

There are 3 constructors in HibernateTemplate class
1) HibernateTemplate()
     - you must pass SessionFactory object before you use any method of this object using setSeesionFactory() method.

2) HibernateTemplate(SessionFactory)
3) HinernateTemplate(SessionFactory, boolean)
  - if you pass true as boolean value... HibernateTemplate perform its own Session management instead of participating in a custom Hibernate current session context.



It is not recommended to use now these days. ***

source:
Spring and Hibernate (SANTOSH KUMAR K)

tomcat web application deployment and configuration tips.

HashMap important methods... notes ...

HashMap:

java.util.Map is an Interface

public interface java.util.Map{
    public abstract int size();
    public abstract boolean isEmpty();
    public abstract boolean containsKey(java.lang.Object);
    public abstract boolean containsValue(java.lang.Object);
    public abstract java.lang.Object get(java.lang.Object);
    public abstract java.lang.Object put(java.lang.Object, java.lang.Object);
    public abstract java.lang.Object remove(java.lang.Object);
    public abstract void putAll(java.util.Map);
    public abstract void clear();
    public abstract java.util.Set keySet();
    public abstract java.util.Collection values();
    public abstract java.util.Set entrySet();
    public abstract boolean equals(java.lang.Object);
    public abstract int hashCode();
}


java.util.HashMap is an implementation class to Map interface

public class java.util.HashMap extends java.util.AbstractMap implements java.util.Map,java.lang.Cloneable,java.io.Serializable{
    static final int DEFAULT_INITIAL_CAPACITY;
    static final int MAXIMUM_CAPACITY;
    static final float DEFAULT_LOAD_FACTOR;
    transient java.util.HashMap$Entry[] table;
    transient int size;
    int threshold;
    final float loadFactor;
    volatile transient int modCount;
    public java.util.HashMap(int, float);
    public java.util.HashMap(int);
    public java.util.HashMap();
    public java.util.HashMap(java.util.Map);
    void init();
    static int hash(int);
    static int indexFor(int, int);
    public int size();
    public boolean isEmpty();
    public java.lang.Object get(java.lang.Object);
    public boolean containsKey(java.lang.Object);
    final java.util.HashMap$Entry getEntry(java.lang.Object);
    public java.lang.Object put(java.lang.Object, java.lang.Object);
    void resize(int);
    void transfer(java.util.HashMap$Entry[]);
    public void putAll(java.util.Map);
    public java.lang.Object remove(java.lang.Object);
    final java.util.HashMap$Entry removeEntryForKey(java.lang.Object);
    final java.util.HashMap$Entry removeMapping(java.lang.Object);
    public void clear();
    public boolean containsValue(java.lang.Object);
    public java.lang.Object clone();
    void addEntry(int, java.lang.Object, java.lang.Object, int);
    void createEntry(int, java.lang.Object, java.lang.Object, int);
    java.util.Iterator newKeyIterator();
    java.util.Iterator newValueIterator();
    java.util.Iterator newEntryIterator();
    public java.util.Set keySet();
    public java.util.Collection values();
    public java.util.Set entrySet();
    int capacity();
    float loadFactor();
}


The above code is generated from the command 'javap'  
usage: javap java.util.Map
           javap java.util.HashMap

From the above methods, some methods are very important methods we have to consider.

in Map:

1) public java.lang.Object put(java.lang.Object, java.lang.Object);
 
-  put method is to put an element/ object / value  in the map object with a reference/map to it (key).
-  Here key, values can be any type.
-  Most preferably key must be immutable and value can be any. Because HashMap concept is depending on hashcode / hashing mechanism. If the key is mutable then the hashcode will be changed, So, It may leads to unreliable. see hashing and bucketing concept  for more clarity.

          This put method returns an object only when try to put an object in the place of old object, and this old object will be returned. From this we will be notified that the returned object is replaced by new object.

      For example: 
m.put("1","one")      --->    returns null   ( because no object (value) was there with that key)
m.put("1","ONE")    --->   returns "one" (because "one" was the old object)


2) public java.lang.Object remove(java.lang.Object); 

- remove removes an element/ value from the map object, here we have to say map that remove the element which is referenced/mapped with this key. So we have to give the corresponding key to remove an element/ value from map object.
      
       remove(key) : returns value of that key
        This remove method returns an Object that is the mapping value you specified key to remove from map object otherwise returns null if the specified key is not there in map object. From this we will be notified that the specified key is removed along with value.

    For example: 
m.put("1", "one")    ----> returns null (because no object (value) was there with that key)
m.remove("1")        ----> returns "one" (because "one" is there with that key)
m.remove("1")        ----> returns null (because no object (value) is there with that key)


3) public java.util.Set keySet();

     This keySet method returns java.util.Set implemented class Object ( We have unknown collection implementations ) , So we have to consider this object as Set type object.

  -  An unordered Set object.
  -  we can iterate this set object and get values from map object.
  -  we can make this collection object to an array object.


    For example:
       1)    Set set = m.keySet();
               Iterator itr = set.iterator();

while (itr.hasNext()) {
System.out.println(m.get(itr.next()));
}//end while  
o/p ...
three
two
one
         2)      Object[] oar= set.toArray();
                  for (int i = 0; i < oar.length; i++) {
System.out.println((String)oar[i]);
}//
o/p...
3
1

     In this second example you cannot convert the object oar to String array object directly like this
String[] strAr=(String[]) oar;  ----- X    
          Because the elements of Object[] array are to be type casted to String type at runtime. 

4) public java.util.Collection values();

      This values method returns all values in the map object in Collection form / notation /view  that can be of any collection interface implementation class object type.

-  An unordered Collection object.
-  we can iterate this Collection object and use values of map object.
-  we can make this collection object to an array object.

  see keySet method example .

5) public java.util.Set entrySet(); 

     Set<Map.Entry<K,V>>  entrySet() 

  This entrySet method returns Set object which contains Entry(is a inner class from Map interface) class objects. These Entry objects are the main objects which holds key, value pairs.


look into Entry api 


in HashMap:

1) public java.lang.Object clone();

 -   Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.

     This clone method returns a copy of the map object that will have all the elements as old in it.

for example:

           map.remove("2");
           HashMap hMap=(HashMap)map;
           Map bMap =(HashMap)hMap.clone();
                                System.out.println(bMap.isEmpty()); -- > false
                                System.out.println(bMap.size()); --> some value
                                System.out.println(bMap.containsKey("1")); -- >true
                                System.out.println(bMap.containsValue("two"));-->false
                                System.out.println("TWO".equalsIgnoreCase(bMap.get("two"))); --> false



Key Points....

- Hashmap allows duplicate keys and duplicate values including null also.

for example:
                                       Map mp=new HashMap();
                                        mp.put(null,null);
                                        mp.put(null,null);
                                        mp.put("1",null);
                                        mp.put("2","ttt");
                                System.out.println(mp.get("1"));
                                        mp.put(null,"33");
                                System.out.println(mp.put("1","one"));
                                System.out.println(mp.put("2","two"));
                                System.out.println(mp.get("1"));
o/p:
null
null
ttt
one

- This implementation (HashMap) is not synchronized.
 If we need HashMap to be synchronized, we have to approach 
   Map m = Collections.synchronizedMap(new HashMap(...));

- Initially this HashMap object contains null key, null value...and we can insert null key and null values later also. 

for example:
                                        Map mp=new HashMap();
                                        System.out.println(mp.put(null,null)); --- > returns null

and also we can insert one more null later..


Hashtable imp methods



to be continued......