Great Deals

Java App which is getting viral

App has exclusive collection of Java interview questions.Proudly written by most viewed java author on quora.com
App has detail explanation about every trending questions nowadays in interviews.
It coves core of every interview whether it is of fresher or experienced.
Topics included are

#Collection
#MultiThreading
#Java8
#Spring
#Hibernate
#Jms
#Angularjs

Most liked Java App for you in free. 


Java interview questions part2

What is classloader
When Java application starts the program it does not load all the required files at once. Rather it loads class files when required.
Class loads is part of Jvm which loads when required.
  • Types of classloader
  • 1.bootstrap classloader
  • 2.extension class loader
  • 3.system class loader
  • 4.custom class loader.

How singleton design pattern can be created without creating private constructor
We can create it by using enum.
How to create your own immutable class
  • Declare all fields as final
  • Declare class as final. 
  • Don't provide setter method for any variable. 
  • Perform cloning of objects in getter methods when getter returns object it should return copy.

What is clonable?
Clonable is an interface must be implemented if you plan to clone object. Clonable allows to create bitwise copy of object. clone performs shallow copy. It will copy only reference.

What is shallow and deep copy?

Shallow copy
       When we use default implementation of clone method. you use shallow copy of objects because object refers the same object.
If only primitive type like int char and immutable type like String are present then there is not much difference.

Deep copy
    
   Deep copy is expensive as it recursively copies data from object getting CLONED. it copies mutable objects which are part of object getting cloned.
What if I don't to use closable but still want to make copy of objects
The alternative to clonable is copy constructor.

What happens if you don't implement Clonable.
It will throw CloneNotSupportedException.

  • Diffrence between failfast and fail safe

failfast works on original collection and fail safe works on the copy of original collection.
fail fast throws exception fail safe won'tthrow exception.

  • CopyOnWriteArrayList significance

copy on writearraylist supports concurrency.
synchronized collection locks whole collection and concurrentcollection locks portion of collection.


  • Singleton vs Static class

  1. Singleton object stores in Heap but, static object stores in stack
  2. We can clone the object of Singleton but, we can not clone the static class object
  3. Singleton class follow the OOP(object oriented principles) but not static class
  4. we can implement interface with Singleton class but not with Static class.
  • Overriding Puzzle
class A
{
int a=10;
    void big(){
        
        System.out.println("A");
    }
}
class B extends A
{
int a=20;
    void big(){
        System.out.println("B");
        
    }
    
void childMethod()
    {
        System.out.println("I only exist in child");
        
    }
}
public class HelloWorld{

     public static void main(String []args){
        A b=(A)new B();
        b.big();
System.out.println("Value of A"+b.a);
     }
}

Output: B
  • Case2: Newly added method can't be called with reference of top class.

public class HelloWorld{

     public static void main(String []args){
        A b=(A)new B();
        b.
childMethod
();
     }
}

Output: 
HelloWorld.java:25: error: cannot find symbol                                                                                                                   

        b.childMethod();       

  • Case3:If same variable declared in parent as well as child class.And called using reference of 
  • Parent class.then always variables of parent class are refered .

public class HelloWorld{

     public static void main(String []args){
        A b=(A)new B();
        b.
a
();
     }
}
Output: Value of A10

  • Diffrence Between the Enumeration and iteration
Iterator more safe does not allow other thread to modify collection throws ConcurrentModificationException.
  • How Hashset maintains unique item 
  • private static final Object PRESENT = new Object();
    
    
     public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }


Frequently asked interview questions

Can we serialise the static members
Does not make any sense to make static  members serializable
Staic member belong to the class not the individual objects.
Why use the hashmap keys as immutable objects
Since if we use mutable objects as keys at the time of storage and over the time when we change it may point to entire different location.so suppose for key 3 value 33 is associated if this key is changed then it may point to diffrent location so to avoid this keys are immutable.
Difference save and persist
Save returns serializable entity
Persist return void
What is executerservice

Executerservice is like a threadpool.
It is a way of submitting thread for execution.It is used where asynchronous tasks need to be performed.
Executerservice has submit method.
Which returns future class instance.
Executerservice takes callable instance .
Future returns the result of thread execution

Can we synchronise the constructor

No not possible.since it will be creating lock on object being created but generally the object is not available to other thread till the time it gets created

Can we synchronise the run  method
Yes  we  can  synchronize  run method.

Types of  garbage  collection
Serial gc
Parallel gc=serial works same as parallel but the girl is done by multiple  threads.

What is  difference between notify and notify all

Notify all - will notify all waiting thread
Notify- invokes the first thread which called the wait method on the object

Join()  in multithreading

Join method in multithreading is used to pause execution of all other threads except the one which called the join method.

Why use inner classes.
Inner classes are used to hide implementation details. To increase encapsulation.
Some examples of usage of inner classes are
iterator inside list.
Listener in gui.

Spread the word if you really like this share with your friends.


ConcurrentHashMap in nutshell

The Java concurrent hash map may be considered as the lodge having many rooms with locking facility.Where as hash map may be considered as the house with one door.

So in case of hash map if you are locking the door. Then you will not be able to access if any of the room of house. Before using hash map every thread locks the hash map making it inaccessible to other thread till the  time it won't complete it's operations. 
Hashmap is like your house
Hashmap

But if concurrent hash map is viewed it may be viewed as multiple separate rooms of Lodge if any room is locked we can still access the other rooms.

Concurrent hashmap used by multiple thread

Creation of ConcurrentHashMap


public ConcurrentHashMap(int initialCapacity,float loadFactor, int concurrencyLevel) 

HashMap anatomy:



Initial Capacity: 

You can specify the size of the concurrenthashmap at the time of creation.


 static final int DEFAULT_INITIAL_CAPACITY = 16;

Load Factor: 

Tolerable capacity of concurrenthashmap if it exceeds concurrenthashmap needs to be resized. However resizing operation is relatively slow.

 static final float DEFAULT_LOAD_FACTOR = 0.75f;

ConcurrencyLevel:

Estimated number of concurrently updated threads.

Advantages of concurrenthashmap:


ConcurrentHashMap can be used to make the concurrent operations possible without waiting for other threads job completion

Increased throughput.

For Producer Consumer Example on concurrenthashmap Producer Consumer in ConcurrentHashmap

Disadvantages of concurrency in hashmap


           Methods including size, isEmpty, and containsValue are typically useful only when a map is not undergoing concurrent updates in other threads. Otherwise these methods procure precise results.

When resizing is done?

1.       
       When the concurrenthashmap is almost full 75% of its defined capacity.
2.       When collisions are increased so to avoid collisions concurrenthashmap  is resized.

Properties of ConcurrentHashmap

1.      

         ConcurrentHashmap does not allow null value.
2.       ConcurrentHashMap does not allow duplicate keys.

public class CHashMap {

            public static void main(String[] args) {
ConcurrentHashMap<String, String> ch=new ConcurrentHashMap<String, String>();
ch.put("a", "a");
ch.put("a", "a");
Enumeration<String> enum1=ch.keys();

while(enum1.hasMoreElements())
{
            String key=enum1.nextElement();
            System.out.println("Key is ==>"+key+" Value is ===>"+ch.get(key));
            }
            }

}

Output is: Key is ==>a Value is ===>a



Java Helloworld

Calcuator Demo
package com.oop;
class Calculator
{
     public Calculator() {
          System.out.println("I am constructor");
         
     }
     //1.add 2.sub 3.multiplication 4.division
     public int add(int num1,int num2)
     {
         
          return (num1+num2);
     }
}
public class CalculatorDemo {

     public static void main(String[] args)
     {
          Calculator calcObj=new Calculator();
          System.out.println("addition is "+calcObj.add(2, 3));
         
     }
}

Example
package com.oop;
class Human
{
     private String address;
    private int age;
     public int getAge() {
          return age;
     }

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

     public String getAddress() {
          return address;
     }
  
     public void setAddress(String address) {
          this.address = address;
     }
    
}
public class HelloWorld {
     //Type2:declaration and oneliner init
     //datatype varname="value"
static String empName="Ashwin More";


//Type1: declaration and then intialization
//dataType variable Name;
//variableName="value";

//creation of objects
//ClassName objectName=new className();


public static void main(String[] args) {
     System.out.println("HI Java Batch and i am "+empName);
    
     Human objectHuman=new Human();
     objectHuman.setAddress("Pune");
     objectHuman.setAge(23);
    
     Human objectHuman1=new Human();
     objectHuman1.setAddress("Pune");
     objectHuman1.setAge(20);
    
     System.out.println(""+objectHuman1.getAddress());
}   
    
}
//visibily modifier class ClassName


Advertising