Sunday 17 September 2017

Write a java program to check two Strings are anagrams or not by sorting and comparing strings?

Java anagram program is very important program asked in java interview for freshers and experienced.
Two Strings are anagrams if they contain same characters but in different order.
Here are the steps to be followed to check two Strings are anagrams or not :
1) Take  two strings as input.
2) convert first string to character array .
3) Take each character from first string and get the index of that character in second string.If the index is present delete that character from second string.
4) Repeat the same step for all characters in First string .
5) Finally check the length of second string if the length is zero then both strings are anagrams else both are not anagrams.

Wednesday 13 September 2017

Interview Questions of Java Collections:

Now, we are going to discuss the most important topic of core java interview which is java collection framework. Here we will discuss collection framework in java interview questions and answers in detail.


(1) What is a collection in java?

Collection in java is a framework and collection allows a group of objects to be treated as a single unit. These objects can be stored, retrieved and manipulated as elements of the collection.


(2) Difference between Array and Collection?

Array

1)      Java array is fixed in size i.e the size of the array can't be increased and decreased once when it is declared.
2)      We can store both primitive types and objects in an array.
3)      Array consumes more memory.
4)      Performance point of view array is faster than a collection.

Collection
1)      Java collection is dynamic in nature i.e it can grow their size as needed.
2)      Collection store only objects.
3)      It consumes less memory.
4)      Performance point of view collection is not faster than an array.

(3) Difference between HashSet and TreeSet?

HashSet
1)      HashSet doesn't maintain any order of elements.
2)      The performance of HashSet is better for operations like add, remove, retrieve, etc.

TreeSet
1)      TreeSet maintains the ascending order of an element.
2)      The performance is not better than HashSet for the operations like add, remove, retrieve, etc.

(4) Difference between Iterator and ListIterator?

Iterator
1)      Iterator is the super interface of ListIterator interface.
2)      By the help of iterator interface, we can traverse the elements only in forward direction.
3)      Iterator can be used in List, Set, and Queue.

ListIterator
1)      ListIterator is the sub-interface of Iterator interface.
2)      By the help of list iterator interface, we can traverse the elements in both direction i.e forward and backward directions.
3)      ListIterator can be used with the List interface.

(5) How many ways, you can retrieve elements from a collection?

There are many ways we can retrieve the elements from the collection.
foreach loop
1)      Iterator interface
2)      ListIterator interface
3)      Enumeration interface

(6) Difference between Iterator and Enumeration?

Iterator
1)      Iterator can traverse both legacy and non-legacy elements.
2)      Iterator is a fail-fast.
3)      Iterator is slower than enumeration.

Enumeration
1)      Enumeration interface mainly used for legacy classes.
2)      Enumeration is not fail-fast.
3)      It is faster than Iterator interface

(7) Difference between Collection and Collections?

Collection is an interface whereas collections  is a class in java.



(8) Difference between Comparable and Comparator?

1)      Java comparable interface belongs to the java.lang package whereas java comparator interface belongs to the java.util package.

2)      Java comparable provides only one sort of sequence whereas Java comparator interface provides multiple sorts of sequences.

3)      In java comparable, there is one method compareTo() and in Java comparable, there is compare() method.


(9) Difference between ArrayList and Vector in java?

ArrayList
1)      ArrayList is a legacy class in java collection.
2)      ArrayList class is not synchronized.
3)      ArrayList class increases its size by 50% of the array size.

Vector
1)      Vector class is a legacy class in java collection.
2)      Vector class is synchronized class.
3)      Vector class increases its size by doubling the array size.

(10) Difference between HashMap and HashSet?

There is some difference between java HashMap and HashSet class.

HashMap
1)      HashMap class implements Map interface.
2)      HashMap class contains elements in the key-value combination.

HashSet
1)      HashSet class implements Set interface.
2)      HashSet class contains only single value, there is no key-value combination.

(11) Difference between ArrayList and LinkedList?

There are some differences between ArrayList and  LinkedList class.

ArrayList
1)      ArrayList uses a dynamic array to store the elements.
2)      ArrayList is good for the store and fetch data.

LinkedList
1)      LinkedList uses a doubly linked list to store data.
2)      LinkedList is good for manipulation of the data.

(12) Difference between HashMap and Hashtable?

HashMap
1)      HashMap class is not synchronized.
2)      HashMap class allows one null key and multiple null values.

Hashtable
1)      Hashtable class is synchronized.
2)      Hashtable class doesn't allow any null key and null values.

(13) Difference between List and Set?

List
1)      List interface contains dupicate elements.
2)      ArrayList, LinkedList, and Vector class implement List interface.
Set
1)      Set interface does not contains duplicate elements.
2)      HashSet, LinkedHashSet, and TreeSet implements Set interface.

(14) Difference between HashMap and TreeMap?

Java HashMap does not maintain insertion order of an element whereas Java TreeMap maintains the elements in ascending order.

(15) What is properties file?

Java properties file maintain the data in the form of key-value pair. We can create properties file using notepad.

(16) Difference between fail-fast and fail-safe?

Java fail-fast iterator throws ConcurrentModificationException when there is a structural modification in underlying collection whereas fail-safe does not throw any exception when they detect any structural modification as fail-safe iterators work with clones of underlying collection.

(17) How we can sort a list of an object?

1)      For the array of objects, we will use Arrays.sort() method.
2)      For the collection of objects, we will use collections.sort().


This java collection framework interview questions and answers will help you in any java collection interview related questions.

Sunday 10 September 2017

What is comparator interface? How to use?

Comparator Interface:


Java Comparator

Comparator is a interface in java which is available in java.util package.

Comparator is used to sort or order the objects of user-defined class.

As we know comparable interface contains only one method compareTo(Object) but comparator interface contains 2 methods which is compare(Object obj1, Object obj2) and equals(Object element).

Comparator interface provides multiple sorting sequence i.e you can sort the elements on the basis of any data member such as name, age, rollno, etc.

A comparison function, which imposes a total ordering on some collection of objects. Comparator can be passed to a sort method(such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparator can also be used to control the order of certain data structure(such as sorted sets and sorted maps) or to provide an ordering for collections of objects that don't have a natural ordering.


Methods of Comparator Interface

    public int compare(Object obj1, Object obj2) : This method compares the first object with second object.
    boolean equals(Object obj) : This method indicates whether some other objects is "equal to " this comparator.


Collections Class

Collections is a class in java, It is not a collection(interface), it is a collections(class) which provides us static method so that we can easily sort the elements of collections. If the elements of collection is a type of Set or Map then we will sort these elements easily by using treeSet and treeMap class but we cannot sort the elements of List if we want to sort the elements of List type , We have to use method of Collections's class so that we can easily sort the elements of List type.


Collections class extends only super class i.e Object class.


The methods of this class all throw a NullPointerException, if the collections or class objects provide them are null.

Method of Collections Class
public void sort(List list, Comparator c) : This method is used to sort the elements of List by the given Comparator.


Java Comparator Example
This is a comparator example, where we will sort the elements of List type on the basis of age and name. Here we will create 4 .java files.

File 1 : Student.java
class Student
{
int rollno;
String name;
int age;
Student(int rollno, String name, int age)
{
this.rollno = rollno;
this.name = name;
this.age = age;
}
}



File 2 : AgeComparator.java

In this java file, we will define the comparison logic based on age. If age of first object is greater than the second it will return positive value and if age of first object is less than the second object it will return negative value, if both will be equal, return 0.

import java.util.*;
class AgeComparator implements Comparator
{
public int compare(Student s1, Student s2)
{
if(s1.age == s2.age)
return 0;
else if(s1.age>s2.age)
return 1;
else
return -1;
}
}

File 3 : NameComparator.java

In this java file, we will define comparison logic based on name and we will use compareTo() method.

import java.util.*;
class NameComparator implements Comparator
{
public int compare(Student s1, Student s2)
{
return s1.name.compareTo(s2.name);
}
}

File 4 : Test.java

In this java file, we will sort the List on the basis of age and name.

import java.util.*;
class Test
{
public static void main(String args[])
{
ArrayList al = new ArrayList();
al.add(new Student(100, "salman", 19);
al.add(new Student(105, "ranvir", 9);
al.add(new Student(102, "varun", 29);
al.add(new Student(107, "arjun", 18);

System.out.println("sorting by name");
Collections.sort(al, new NameComparator());
for(Student st : al)
{
System.out.println(st.rollno+" " +st.name+" " +st.age);
}

System.out.println("sorting by age");
Collections.sort(al, new AgeComparator());
for(Student st : al)
{
System.out.println(st.rollno+" " +st.name+" " +st.age);
}
}
}

output :

1) sorting by name:


              107 arjun 18
              105 ranvir 9
              100 salman 19
              102 varun 29

2) sorting by age:
              105 ranvir 9
              107 arjun 18
              100 salman 19
              102 varun 29

What is Map? How to use map interface?

Map is an interface in java which is available in java.util.* package. Collection map interface contains keys and values and each keys and values are called objects.

Map contains only unique key and can be contains duplicate values.

Each key and value pairs are known as entry.

There are four classes that implements Map interface in java collection.

    HashMap class
    LinkedHashMap class
    HashTable class
    TreeMap class


Methods of Java Map Interface
There are some useful methods of collection map interface. These are

1) void clear()

This method removes all of the mapping from this map.

2) Object put(Object key, Object value)

This method is used to insert an key and value i.e entry in this map.

3) void putAll(Map map)

This method is used to insert the specified map in this map.

4) boolean containsKey(Object key)

This method returns true if this map contains a mapping for the specified key.

5) boolean containsValue(Object value)

This method returns true if this map maps one or more keys to the specified value.

6) Object remove(Object key)

This is used to remove or delete the entry for the specified key.

7) Object get(Object key)

This method returns the value for the specified key.

8) Set keySet()

This method returns a Set view of the keys contained in this map.

9) Set entrySet()

This method returns the Set view containing all the key and values.

10) int hashCode()

This method returns the hash code value for this map.

11) boolean isEmpty()

This method returns true if there is no key and value mapping.



Map.Entry Interface
Map.Entry interface is a child interface of Map interface and it provides method so that we easily get the key and get the value.

Methods of Map.Entry Interface
Map.Entry provides two method.

1) Object getKey()

It is used to get key.

2) Object getValue()

It is used to get the value.



Java Map Example
This is an example of Map interface.

import java.util.*;
class MapExample
{
public static void main(String args[])
{
//creating object of HashMap class
Map m = new HashMap();
m.put(1, "pink");//using put method to insert key and value
m.put(2, "red");
m.put(3, "yellow");
m.put(4, "orange");
m.put(5, "brown");
m.put(6, "pink");
//using Map.Entry interface
for(Map.Entry me : m.entrySet())
{
System.out.println(me.getKey()+" "+me.getValue());
}
}
}

output : 1 pink
              2 red
              3 yellow
              4 orange
              5 brown
              6 pink

In the above example, there is 1,2... is a key and pink, red... is value. In this program there is no duplicate key but there is duplicate value pink. In this above example we used HashMap class, we will learn in later this HashMap class.


Java Map Example 2
This is another example of java map where we will take duplicate elements and let's see what happens.

import java.util.*;
class MapExample2
{
public static void main(String args[])
{
//creating object of HashMap class
Map m = new HashMap();
m.put(1, "pink");//using put method to insert key and value
m.put(2, "red");
m.put(3, "yellow");
m.put(4, "orange");
m.put(5, "brown");
m.put(2, "black");//duplicate key
//using Map.Entry interface
for(Map.Entry me : m.entrySet())
{
System.out.println(me.getKey()+" "+me.getValue());
}
}

}

output : 1 pink
              2 black
              3 yellow
              4 orange
              5 brown

What is Map Collection?

A map collection refers to a set of maps that are compiled and organized for a specific purpose, such as research, education, or preservatio...