Wednesday, 25 March 2015

Difference between Encapsulation and Abstraction

Abstraction: Abstraction means representing the essential features without showing the background details.It lets you focus on what the object does instead of how it does.For example: Mobile phone has features calling,messaging etc.A user can call or message without knowing technical details that how a call is connected,how voice is transfered over the network etc.Thus, hiding internal implementation datails and just highlighting the set of services offered is called as Abstraction.

                        Abstraction in java is achieved through interface and abstract class and methods.


                              abstract class MobilePhone

                                {

                                     public abstract call(int number);

                                     public abstract sendMsg(int number,String msg);

                            }


Encapsulation: Binding data and its functionality together into a single unit so that it cannot be accessed directly from outside is called as Encapsulation.

For Example:I have an account in SBI bank.I went to the bank and ask my balance.They will happily tell me my balance.Again,if i ask them to change my balance without withdrawing or depositing any thing,Will they..?. No because i don't have direct access to the property balance.Balance is private member of account class and we cannot directly modify it without using public methods withdraw() or deposit().This is encapsulation.


           Encapsulation in java is achieved through class and access modifier (mainly private ).Hiding data behind the methods is the central concept of encapsulation.If a class has all its member variables private then it is called as tightly encapsulated class.

                            

                           class EncapsulationTest

                                 {

                                       private int a;                                           

                                       private int b;


                                       public int getA()  {    }

                                       public int getB()  {    }

                                       public int setA()  {    }

                                       public int setB()  {    }
                               }


Advantages:

                       1) Security

                       2) Enhancement will become easy.

                       3) Improves modularity of the application.


Note: In the  case of abstraction you are hiding the implementation details from the user and showing only the set of services offered whereas in the case of encapsulation you are hiding the data members from the rest of your code in the application.

Monday, 23 March 2015

Difference between for each loop and an Iterator

package com.manish;
import java.util.*;
public class Test

{

    public static void main(String[] args)

    {

         List lst=new ArrayList();

         lst.add("Manish"); 

         lst.add("Nitesh");

        lst.add("Rupesh"); 

         lst.add("Shubham");

         lst.add("prerit");

// Using for  each we don't have a chance to remove object from the list.

        for(Object l:lst)

        {

            //    lst.remove("Rupesh");     /*    Not OK

 java.util.ConcurrentModificationException   */

        }

        System.out.println(lst);     

 //   O/P    [Manish, Nitesh, Rupesh, Shubham, prerit]

    

// Using iterator we have  a chance to remove  object from the list while iterating  using iterator object.

        Iterator it=lst.iterator();

        while(it.hasNext())

        {

            Object obj=it.next();

            if(obj.equals("Rupesh"))

            {

                 lst.remove("Rupesh");  /*  Not OK it will throw

      java.util.ConcurrentModificationException */

                it.remove();    // OK

            }   

        }

        System.out.println(lst);     

 //  O/P  [Manish, Nitesh, Shubham, prerit]

    }

}

Note: In addition,in the case of for each loop we can access the elements in the forward direction only.If you want to access the elements in both forward and reverse direction then you can use listIterator interface (subclass of Iterator interface).

Saturday, 21 March 2015

Q. How Map allows primitive or integer as key ?



Ans:Map allows object as key and value.In the case of primitive like int, autoboxing (introduced in java 1.5) is done by the compiller.So primitive int is converted to Integer object by the compiller automatically.Thus, Map allows primitive int as key.


                      e.g      package com.manish;

                                 import java.util.*;

                                public class Test

                                {

                                   public static void main(String[] args)

                                    {

                                           Map mp=new HashMap();

                                           mp.put(1, 2);      // OK from 1.5

                                     }

                                 }


The same code will give compillation error when compilled in java 1.4 or lower.


                      e.g      package com.manish;

                                 import java.util.*;

                                public class Test

                                {

                                   public static void main(String[] args)

                                   {

                                     Map mp=new HashMap();

                                     mp.put(1, 2);    // Not OK compillation error in 1.4 version

                                   }

                                 }

Friday, 20 March 2015

Q.Given an array of size 1000 having no's between 1 to 9. Find the number of times each element is repeated in the most efficient way?



                                package com.manish;

                                import java.util.Arrays;

                                public class OccurenceOfNumber 

                                 {


public static void main(String[] args)

{

int arr[]={2,5,8,9,2,1,1,5,5};

Arrays.sort(arr);

for(int i=1;i<arr.length;i++)

{

int low=binarySearchFirst(arr,i);

int high=binarySearchLast(arr,i);

int total=(high>=low && high!=-1 && low!=-1)?(high-low+1):0;

System.out.println(i+" : "+total+" times");

}

}

public static int binarySearchFirst(int arr[],int k)

{

int begin=0;

int end=arr.length-1;

int mid=-1;

while(begin<=end)

{

mid=(begin+end)/2;

if(arr[mid]< k)

{

begin=mid+1;

}

else{

end=mid-1;

}

}

return (begin<=end && begin>=0 && arr[begin]!=k)? -1:begin;

}

public static int binarySearchLast(int arr[],int k)

{

int begin=0;

int end=arr.length-1;

int mid=-1;

while(begin<=end)

{

mid=(begin+end)/2;

if(arr[mid] > k)

{

end=mid-1;

}

else {

begin=mid+1;

}

}

return (end>=begin && end>=0 && arr[end]!=k)? -1:end;

}

                                  }


Q. Given no's 12345.find the sum of all the digits example- 1+2+3+4+5.


                           package com.manish;

                           import java.util.Scanner;

                           public class SumOfDigits

                            {

public static void main(String[] args)

{

int num=new Scanner(System.in).nextInt();

int sum=0;

int input=num;

while(input !=0)

{

int lastdigit=input%10;

sum=sum+lastdigit;

input=input/10;

}

System.out.println(sum);

}

                            }

Q. Find factorial using recursion and iteration ?


                          package com.manish;

                          public class Factorial 

                           {

                              public static void main(String[] args)

{

System.out.println(factorialRecursion(3));

System.out.println(factorialIteration(3));

}

// using iteration

public static int factorialRecursion(int num)

{

if(num==0)

{

return 1;

}

return num*factorialRecursion(num-1);

}

public static int factorialIteration(int num)

{

int res=1;

while(num !=0)

{

res=res*num;

num--;

}

return res;

}

                   }


Q. You are given an array of integers, containing both +ve and -ve numbers. You need to find the two elements such that their sum is closet to zero.

                                    package com.manish;

                                    import java.util.Arrays;

                                    public class MinTest

                                      {

                                            public static void main(String[] args)

                                              {

                                                   int arr[]=new int[]{5,3,1,-8,-8,6};

minSum(arr);

                                              }

                                            public static void minSum(int arr[])

                                              {

                                                  int l, r , min_sum,min_left,min_right,tempsum = 0;

                                                   if(arr.length<2)

                                                   {

                                                        System.out.println("invalid input");

                                                    }

                                                    Arrays.sort(arr);

                                                   l=0;r=arr.length-1;

                                                  min_sum=arr[l]+arr[r];

                                                  min_left=l;

                                                  min_right=r;

                                                   while(l<r)

                                                     {

                                                        tempsum=arr[l]+arr[r];

                                                        if(Math.abs(tempsum) < Math.abs(min_sum))

                                                           {

min_left=l;

                                                                min_right=r;

                                                                min_sum=tempsum;

                                                             }

                                                        if(tempsum < 0) l++;

                                                        else r--;

                                                      }

                                                  System.out.println(arr[min_left]+" "+arr[min_right]);

}

                                   }