Saturday, 4 June 2016

Difference between ArrayList and Array





                                   ArrayList
                                     Array

ArrayList is a variable length Collection class which means its size gets increased to half of its capacity once its initial size is full.


Array is fixed length data structure which means one cannot change its length after creating the array object.

ArrayList can only contains objects.It cannot contain primitive types i.e (int,float,long)

Arrays can contain both objects as well as primitive types.


Apart from for and for each loop,Iterator can also be used to iterate ArrayList.


For and for each loop can be used to iterate over Arrays.

ArrayList is single dimensional.
For ex:-
ArrayList<String> a=new ArrayList<String>();


Arrays can have multi dimensions also.
For ex:- Integer [][] a=new Integer[3][3];


In ArrayList ,elements are added using add(e) method.
For ex:- ArrayList<String> a=new ArrayList<String>();
a.add(“robert”);


In Arrays,elements are added using assignment operator.
For ex:-
Integer a[]=new Integer[3];
a[0]=new Integer(1);



Enjoy Reading

Difference between Queue and Stack



               
                                   Queue
                                     Stack
Queue is a collection of objects works on mechanism of First In First Out (FIFO) which means object which is added first, will be removed first.
Stack is collection of objects works on the principle of Last In First Out (LIFO) which means object which is added first will be removed last.
In Queue, Insertion and deletion operation are performed at different end i.e insertion is performed at one end (front) and deletion is performed at another end (rear).
In Stack, Insertion and deletion are performed at same end i.e at one side of the stack (top).
Queue consist of two pointers front and rear. Front points to the first element and rear points to last element
Stack consist of only one pointer i.e top which points to the last element.
Queue is said to be empty if front is equal to rear.
Stack is said to be empty if top is equal to -1.
Real Time Example:-Standing in line in Bank to deposit amount.
Real Time Example:-Distributing set of plates at the buffet.
Technical example:- sending imq messages
Technical example:-Checking for equal number of parenthesis in an expression.(a+b)
Common methods of queue are:-add(e),remove(),element(),offer(e),poll(),peek().
Common methods are :-push(e),pop(),peek(),empty(),search(e).




Enjoy Reading.

Sunday, 29 May 2016

Difference between Comparable and Comparator interfaces ?



Comparable and Comparator interface are two interfaces used to compare and sort the objects.Below are some basic differences between Comparable and Comparator interface.



Comparable
Comparator
It uses the compareTo() method.
int objectOne.compareTo(objectTwo).
it uses the compare() method.

int compare(ObjOne, ObjTwo)
It is necessary to modify the class whose instance is going to be sorted.
A separate class can be created in order to sort the instances.
Only one sort sequence can be created.
Many sort sequences can be created.
It is frequently used by the API classes.
It used by third-party classes to sort instances.


To know more about the Comparator,refer this example Comparator Example

Enjoy Reading

Saturday, 28 May 2016

Implement Berlin Clock


This question is asked in UBS bank Interview.

Problem:-

Berlin Clock represent time in the form of Lamps. Each Row representation of Lamps involves a
different logic. On the top of the clock there is a yellow lamp that blinks on/off every two seconds.The time is calculated by adding rectangular lamps.
  
The top two rows of lamps are red. These indicate the hours of a day. In the top row there are 4 red     lamps. Every lamp represents 5 hours. In the lower row of red lamps every lamp represents 1 hour.So if two lamps of the first row and three of the second row are switched on that indicates                 5+5+3=13h or 1 pm.
  
The two rows of lamps at the bottom count the minutes. The first of these rows has 11 lamps, the       second 4. In the first row every lamp represents 5 minutes. In this first row the 3rd, 6th and 9th lamp are red and indicate the first quarter, half and last quarter of an hour. The other lamps are yellow. In the last row with 4 lamps every lamp represents 1 minute.
  
  For example:-

   Input       Result
  00:00:00     Y
                   OOOO
                   OOOO
                   OOOOOOOOOOO
                   OOOO


Sample TimeConverter Class


import java.util.regex.Matcher;  
 import java.util.regex.Pattern;  
 /**  
  * This class contains the business logic to convert time into Berlin Clock  
  *   
  * @author Dixit  
  *   
  */  
 public class TimeConverterImpl implements TimeConverter {  
 /**  
       * Method validates and convert the time(hh:mm:ss) into Berlin Clock(in the form of Lamps)  
       * For example: 00:00:00 is converted into   
       * Y  
       * OOOO  
       * OOOO  
       * OOOOOOOOOOO  
       * OOOO  
       *   
       * @param aTime consist of String in the form of hh:mm:ss.  
       * @return String consisting of Lamps value.  
       */  
      @Override  
      public String convertTime(String time) {  
           // Input time needs to validated first before performing conversion.  
           if (!validateInputTime(time)) {  
                return TimeConverterConstants.INVALID_TIME;  
           }  
           int timeUnitDivisibleByFive;  
           int timeUnitModulusOfFive;  
           int timeUnitValue;  
           // Input time is split using String split method providing ":" as  
           // argument  
           String[] splitTime = time.split(TimeConverterConstants.COLON);  
           StringBuffer convertedTime = new StringBuffer();  
           // first Seconds Lamp(First Row) is appended to StringBuffer.  
           convertedTime.append(getLamps(Integer.parseInt(splitTime[2])));  
           // line separator is added  
           convertedTime.append(TimeConverterConstants.LINE_SEPARATOR);  
           timeUnitValue = Integer.parseInt(splitTime[0]);  
           timeUnitDivisibleByFive = timeUnitValue  
                     / TimeConverterConstants.MULTIPLE_OF_FIVE;  
           timeUnitModulusOfFive = timeUnitValue  
                     % TimeConverterConstants.MULTIPLE_OF_FIVE;  
           // append second row of Hour Lamps  
           convertedTime.append(getLamps(timeUnitValue, timeUnitDivisibleByFive,  
                     TimeConverterConstants.RED_LAMP));  
           convertedTime.append(TimeConverterConstants.LINE_SEPARATOR);  
           // append third row of Hour Lamps  
           convertedTime.append(getLamps(timeUnitValue, timeUnitModulusOfFive,  
                     TimeConverterConstants.RED_LAMP));  
           convertedTime.append(TimeConverterConstants.LINE_SEPARATOR);  
           timeUnitValue = Integer.parseInt(splitTime[1]);  
           timeUnitDivisibleByFive = timeUnitValue  
                     / TimeConverterConstants.MULTIPLE_OF_FIVE;  
           timeUnitModulusOfFive = timeUnitValue  
                     % TimeConverterConstants.MULTIPLE_OF_FIVE;  
           // append fourth row of Minute Lamps.  
           convertedTime.append(getLamps(timeUnitValue, timeUnitDivisibleByFive,  
                     TimeConverterConstants.RED_LAMP,  
                     TimeConverterConstants.YELLOW_LAMP));  
           convertedTime.append(TimeConverterConstants.LINE_SEPARATOR);  
           // append fifth row of Minute Lamps.  
           convertedTime.append(getLamps(timeUnitValue, timeUnitModulusOfFive,  
                     TimeConverterConstants.YELLOW_LAMP));  
           return convertedTime.toString();  
      }  
      /**  
       * Method Validates the Time It checks for following things:- 1) Checks for  
       * Null and empty value of inputTime. 2) Checks for proper valid pattern of  
       * time in the form of (hh:mm:ss) and also check for limit value allowed in  
       * HH ,MM and SS. For example: 00:00:00 is valid time but 00:00 is not.  
       *   
       * @param inputTime  
       *      consist of time in the form of hh:mm:ss.  
       * @return true if input is correct and false if input is not correct.  
       */  
      private boolean validateInputTime(String inputTime) {  
           try {  
                if (inputTime != null && !inputTime.isEmpty()) {  
                     Pattern timeRegexPattern = Pattern  
                               .compile(TimeConverterConstants.TIME_REGEX_PATTERN);  
                     Matcher timeMatcher = timeRegexPattern.matcher(inputTime);  
                     if (!timeMatcher.matches()) {  
                          return false;  
                     }  
                } else {  
                     return false;  
                }  
           } catch (Exception e) {  
                System.out.println("Exception occured in validation method :-"  
                          + e.getMessage());  
           }  
           return true;  
      }  
      /**  
       * Method checks if timeUnitValue modulus of 2 is 0 then it returns YELLOW  
       * Lamp else it returns OFF Lamp.  
       *   
       * @param timeUnitValue  
       *      consist of SS value.  
       * @return String consist of Single Lamp.  
       */  
      @Override  
      public String getLamps(int timeUnitValue) {  
           if (timeUnitValue % TimeConverterConstants.MULTIPLE_OF_TWO == 0) {  
                return TimeConverterConstants.YELLOW_LAMP;  
           } else {  
                return TimeConverterConstants.OFF_LAMP;  
           }  
      }  
      /**  
       * This method returns Eleven Lamps based on the numericValue passed  
       * to it. The lamps result may consist of RED,YELLOW,OFF and combination of  
       * (RED and OFF)Lamps or (YELLOW and OFF) Lamps.  
       *   
       * @param timeUnitValue  
       *      consist of MM value.  
       * @param numericValue  
       *      consist of integer value divisible by five.  
       * @param strRedLamp  
       *      consist of RED lamp value.  
       * @param strYellowLamp  
       *      consist of YELLOW lamp value.  
       * @return String consist of Eleven Lamps.  
       */  
      @Override  
      public String getLamps(int timeUnitValue, int numericValue,  
                String strRedLamp, String strYellowLamp) {  
           StringBuilder lamps = new StringBuilder(  
                     TimeConverterConstants.ELEVEN_OFF_LAMPS);  
           for (int i = 0; i < numericValue; i++) {  
                if ((i + 1) % TimeConverterConstants.MULTIPLE_OF_THREE == 0) {  
                     lamps.replace(i, i + 1, strRedLamp);  
                } else {  
                     lamps.replace(i, i + 1, strYellowLamp);  
                }  
           }  
           return lamps.toString();  
      }  
      /**  
       * This method returns four Lamps based on the numericValue passed to  
       * it. The lamps result may consist of RED,YELLOW,OFF and combination of  
       * (RED and OFF)Lamps or (YELLOW and OFF) Lamps.  
       *   
       * @param timeUnitValue  
       *      consist of either HH or MM value.  
       * @param numericValue  
       *      consist of integer which may be divisible of five or modulus  
       *      of five.  
       * @param strLamp  
       *      lamp value passed to the function. It can be either RED or  
       *      YELLOW.  
       * @return String consist of four Lamps.  
       */  
      @Override  
      public String getLamps(int timeUnitValue, int numericValue, String strLamp) {  
           StringBuilder lamps = new StringBuilder(  
                     TimeConverterConstants.FOUR_OFF_LAMPS);  
           for (int i = 0; i < numericValue; i++) {  
                lamps.replace(i, i + 1, strLamp);  
           }  
           return lamps.toString();  
      }  
 }  



To get the full code,please hit this link Berlin Clock

Enjoy Programming :)

JDK 1.8 Compiler Compliance is not available in Eclipse Kepler


Most of the time we encounter this issue that jdk 1.8 Compiler compliance is not available in Eclipse .Mostly this issue seen in Kepler.

Steps to resolve this issue:-

  1. Go to Help in Eclipse and Oper Eclipse Market Place option.
  2. Search for jdk 1.8 for kepler
  3. Install the required plugin.
  4. Restart the eclipse.

Enjoy Coding :)

Write Comparator for Student class, assuming student class has name and roll number.


Question:-

Write comparator for Student class, assuming student class has name and roll number.

           Conditions:

                   If the name is same, check of roll number

                   If the name is different, check only for name



Sample Program:-


import java.util.Comparator;  
 /**  
  * Comparator for Student class which uses following field for comparison  
  *   
  * 1.Name ,If name are same, then it uses Roll Number.  
  *   
  * If Name are different , then it checks for name only.  
  *   
  * @author   
  *  
  */  
 public class StudentComparator implements Comparator<Student> {  
   @Override  
   public int compare(Student student1, Student student2) {  
    if (student1 != null && student2 != null) {  
      String name1 = student1.getName().trim();  
      String name2 = student2.getName().trim();  
      if (name1.equals(name2)) {  
       return student1.getRollNumber() - student2.getRollNumber();  
      }  
      return name1.compareTo(name2);  
    }  
    return 0;  
   }  
 }  

Enjoy Programming :)

How to implement an ArrayList


Sample Program:-


/**  
  * @author Dixit  
  *  
  */  
 public class CustomArrayListImpl {  
      private static final int LIST_SIZE = 5;  
      private Object data[];  
      private int index;  
      private int size;  
      public CustomArrayListImpl() {  
           this.data = new Object[LIST_SIZE];  
           this.size = LIST_SIZE;  
      }  
      public void add(Object obj) {  
           System.out.println("index:" + this.index + " list size:"  
                     + this.data.length);  
           if (this.index == this.size - 1) {  
                increaseSize();  
           }  
           data[this.index] = obj;  
           this.index++;  
      }  
      private void increaseSize() {  
           this.size = this.size + LIST_SIZE;  
           Object newData[] = new Object[this.size];  
           for (int i = 0; i < data.length; i++) {  
                newData[i] = data[i];  
           }  
           this.data = newData;  
           System.out.println("index:" + this.index + " List size:"  
                     + this.data.length);  
      }  
      public Object get(int i) throws Exception {  
           if (i > this.index - 1) {  
                throw new Exception("ArrayIndexOutOfBound Occurs");  
           }  
           if (i < 0) {  
                throw new Exception("Negative Value Provided");  
           }  
           return this.data[i];  
      }  
      public void remove(int i) throws Exception {  
           if (i > this.index - 1) {  
                throw new Exception("ArrayIndexOutOfBound Occurs");  
           }  
           if (i < 0) {  
                throw new Exception("Negative Value Provided");  
           }  
           System.out.println("Object getting removed:" + this.data[i]);  
           for (int x = i; x < this.data.length - 1; x++) {  
                data[x] = data[x + 1];  
           }  
           this.index--;  
      }  
      /**  
       * @param args  
       * @throws Exception  
       */  
      public static void main(String[] args) throws Exception {  
           CustomArrayListImpl list = new CustomArrayListImpl();  
           list.add("0");  
           list.add("1");  
           list.add("2");  
           list.add("3");  
           list.add("4");  
           System.out.println("After resizing :-");  
           list.add("5");  
           list.remove(4);  
           System.out.println(list.get(3));  
      }  
 }  


 Output:  
 index:0 list size:5  
 index:1 list size:5  
 index:2 list size:5  
 index:3 list size:5  
 index:4 list size:5  
 index:4 List size:10  
 After resizing :-  
 index:5 list size:10  
 Object getting removed:4  
 3  

Explanation:-
List initial size is set to 5 and it is increased dynamically every time with more 5 indexes.                        
Limitations:-
In Object array we need to provide the size at the time of initialization which is not required for ArrayList. ArrayList automatically assigns its size to 10.

If List is used in Multithreading environment, where two threads are operating on it. One Thread is iterating over it and another thread is adding element to it, then in that case it will throw ConcurrentModificationException.

In order to avoid ConcurrentModificationException, we need to work on the clone of original ArrayList.


Enjoy Programming:)