Sunday, 1 November 2015

How to remove elements from HashSet



There are four ways to remove elements from Hashset.

      1)      Removing All Elements

The Simplest removal method, clear(), clears all of the elements from the set:

    public void clear()  

While there is no return value, you may get an UnsupportedOperationException thrown when working with read-only set.

      2)      Removing Single Elements

To remove a single element, you can use remove() method

    public boolean remove(Object element)  

Determining whether the element is in the set is done via the equals method of the element. If the element is present, the element is removed from the set and true is returned. If not found, false is returned. If a set is read only, the removing an element will throw UnsupportedOperationException.

      3)      Removing Another Collection

The third way to remove element is removeAll():

    public boolean removeAll(Collection c)  

The removeAll() method takes a Collection as an argument and removes from the set all instance of each element in the Collection passed in.The Collection passed in can be a Set or some other Collection. For example:-

{“a”,”b”,”c”,”d”,”e”}

And the collection passed in is

{“b”,”c”,”e”}

The resulting set would be

{“a”,”d”}

removeAll() returns true if the underlying set changed, or false or UnsupportedOperationException.

     4)      Retaining Another Collection

The retainAll() method works like removeAll(),but in opposite direction:

   public boolean retainAll(Collection c)  

Only those elements within the collection argument are kept in the original set. Everything else is removed. For example:-

{“a”,”b”,”c”,”d”,”e”}

And the collection passed in is

{“b”,”c”,”e”}

The resulting set would be

{“b”,”c”,”e”}


Happy Reading.

How to add element in ArrayList



You can add either a single element or a group of elements to the list.

      1)      Adding Single Elements

There are two varieties of the add() method to add a single element to the list .

    public boolean add(Object element)  
    public boolean add(int index,Object element)  

When called with only an element argument, the element is added to the end of the list. When add() is called with the both element and index arguments, the element is added at the specific index and any elements after it are pushed forward in the list.

For example:-

 List list=new ArrayList();  
 list.add(“a”);  
 list.add(“b”);  
 list.add(“c”);  
 list.add(1,“d”);  

Note:- Like Array, the index used by a List starts at zero.

Since all lists are ordered, the elements are held in the order in which they are added.Unless and until ,you specify the position to add the element as in list.add(1,“d”).
      
      2)      Adding Another Collection

You can add a group of elements to a list from another collection with the addAll() method:

    public boolean addAll(Object element)  
    public boolean addAll(int index,Object element)  

Each elemtn in the collection passed in will be added to the current list via the equivalent of calling the add() method on each element. If an index is passed to the method call, elements are added starting at that position, moving existing elements down to fit in the new elements. Otherwise, they are added to the end.

Note:- In both the cases, if list is read only, then an UnsupportedOperationException will be thrown.


Happy Learning J

What is Function Overriding and Function Overloading in Java



Over-Riding:- An override is a type of function which occurs in a class which inherits from another class. An override function “replaces” a function inherited from the base class, but does so in such a way that it is called even when an instance of its class is pretending to be a different type through polymorphism.

In simple words, method in base class is overridden in child class. The key benefit of overriding is the ability to define behavior that’s specific to a particular subclass type. The code snippet below should explain things better.

Sample Program:-

 /**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class SampleProgram {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           Car a = new Car();  
           Car b = new Porche();// Car reference ,but a Porche object  
           a.start();// Car version of start method called  
           b.start();// Porche version of start method called  
      }  
 }  
 class Car {  
      public void start() {  
           System.out.println("Generic method to start the car in Base class");  
      }  
 }  
 class Porche extends Car {  
      public void start() {  
           System.out.println("Porche method to start the car in child class");  
      }  
 }  

 Output  
 Generic method to start the car in Base class  
 Porche method to start the car in child class  

The rules for overriding are:-

                 -          The argument list must exactly match that of the overridden method. If they
                    don't match, you can end up with an overloaded method you didn't intend.

                 -          The return type must be the same as, or a subtype of, the return type declared
                    in the original overridden method in the superclass.

                 -          The access level can't be more restrictive than the overridden method's.

                 -          The access level CAN be less restrictive than that of the overridden method.

                 -          Instance methods can be overridden only if they are inherited by the subclass.
                   A subclass within the same package as the instance's superclass can override
                   any superclass method that is not marked private or final. A subclass in a
                   different package can override only those non-final methods marked public
                   or protected (since protected methods are inherited by the subclass).

                 -          The overriding method CAN throw any unchecked (runtime) exception,
                    regardless of whether the overridden method declares the exception.

                 -          The overriding method must NOT throw checked exceptions that are new
                    or broader than those declared by the overridden method. For example, a
                    method that declares a FileNotFoundException cannot be overridden by a
                    method that declares a SQLException, Exception, or any other non-runtime
                    exception unless it's a subclass of FileNotFoundException.

                 -          The overriding method can throw narrower or fewer exceptions. Just because
                    an overridden method "takes risks" doesn't mean that the overriding subclass'
                    exception takes the same risks. Bottom line: an overriding method doesn't
                    have to declare any exceptions that it will never throw, regardless of what the
                    overridden method declares.

                  -          You cannot override a method marked final.

                  -          You cannot override a method marked static.

                  -          If a method can't be inherited, you cannot override it.

Over-Loading:- Overloading is the action of defining multiple methods with the same name, but with different parameters. It is unrelated to either overriding or polymorphism. Functions in java could be overloaded by two mechanisms ideally:

-          Varying the number of arguments
-          Varying the Data type

The rules are simple:-

-          Overloaded methods MUST change the argument list.
-          Overloaded methods CAN change the return type.
-          Overloaded methods CAN change the access modifier.
-          Overloaded methods CAN declare new or broader checked exceptions.
-          A method can be overloaded in the same class or in a subclass. In other words,
                     if class A defines a doStuff(int i) method, the subclass B could define a
         doStuff(String s) method without overriding the superclass version that
                     takes an int. So two methods with the same name but in different classes
                     can still be considered overloaded, if the subclass inherits one version of the
                     method and then declares another overloaded version in its class definition.


Sample Program:-


 /**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class CalulateSum {  
      void sum(int a, int b) {  
           System.out.println("Integer Sum:" + (a + b));  
      }  
      void sum(double a, double b) {  
           System.out.println("Double Sum:" + (a + b));  
      }  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           CalulateSum calulateSum = new CalulateSum();  
           calulateSum.sum(3, 4);  
           calulateSum.sum(3.2, 4.8);  
      }  
 }  



 Output  
 Integer Sum:7  
 Double Sum:8.0  

Happy Learning :)

Monday, 12 October 2015

How to remove spaces from given string



Suppose you have a String str="hello my na me i s John". How will you remove the spaces between words.Its a very basic question asked in interview for freshers.

I have mentioned two ways to do the same problem one is using split function and another is using replace function.


Sample Program:-

/**  
  *   
  */  
 /**  
  * @author Dixit  
  *  
  */  
 public class RemoveSpaceInStrings {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           String str="hello my na me i s John";  
           removeSpaceWithSplitFunction(str);  
           removeSpcaseWithoutSplitFunction(str);  
      }  
      private static void removeSpcaseWithoutSplitFunction(String str) {  
            System.out.println("removeSpcaseWithoutSplitFunction:Resulting String is:-" +str.replace(" ", ""));  
      }  
      private static void removeSpaceWithSplitFunction(String str) {  
         String result = "";  
         String strArray[] = str.split(" ");  
         for (int i = 0; i < strArray.length; i++) {  
           result = result + strArray[i];  
         }  
         System.out.println("removeSpaceWithSplitFunction:Resulting String is:-" + result);  
      }  
 }  


 Output  
 removeSpaceWithSplitFunction:Resulting String is:-hellomynameisJohn  
 removeSpcaseWithoutSplitFunction:Resulting String is:-hellomynameisJohn


Enjoy Programming :)



Wednesday, 30 September 2015

Important String interview questions



Important String questions which are mostly asked in interviews.Many interviewer focus on String concepts to check the fundamentals of interviewee.Go through the below questions which will help you to improve your understanding about String.


1) Find the output of below program ?

 public class TestProgram {  
      public void method(Object o) {  
           System.out.println("Object ");  
      }  
      public void method(String s) {  
           System.out.println("String ");  
      }  
      public static void main(String a[]) {  
           TestProgram testProgram = new TestProgram();  
           testProgram.method(null);  
      }  
 }  

 Output:-  
 String   

Reason:- null value is considered as String which calls the method with String as an argument.

2) Find the output of below program ?

 public class TestProgram {  
   public static void main(String a[]) {  
    String s1=new String("Hello");  
    String s2=new String("Helloo");  
    System.out.println(s1=s2);  
   }  
 }  

Output:-  
 Helloo  

Reason:- String s2 value is assigned to s1 in System.out.println(s1=s2) statement.

3)  Find the output of below program ?

 public class TestProgram {  
      public void method(StringBuffer sb) {  
           System.out.println("StringBuffer Version");  
      }  
      public void method(String s) {  
           System.out.println("String Version");  
      }  
      public static void main(String a[]) {  
           TestProgram q = new TestProgram();  
           q.method(null);  
      }  
 }  

Output:- Compile time error.

Reason:- The method method(StringBuffer sb) is ambiguous for the type TestProgram.
If you comment the public void method(String s), then code works fine and it will print StringBuffer Version.

4) Find the output of below program ?

 public class TestProgram {  
      public static void main(String a[]) {  
           String s1 = new String("Hello");  
           String s2 = new String("s1");  
           System.out.println(s1 == s2);  
      }  
 }  


 Output:-  
 false  

Reason:- Both the instances s1 and s2 does not refer to the same object.They are referring to different object with different memory address.Hence equality comparison returns false whereas if we check the contents of both the strings using equals method, then it will return true.

5) Find the output of below program ?

public class TestProgram {  
      public static void main(String a[]) {  
           String s1 = new String("Hello");  
           StringBuffer s2 = new StringBuffer(s1);  
           System.out.println(s1 == s2.toString());  
           System.out.println(s1.equals(s2));  
      }  
 }  

 Output:-  
 false  
 false 

Reason:- first print statement returns false because both s1 and s2 are referring to distinct object with distinct memory address and second print statement returns false because the equals method from StringBuffer is not overridden from Object class, so it uses reference equality(==).

6) Find the output of below program ?

1:  public class TestProgram {  
2:       public static void main(String a[]) {  
3:            String obj = "hello";  
4:            String obj2 = obj;  
5:            obj2 = " world";  
6:            System.out.println(obj + " " + obj2);  
7:       }  
8:  }  

 Output:-  
 hello world 

Reason:- In line number 3,obj is referring to String literal "hello".In line 4,obj2 is referring to same String as referred by obj.In line 5,obj2 is referring to new String literal " world".

7) Find the output of below program ?

 public class TestProgram {  
      public static void main(String a[]) {  
           String x = "hello ";  
           x.concat("world");  
           System.out.println(x);  
      }  
 } 

 Output:-  
 hello  

Reason:- concat method called on String x creates a new String object which needs to be assigned to a reference variable.String x is still referring to original String literal "hello ".

8) How many String objects created below ?

 public class TestProgram {  
      public static void main(String a[]) {  
           String s1 = "Hello ";  
           String s2 = s1 + "john ";  
           s1.concat("pallavi");  
           s2.concat(s1);  
           s1 += "ashish";  
           System.out.println(s1 + " " + s2);  
      }  
 }  

 Output:-  
 Hello ashish Hello john 

8 Strings objects get created.

Reason:-
1 :- "Hello " object gets created in String pool.
2:- "john " gets created in String pool and lost because no String variable is directly referring to it.
3:- "Hello john " s2 gets created.
4:- "pallavi" gets created in String pool and lost because no String variable is directly referring to it.
5:- "Hello pallavi " gets created in String pool and lost because no String variable is directly referring to it.
6:- "Hello john Hello" gets created in String pool and lost because no String variable is directly referring to it.
7:- "ashish " gets created in String pool and lost because no String variable is directly referring to it.
8:- "Hello ashish" gets created in String pool.

9) How many String objects created below ?

 public class TestProgram {  
   public static void main(String a[]) {  
    String s1 = new String("Hello");  
    String s2 = new String("Hello");  
   }  
 }  

Answer:- 3

Reason:-
1:- first String literal object "Hello"  gets created in String pool.
2:- a new String object with the value "Hello" placed in Heap memory.
3:- another new String object with the value "Hello" placed in Heap memory.

10) Find the output of below program ?

 public class TestProgram {  
   public static void main(String a[]) {  
    StringBuffer str = "";  
   }  
 } 

Output:- Compile time error.

Reason:- In order to create a StringBuffer object ,we need to build an object explicitly like new StringBuffer(""); .whereas in case String we can directly assign the literal like String str="";

11) Find the output of below program ?

1:  public class TestProgram {  
2:    public static void main(String a[]) {  
3:     String str = "";  
4:     String str1="Hello";  
5:     System.out.println(str.length());  
6:     System.out.println(str1.length());  
7:     System.out.println(str1.charAt(0));  
8:     System.out.println(str1.charAt(5));  
9:    }  
10:  }  

Output:-  
 0  
 5  
 H  
 Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5  
      at java.lang.String.charAt(Unknown Source)  
      at TestProgram.main(TestProgram.java:9)  


Reason:- At line number 8, it gives an StringIndexOutOfBoundsException because String index starts from 0 .

12) How many String objects created below ?

 public class TestProgram {    
   public static void main(String a[]) {  
    String s1="Hello";  
    String s2="Hello";  
    String s3="Hello";  
   }  
 } 

Answer:- 1

Reason:- "Hello" String literal object gets created in String pool and s1,s2,s3 refers to the same literal object.

13) Difference between StringBuffer and String?
 refer to this link what is the differnce between StringBuffer and String?

14) Difference between String literal and String Object?
refer to this link difference between String literal and String object?


All the best :)

Wednesday, 23 September 2015

Fibonacci Problem :Calculate the sum (F(X) + F(X + 1) + ... + F(Y)) mod 1000000007, where F(N)=F(N-1)+F(N-2),N>=2



Interview question asked in OYO Rooms company.

You are given two non-negative integers X and Y, you have to calculate the sum
(F(X) + F(X + 1) + ... + F(Y)) mod 1000000007, where F(N)=F(N-1)+F(N-2),N>=2.

Input

The two non-negative integers X and Y.

Output

For each test case you have to output a single line containing the answer.
Since the answer can be huge i.e go out of the bounds of integers, You are required to print the answer MOD 10^9+7

Example

Input:
2 6
Output:
19

Explanation

The fibonacci series is like this  0 ,1, 1, 2, 3, 5, 8, 13, 21,....

For the test case, we need to calculate the sum of the Fibonacci series from its 2nd term till 6th. ( i.e 1 + 2 + 3 + 5 + 8 ) = 19%(10^9+7) = 19



import java.math.BigInteger;  
 import java.util.ArrayList;  
 import java.util.List;  
 import java.util.Scanner;  
 /**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class FibonacciProblem {  
      /**  
       * @param args  
       */  
      public static void main(String a[]) {  
           int mod = 1000000007;  
           Scanner sc = new Scanner(System.in);  
           int x = sc.nextInt();  
           int y = sc.nextInt();  
           List<Integer> list = new ArrayList<Integer>();  
           list = getFibo(y);  
           if (!list.isEmpty()) {  
                int sum = 0;  
                BigInteger result = BigInteger.valueOf(0);  
                for (int j = x; j <= y; j++) {  
                     sum = sum + list.get(j);  
                }  
                result = BigInteger.valueOf(sum % mod);  
                System.out.println("Result:" + result);  
           }  
      }  
      private static List<Integer> getFibo(int y) {  
           // TODO Auto-generated method stub  
           List<Integer> l = new ArrayList<Integer>();  
           int a = 0;  
           int b = 1;  
           if (y == 0) {  
                return l;  
           }  
           if (y == 1) {  
                l.add(a);  
                l.add(b);  
                return l;  
           } else {  
                l.add(a);  
                l.add(b);  
                for (int i = 2; i <= y; i++) {  
                     int sum = a + b;  
                     a = b;  
                     b = sum;  
                     l.add(sum);  
                }  
           }  
           return l;  
      }  
 }  


 Output  
 2  
 6  
 Result:19  


Enjoy Programming

How to find continuous sequence with largest sum


You are given an array of integers both positive and negative integers.Find the continuous sequence with largest sum.

For Example:

Input:-{2,-8,3,-2,4,-10}
Output:-5(i.e {3,-2,4})


/**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class LargestSumSequence {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           int a[]={2, -8, 3, -2, 4, -10};  
           System.out.println("Continuous sequence with Largest sum :"+getMaxSum(a));  
      }  
      public static int getMaxSum(int[] a) {  
           int maxsum = 0;  
           int sum = 0;  
           for (int i = 0; i < a.length; i++) {  
                sum += a[i];  
                if (maxsum < sum) {  
                     maxsum = sum;  
                } else if (sum < 0) {  
                     sum = 0;  
                }  
           }  
           return maxsum;  
      }  
 }  


Output:-  
 Continuous sequence with Largest sum :5 


Enjoy Programming