Tuesday, 22 March 2016

Difference between Hash Set and Hash Map

Ques : What is Difference between Hash Set and Hash Map?

                        Hash Map                       
 Hash Set
HashMap  is a implementation of Map interface
HashSet is an implementation of Set Interface
HashMap Stores data in form of key value pair
HashSet Store only objects
Put method is used to add element in map
Add method is used to add element is Set
In hash map hashcode value is calculated using key object
Here member object is used for calculating hashcode value which can be same for two objects so equal () method is used to check for equality if it returns false that means two objects are different.
HashMap is faster than hashset because unique key is used to access object
HashSet is slower than Hashmap

Wednesday, 16 March 2016

Remove white space from String

package com.tutorial4u;

import java.util.Scanner;

public class RemoveWwhiteSpace {
       public static void main(String[] args) {
             System.out.println("Enter any string : ");
             Scanner sc = new Scanner(System.in);
             String str = sc.nextLine();
             char[] c = str.toCharArray();
             StringBuffer sb = new StringBuffer();
             for(int i=0; i<c.length; i++){
                    if((c[i] !=' ')&& (c[i] !='\t')){
                           sb.append(c[i]);
                    }
             }
             System.out.println(sb);
       }


}

Output:

Enter any string :
Welcome To Tutorial4u
WelcomeToTutorial4u

Interview Question


Q : In how many ways you can create string objects in java?

There are two ways to create string objects in java. One is using new operator and another one is using string literals. The objects created using new operator are stored in the heap memory and objects created using string literals are stored in string constant pool.

1
2
String s1 = new String("ashish"); //Creating string object using new operator
String s2 = "ashish";  //Creating string object using string literal

In case of new operator two object is created one is in heap and other one is in string constant Pool and object is pointing to heap object.

Q: What is difference between String and String Buffer ?

String
String Buffer
 String class are immutable.
 String Buffer class are mutable.
Object of String class are created using both new operator and string literal.
Object of  String Buffer class is created using only new operator .
In String class equals() and hash code method are override. 
 In String Buffer  equals() and hash code method are not override.
In Case of String consume more memory.
 In case of String Buffer consume less memory.
In case of String object are stored String constant pool as well as heap memory.
 In case of String Buffer object are stored only in heap memory

No of Occurrence in Array

package com.tutorial4u; import java.util.HashMap; /************************************************************  No of Occurrence in Array...