Monday, 24 February 2014

Java Interview Questions and Answers

JAVA INTERVIEW QUESTIONS & ANSWERS

HashSet


Java Hash Set is a useful class implementation of Java Collection framework. HashSet implements Serializable, Cloneable, Iterable<E>, Collection<E> and Set<E> interfaces and extends AbstractSet class directly.
Java Hash Set does not contains duplicate values, allows null values and does not guarantee if the order of elements will remain same over the time.
Hash Set in Java provides a huge set of implementations, some of the basic and commonly used operations are listed below with proper example.
How to create a Java Hash Set
A Java HashSet object can be obtained as shown below, gnerics specification is optional but it is always a good practice to tell JVM about the content that is going to be stored in HashSet. Use of generics eleminates the need of explicit type casting.
  1. // creating a new hash set with String  elements  
  2. HashSet<String> hashSet = new HashSet<String>(); // using generics --String in this case  
  3.          

How to add Elements to a Java Hash Set - add() & addAll()
Java HashSet provides two methods to add elements to it, add() adds a single object at a time while addAll() can be used to add all elements from a specified collection to the HashSet.
  1. // adding elements to hash set  
  2. hashSet.add("element1"); // add elements  
  3.   
  4. // adding a collection using addAll()  
  5. HashSet<String> hashSet2 = new HashSet<String>(); //new Hash Set to add   
  6.   
  7. hashSet2.add("newHashSet1"); // adding elements to new Hash Set  
  8. hashSet2.add("newHashSet2");  
  9. System.out.println(hashSet2); // show elements in new hash set  
  10.   
  11. hashSet.addAll(hashSet2); // adding new hash set  
  12. System.out.println(hashSet); // elements after adding collection using addAll  
  13.          

How to remove Elements from Java Hash Set - remove() & removeAll()
Hash Set in java provides two methods to remove elements from HashSet, remove() remmoves one element while removeAll() removes all elements from HashSet that are present in specified collection.
  1. // removing elements from hash set  
  2. hashSet.remove("element1");  // remove elements  
  3. System.out.println(hashSet);  
  4.   
  5. hashSet.removeAll(hashSet2); //removes all elements present in specified collection   
  6.          

How to make Java Hash Set Empty - clear()
Java Hash Set provides clear() method to remove all elements from a HashSet, it makes HashSet an empty collection.
  1. // removing all elements from hash set  
  2. hashSet.clear();  
  3. System.out.println(hashSet); // return an empty hash set  

How to clone a Java HashSet
Creates a shallow copy of HashSet instance but elements does not coloned themeselves. While comparing a HashSet and its clone using .equals(), it always returns a 'true'.
  1. //cloning hash set  
  2. HashSet cloneHashSet = (HashSet) hashSet.clone(); // returns a shallow copy of hash set  
  3. System.out.println(cloneHashSet);  
  4. System.out.println(hashSet.equals(cloneHashSet)); // returns a true  
  5.          

How to compare Java HashSet using .equals()
It returns true if the specified object is a set and having same size as the HashSet and contains all elements that are present in HashSet comparing to.
  1. hashSet.equals(hashSet2); // returns true if specified object is a set   
  2. //and having same size and contains all elements  
  3.          

How to check if HashSet contains specified element/elements - contains() and containsAll()
HashSet provides two very important methods, contains() returns true if the specified element is present in the HashSet and containsAll() returns true if the elements in specified collection are present in HashSet.
  1. hashSet.contains("element"); // return true if set contains specified element  
  2.   
  3. hashSet.containsAll(hashSet2); // return true if the hash set contains all the elements  
  4. //specified in provided collection  
  5.          

How to convert Java HashSet to an Array or a String
toArray() converts all HashSet elements to an array and toString() represents a String form of HashSet.
  1. hashSet.toArray(); // returns an array with hash set elements in it  
  2. hashSet.toString(); // returns a string presentation of hash set elements  
  3.          

How to use retainAll with Hash Set in Java
retainAll() method returns only those elements from HashSet that are present in the specified collection.
  1. hashSet.retainAll(hashSet2); // retain all elements that are present in specified collection   
  2. // removes all elements that are not present in specified collection  
  3.          

How to get size of a Hash Set in Java
The size of a HashSet can be obtained using .size() method, it returns an integer value equals to the number of elements in the hash set.
  1. // check size of hash Set  
  2. hashSet.size(); // returns an integer value   
  3.          

How to apply Iterator on a Java HashSet - iterator()
An iterator can be applied on a HashSet instance using .iterator() method, iteration of HashSet does not retain the order. hasNext() checks if the hash set contains more elements and .next() returns the next element in hash set.
  1. Iterator<String> iterator = hashSet.iterator(); // returned an iterator on hash set -- no order  
  2.   
  3.         while(iterator.hasNext()){  
  4.             System.out.println(iterator.next());  
  5.         } 
HashSet


HashSet is backed by HashMap instance and it stores unique elements but order in which the elements are stored is not defined, it also allows null element.


The value that is added to the HashSet acts as a key to the backing HashMap with a dummy object as the value to that key which is a static constant so that multiple add operations does not result in multiple instances of object. For example if we add a value to the hashset like
Set<String> collections= new HashSet<String>();
collections.add("HashSet");
then internally it is stored in a map as hashmap.put("HashSet",dummy) where dummy is 
private static final Object dummy = new Object();


When iterating over a HashSet a keyset iterator is returned not the values. Since the elements stored in the HashSet are stored as keys into the HashMap. 

Set Implementation Internally in Java

Each and every element in the set is unique .  So that there is no duplicate element in set .

So in java if we want to add elements in the set then we write code like this

public class Sunil {
   
    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
       
        HashSet<Object> hashset = new HashSet<Object>();
        hashset.add(3);
        hashset.add("Java");
        hashset.add("Blogspot");
        System.out.println("Set is "+hashset);
    }
}

It will print the result :       Set is [3, Java , Blogspot]


Now let add duplicate element in the above code

public class Sunil {
   
    public static void main(String[] args)
    {
        HashSet<Object> hashset = new HashSet<Object>();
        hashset.add(3);
        hashset.add("Java");
        hashset.add("Blogspot");
        hashset.add(3);                     // duplicate elements
        hashset.add("Java");              // duplicate elements
        System.out.println("Set is "+hashset);
    }
}


It will print the result :       Set is [3, Java, Blogspot]


Now , what happens internally when you pass duplicate elements in the  add() method of the Set object , It will return false and do not add to the HashSet , as the element is already present .So far so good .

But the main problem arises that how it returns false . So here is the answer

When you open the HashSet implementation of the add() method in Java Api's that is rt.jar , you will find the following code in it

public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable

{
    private transient HashMap<E,Object> map;
   
    // Dummy value to associate with an Object in the backing Map
   
    private static final Object PRESENT = new Object();
   
   
   
    public HashSet() {
        map = new HashMap<>();
    }
   
    // SOME CODE ,i.e Other methods in Hash Set
   
   
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
   
   
   
    // SOME CODE ,i.e Other methods in Hash Set
}


So , we are achieving uniqueness in Set,internally in java  through HashMap . Whenever you create an object of HashSet it will create an object of HashMap as you can see in the italic lines in the above code .

As we know in HashMap each key is unique . So what we do in the set is that we pass the argument in the add(Elemene E) that is E as a key in the HashMap . Now we need to associate some value to the key , so what Java apis developer did is to pass the Dummy  value that is ( new Object () ) which is referred by Object reference PRESENT .

So , actually when you are adding a line in HashSet like  hashset.add(3)   what java does internally is that it will put that element E here 3 as a key in the HashMap(created during HashSet object creation) and some dummy value that is Object's object is passed as a value to the key .

Now if you see the code of the HashMap put(Key k,Value V) method , you will find something like this

 public V put(K key, V value) {
//Some code
}

The main point to notice in above code is that put (key,value) will return

1.  null , if key is unique and added to the map
2.  Old Value of the key , if key is duplicate

So , in HashSet add() method ,  we check the return value of map.put(key,value) method with null value
i.e.

   public boolean add(E e) {
            return map.put(e, PRESENT)==null;
       }

So , if map.put(key,value) returns null ,then
map.put(e, PRESENT)==null      will return true and element is added to the HashSet .



So , if map.put(key,value) returns old value of the key ,then
map.put(e, PRESENT)==null      will return false and element is  not added to the HashSet .

Thursday, 13 February 2014

Basic Questions & Answers on SDLC

BASIC SDLC QUESTIONS AND ANSWERS

01.Q) What is SDLC?
A) In full SDLC is System Development Life Cycle. It is a process used by Software Professionals to create, modify or maintain software systems. It mainly defines the models and methodologies that is commonly used to develop these systems.

02.Q) What are the benefits of using SDLC?
A) Using SDLC properly should result in following benefits for Software systems.
        - A high quality system.
        - Meets or exceeds customer expectations.
        - Timely completion.
        - Complete within estimated budget.
        - Effective and efficient working system.
        - Inexpensive to maintain.
        - Cost-effective to enhance

03.Q) What are the different phases of SDLC?
A) Major phases of SDLC could be defined as 
         - Initiation
         - Feasibility
         - Requirements Collection
         - Design
         - Development
         - Verification
         - Maintenance and Review

04.Q) Explain Initiation and Feasibility phase.
A) The Objective of Initiation and feasibility is to 
         - Perform Initial Analysis
         - Explore alternate solution
         - Define costs and benefits
         - Propose preliminary plan

05.Q) Explain Requirement Collection phase.
A) Generally the following things are done in Requirement collection phase.
         - Problem Definition
         - Analyze current System
         - Focus on decision and related information need
         - Define Business Functionality
         - Define Requirements
         - Plan for training and user acceptance.

06.Q) Explain Design phase.
A) In Design phase the following things are generally being done.
         - Detailed Project Plan
         - Business needs
         - Logical Design
         - Business functions and rules
         - Overall Architecture
         - Process diagrams and other documentations
         - Database design
         - Other system interactions
         - Screen layouts
         - Hardware Procurement's
         - Overall testplans

07.Q) Explain the Development phase.
A) Generally following things are being done under Development phase.
         - More detailed design
         - Actual code development
         - Unit test is prepared and tested.
         - Test case preparation

08.Q) Explain Verification phase.
A) Following things are being done in Verification Stage
         - Verification test
         - Stress test
         - User Acceptance test
         - Security test

09.Q) Explain Maintenance and Review phase.
A) Following steps are being done under Maintenance and Review phase.
         - Process Review
         - Lessons Learned
         - Bug Fixing
         - Scheduled Maintenance
         - Enhancements

10.Q) What are the different Software development methods?
A) These are some of the most common development methodologies:
         - Waterfall
         - Prototyping
         - Spiral
         - Rapid Application Development

11.Q) What is Waterfall model?
A) Waterfall model is a simple and most common process model. It has following characteristics.
         - Sequential process model
         - Process resembles a waterfall
         - Progress of different phases moves downwards.
         - A phase completes before starting next phase.
         - 1st engineering approach of software development.
         - Organized and step by step development

12.Q) What are the different phases of waterfall method?
A) Different phases of waterfall models are 
         - Conception
         - Analysis & Design
         - Construction
         - Testing
         - Production/ Implementation
         - maintenance

13.Q) What is Prototyping model of Software development?
A) Prototype model is a method of developing software or part of a software by developing prototype first. It has following characteristics.
         - Develop Prototype first approach
         - Used to reduce risk
         - Gives early feel of what end product might be.
         - Not a complete development model

14.Q) What are the advantages of prototype model?
A) There are several advantages of Prototype model.
         - Early feel to end users.
         - Reduces risk by prototypes risky modules first
         - End users are most involved
         - Could help understand complications
         - Used to collect feedback
         - Used to collect requirements

15.Q) What are the disadvantages of Prototypes?
A) The disadvantages of prototype model:
         - Developed prototypes could be completely discarded.
         - Not a complete software model
         - No strict plans are involved.
         - Takes away development time.
         - Too much client interaction might reduce focus
         - Risk of scope creep

16.Q) What is spiral model?
A) Spiral model is a mix of Waterfall and prototype model. It attempts to benefit from both. Software development could be visualized as a spiral progression through 4 quadrants.
         - Analysis
         - Evaluation
         - Development
         - Planning
It has the following characteristics.
         - Project is broken down into smaller segments.
         - Smaller segments are easy to change.
         - Easier to evaluate risk and evaluate alternatives.
         - Each cycle progress in same series of steps.

17.Q) What is Rapid Application Development?
A) The basic approach for Rapid Application development is to develop software using iterations. It stresses mainly on delivering production quality software in short iterations.
These are other key characteristics of this methodology:
         - Quick delivery
         - High quality product
         - Reduces Project risk by handling risky modules earlier
         - Each iteration has all the phases (requirement, design, development, testing and release)
         - High user involvement
         - Low cost