Sunday, April 3, 2016

Access Specifiers VS Access Modifiers

  • In old language like C++ public, private, protected, default are considered as Access Specifiers . Except this remaining ( like static ) are considered as Access Modifiers.
  • But in Java there is no terminology like specifiers, all are by default considered as modifiers only.

public
synchronized
private
abstract
protected
native
default
strictfp(1.2v)
final
transient
static
volatile
  • All this 12 are refer as access modifiers only but not specifiers.
Proof for this:

  • Observe the below class 

package interviewdev.blogspot.in;

/**
 * @author amol
 * 
 *  access modifiers allowed to AccessModifierTest(outer class) are : 
 * 1. public
 * 2. default
 * 3. abstract
 * 4. final
 * 5. strictfp(1.2v)
 */
class AccessModifierTest {

//TODO code

 
}
  • If different modifier specified other than mentioned in comment, following compile time error will be thrown.

  • Illegal modifier for the class AccessModifierTest; only public, abstract & final are permitted AccessModifierTest.java /TestProj/src/interviewdev/blogspot/in line 13 Java Problem

Saturday, April 2, 2016

Difference : == operator and .equals() method

             This is the most common question asked in the interview for fresher as well as experienced.Most of  time interviewer person expect answer in one line like,  ==  operator meant for address or reference comparison and  .equals()  method meant for content comparison.

What is reference comparison and content comparison ?  


String s1 = new String("madhav");
String s2 = new String("madhav");
//case 1
System.out.println(s1==s2);
//case 2
System.out.println(s1.equals(s2));


  • As depict in above figure, both variable are pointing to two different memory reference but  having same contents.
  • case1 will return false where  ==  operator used, as the reference or memory address is not same.
  • case 2 will return true  where .equals() method used, the content of both variable are exactly same 
  • Following figure show both variable pointing to the same memory address or reference.
String s1 = new String("someValue");
String s2 = new String(s1);
String s3 = s2;

//case 1 : checking references

System.out.println(s1==s2);
System.out.println(s1==s3);
System.out.println(s2==s3);


//case 2 : checking content

System.out.println(s1.equals(s2));
System.out.println(s2.equals(3));
  • Here in case 1, same reference is shared by only s1 and s3, hence the result of  ==   operator is true.
  •  new  keyword used for creating s2, So different address is allocated. Therefore the result of  ==   operator on s2 and s1 is false.
  • For case 2  .equals()  method will return true as the contents are all same.
Note :
  •  .equals()  method present in Object class also meant for reference comparison only based on our requirement we can override for reference comparison.
  • In String class, all wrapper class and all collection classes  .equals()  method is overridden for content comparison. 

Wednesday, March 30, 2016

How HashMap works in Java ?

HashMap :


    • HashMap is class from java.util pacakge.
    • It stores key value pair in Map.Entry static nested class implementation.
    • It maintain only unique key's, one null value is allowed as a key.
    • If any key is already present with some value and other key is put with new value then current value of that key get overwrite with new value.
    •  HashMap is not synchronized.
Example :
package interviewdev.blogspot.in;

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

public class HashMapExample {

 public static void main(String[] args) {
   
    HashMap hm=new HashMap();  
    
    hm.put(1,"Amit");  
    hm.put(2,"Virat");  
    hm.put(3,"Dhoni");  
    
    for(Map.Entry m:hm.entrySet()){  
     System.out.println(m.getKey()+" "+m.getValue());  
    }  

 }

}


  • A HashMap in Java stores key-value pairs. The HashMap requires a hash function and uses hashCode() and equals() functions of Object class, in order to put and retrieve elements to and from the collection respectively.
  • When we call put method by passing key-value pair, HashMap uses Key hashCode() with hashing to find out the index to store the key-value pair. The Entry is stored in the LinkedList, so if there are already existing entry, it uses equals() method to check if the passed key already exists, if yes it overwrites the value else it creates a new entry and store this key-value Entry. 
  • When we call get method by passing Key, again it uses the hashCode() to find the index in the array and then use equals() method to find the correct Entry and return it’s value. 
  • Some important characteristics of a HashMap are its capacity, its load factor and the threshold resizing.
  • HashMap initial default capacity is 16 and load factor is 0.75. Threshold is capacity multiplied by load factor and whenever we try to add an entry, if map size is greater than threshold, HashMap rehashes the contents of map into a new array with a larger capacity. The capacity is always power of 2, so if you know that you need to store a large number of key-value pair.
  • Below image will explain these detail clearly.

How HashMap works internally ?

HashMap works on the Principal of Hashing. To understand hashing we must understand Hash Function , Hash Value and Bucket. Let's understand each of them.

Hash Function and Hash Value:


  • hashCode() function  which returns an integer value is the Hash function
  • The code for the hashCode() in Object class is as follow :


         public native int hashCode();
  • The integer value returned by the above function is known as Hash value.
Bucket : 
  • A bucket is used to store key-value pairs.
  • In HashMap bucket is Linked List (Simple Linked List for HashMap).







Difference : "Child c = new Child()" and "Parent p = new Child()"

                 Hi Guy's, many time while programming we encounter this kind of declaration's. As it's part of daily development, there are chances of facing this concept in interview. Below simple difference will clear the catch.

Child c = new Child() Parent p = new Child()
If we know exact run time type of object then we should use this approach. If we don't know exact run time type of object then we should use this approach (Polymorphism)
By using child reference, we can call both parent and child class methods. By using parent class reference, we can call only methods available in parent class and child specific methods we can't call.
We can use child reference to hold only that particular child class objects. We can use parent reference to hold any child class object.
HasMap hmap = new HashMap(); ArrayList alist = new ArrayList(); Map map = new HashMap(); List list = new ArrayList();

Tuesday, March 29, 2016

Difference : Interface and Abstract class

              This is most common question in the interview room. Many of interviewee are confused or find them-self trapped while answering this question. Following are the basic  difference between the abstract and interface


Interface Abstract Class
If we don't know anything about implementation, just we have requirement specification then we should go for interface If we are talking about implementation but not completely (Partial implementation) then we should go for Abstract class
Inside Interface every method is always public and abstract, whether we are declaring or not. Hence interface is also considered as 100% Abstract class Every method present in Abstract class need not be public and abstract. In addition to abstract methods we can take concrete method also
Every variable present inside interface is always public, static and final whether we are declaring or not The variable present inside Abstract class need not be public, static and final
We can't declare interface variables with the modifiers : private, protected, transient and volatile There are no restrictions on Abstract class variable modifiers
For interface variables compulsory we should perform initialization at the time of declaration otherwise we will get compile time error For Abstract class variables it is not required to perform initialization at the time of declaration
Inside interface we can't declare instance and static block. Otherwise we will get compile time error. Inide Abstract class we can declare instance and static block
Inside interface we can't declare constructors. Inside Abstract class we can declare constructor, which will be executed at the time of child objectcreation.
We implements interface. We extends abstract class