Thursday, September 25, 2014

How to remove duplicate of LinkedList ?

How to remove duplicates of a LinkedList ?

This is one of the most frequently asked java question in oracle interview. There can be n number of ways to do the task, below program demonstrates a simple way of doing this.



import java.util.*;
class RemoveLinkedListDuplicate
{ 
 public static void removeDuplicate()
 {
  LinkedList l=new LinkedList();
  l.add("J");
  l.add("A");
  l.add("V");
  l.add("A");
  l.add("J");
  l.add("A");
  l.add("V");
  l.add("A");
  System.out.println(l);
  LinkedHashSet lhs=new LinkedHashSet(l);
  LinkedList ll=new LinkedList(lhs);
  System.out.println(ll);
 }
 public static void main(String[] args) 
 {
  removeDuplicate();
 }
}

Output of the Above example :


Wednesday, September 24, 2014

catching multiple exception in Java: java 1.7 update



Did you know from java 1.7 you can catch multiple exceptions in a single catch block ?

Until java 1.6 if we wanted to catch multiple exceptions in a single java program we have to write multiple catch blocks.

For Example in Java 1.6 environment

class ExceptionTest
{

                public static void main(String[] args)
                {
                                try
                                {
                                                int num1=Integer.parseInt(args[0]);
                                                int num2=Integer.parseInt(args[1]);
                                                int result=num1/num2;
                                }
                                catch (ArithmeticException e)
                                {
                                                System.out.println(e.getMessage());
                                } 
                                catch (ArrayIndexOutOfBoundsException e)
                                {
                                                System.out.println(e.getMessage());
                                } 
                                catch (NumberFormatException e)
                                {
                                                System.out.println(e.getMessage());
                                }
                               
                }
}

This leads to duplicity of code making program lengthy and quite tough to read.

But from java 1.7 we can catch multiple exceptions in a single catch block. Above example code can be rewritten in Java 1.7 and higher version as. 


class ExceptionTest
{

                public static void main(String[] args)
                {
                                try
                                {
                                                int num1=Integer.parseInt(args[0]);
                                                int num2=Integer.parseInt(args[1]);
                                                int result=num1/num2;
                                }
                                catch (ArithmeticException |NumberFormatException |ArrayIndexOutOfBoundsException e)
                                {
                                                System.out.println(e.getMessage());
                                }                             
                }
}

Rules to catch multiple exceptions

  1. Exception type parameters must be separated by a pipe symbol.
  2. We are not allowed to pass alternate exception in a multi exception catch block. Violation it will lead to a compile time error.
  3. By default variable in multi exception catch block is implicitly final, hence no other assignment on the same variable are allowed. Violation the rule will give a compile time error.
     

      NOTE
·         Byte code generated for above example using java 1.6 and java 1.7 + version have no changes.


Three cursor of Collection : Enumeration, Iterator, ListIterator

Why do we need Cursor?

If we want to retrieve elements from the List one by one , then cursor is required. Java provides three cursor in Collection .

  1. Enumeration
  2. Iterator
  3. ListIterator

Enumeration:

It is available since java 1.0 and can be used only on legacy classes. We can perform only read operation on enumeration object. Enumeration has only two methods.

Methods in enumeration
  •  hasMoreElement() 
  • nextElement()
How to get Enumeration object ?
To get a Enumeration object we should use elements() method from Vector class.

Example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import java.util.*;
class EnumerationDemo 
{
	public static void main(String[] args) 
	{
		Vector v=new Vector();
		v.add("A");
		v.add("B");
		v.add("C");
		Enumeration e=v.elements();
		while(e.hasMoreElements())
		{
			String s=(String)e.nextElement();
			System.out.println(s);
		}
	}
}
Output of the above program:

EnumerationDemo.Java 
Limitation of Enumeration

1.       Can only perform read operation.
2.       Can only be operated on legacy classes.

Iterator

Iterator is a universal cursor and can be applied on any Collection object. Unlike Enumeration it can perform read and remove operations.

Methods of Iterator Interface
1.       hasNext()
2.       next()
3.       remove()

How to get Iterator object ?
To get a Iterator object we should use iterator() method of Collection Interface.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.util.*;
class IteratorDemo 
{
	public static void main(String[] args) 
	{
		ArrayList al=new ArrayList();
		for(int i=0; i<=10;i++)
		{
			al.add(i);
		}
		Iterator i=al.iterator();
		while(i.hasNext())
		{
			Integer in=(Integer)i.next();
			if(in%2==0)
			{
			System.out.print(in);
			System.out.println(" The number is Even");
			}
			else
			{
				i.remove();
			}			
			
		}
		System.out.println(al);
	}
}

Output of the above program:

IteratorDemo.Java Output

Limitation of Iterator

It is unidirectional cursor hence can only move forward.

ListIterator

ListIterator is given to provide facilities like moving backward and forward in a list, adding an object, replacing an object etc. This cursor can be operated on any List Object. It is a bi-directional cursor.

Methods of ListIterator Interface

public boolean hasNext()


These methods are provided to facilitate the forward direction relation operation.
public Object next()

public int lastIndex()

public boolean hasPrevious()

These methods are provided to facilitate the backward direction relation operation.
public Object previous()

public int previousIndex()

public void add(Object obj)

These methods are provided to facilitate misc. Operations.
public void set(Object obj)

public void remove()

How to get ListIterator object ?
To get a ListIterator object we should use listIterator() method of List Interface.

Example:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.*;
class ListIteratorDemo  
{
	public static void main(String[] args) 
	{
		LinkedList l=new LinkedList();
		l.addFirst("J");
		l.add("A");
		l.add("V");
		l.addLast("A");
		System.out.println(l);
		
		ListIterator li=l.listIterator();
		while(li.hasNext())
		{
			String data=(String)li.next();
			if(data.equals("A"))
			{
				li.set("K");				
			}
		}
		System.out.println(l);
	}
}


Summary of three Cursor


Properties
Enumeration
Iterator
ListIterator
Is legacy ?
Yes
No
No
Access
Can only read
Read and remove
Read, replace, remove, add
How to get object ?
elements() method of Vector class
iterator() method of Collection interface
listIterator() method of List interface.
Direction
Unidirectional
Unidirectional
Bidirectional



Tuesday, September 23, 2014

Stack class in Java : A complete overview

Stack

Stack is the subclass of Vector and implements Serializable, Clonable, Collection and List interface. Stack is the representation of LIFO data structure in Java.
  1. Underlined data structure is Stack (LIFO). 
  2. Heterogeneous data elements are allowed.  
  3. Null insertion is allowed. 
  4. Duplicates are allowed. 
  5. Insertion order is preserved.


Constructor
Stack s=new Stack() //Creates an empty Stack

Methods
push(Object obj)
Insert an element on top of Stack
pop()
Remove and return an element from the top of Stack.
peek()
Return an element from the top of Stack.
search(Object o)
Return the offset if the passed object is found in Stack, -1 otherwise.

Example:

import java.util.*;
class StackDemo
{
public static void main(String[] args)
{
Stack s=new Stack();
for(int i=1;i<=5;i++)
{
s.push(i);
}
System.out.println(s.peek()); //Returns the element at the top of stack
System.out.println(s.pop()); //Remove and returns the element from top of Stack
System.out.println(s.search(3));
System.out.println(s.search(10));
}
}

Output of the above program :

                

Diagrammatic representation of the above program :


Note

If there are duplicate elements in the stack search(Object ob) method will return the offset of the element which is nearest to top of stack.

When to use Stack

Stack is useful when our requirement is to retrieve the element which came last or which added last. In other terms we can say that if we want to retrieve the latest inserted element then we should go for Stack.

Monday, September 22, 2014

Xicom Technologies Ltd hiring Java/J2ee Developer


Company name : Xicom Technologies Ltd

Location :New Delhi

Position : Java/J2ee Developer

Experience :  1 - 5+ Years


JAVA / J2EE Developers 


DESIRED CANDIDATE PROFILEMust have expert knowledge of Java, J2EE (Servlets, JSP, EJB, Struts, XML) and Web Services (SOAP/REST/AXIS).

Minimum 1 experience working with Spring and Hibernate Frameworks.

Proficient in Oracle database concepts and SQL writing
EXPERIENCE LEVEL1 - 5+ Years
INDUSTRY TYPE / FUNCTIONAL AREAIT Software / Java Developers


How to apply: click here 

Method definition inside an interface in java 1.8 : Default method in Java

Did you know from java 1.8 you can define a method inside an interface?


As per the explanation from Oracle

An example that involves manufacturers of computer-controlled cars who publish industry-standard interfaces that describe which methods can be invoked to operate their cars. What if those computer-controlled car manufacturers add new functionality, such as flight, to their cars? These manufacturers would need to specify new methods to enable other companies (such as electronic guidance instrument manufacturers) to adapt their software to flying cars. Where would these car manufacturers declare these new flight-related methods? If they add them to their original interfaces, then programmers who have implemented those interfaces would have to rewrite their implementations. If they add them as static methods, then programmers would regard them as utility methods, not as essential, core methods.

Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.

Few important points.

  • To make a method as default method it must be started with the keyword default
  • You need not to override default method in the implementation class.
  • Default methods are by default available in the implementation class and can be invoked using an object of that class.


A simple example
//interface DefaultMethod.java

interface DefaultMethod {
      
       //abstract Method
       public void methodA();
      
       //static methods
       static void methodB()
       {
              System.out.println("Inside Method B");
       }
      
       //default Method
       default void newDefaultMethod()
       {
              System.out.println("\n Default Method");
       }
}


//class DefaultMethodImplementation.java which implements DefaultMethod interface.

public class DefaultMethodImplementation implements DefaultMethod {
      
       public void methodA(){           
              System.out.println("\n Inside A");      
       }

       public static void main(String[] args) {       
              DefaultMethodImplementation dmi=new DefaultMethodImplementation();  
              dmi.methodA();
              dmi.newDefaultMethod();          
       }

}

Output of the above Java Program:



Happy Learning :) 
Post your questions in the comment box.

Wednesday, September 17, 2014

LinkedList In Java: A Complete Overview

LinkedList

LinkedList is the subclass of List interface. LinkedList is an implementation of doubly linked list data structure.

LinkedList implements List as well as Serializable, and Clonable interfaces.

Few Important Points About LinkedList

  •  Underlined data structure is doubly linked list . 
  • Heterogeneous data elements are allowed.     
  • Null insertion is allowed. 
  • Duplicates are allowed. 
  • Insertion order is preserved.

     Constructor In ArrayList


LinkedList()
Constructs an empty list.

LinkedList(Collection<? extends E> c)
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.



Methods In ArrayList

In addition to methods which are available in List, Collection interface, there are several LinkedList specific methods which you can be used only on LinkedList object.

  • Void addFirst(Object o) //Adds a new node at first place
  • Void addLast(Object o) //Adds a new node at last place
  • Object removeFirst() //remove and return the object at first node
  • Object removeLast() //remove and return the object at last node
  • Object getFirst() //return the object at first node
  • Object getLast() //return the object at last node

//Sample Program For LinkedList

import java.util.*;
class LinkedListDemo
 {
public static void main(String [] args)
{
LinkedList l=new LinkedList();
l.add("10");
l.add("10");
l.add(null);
l.add(1,100);
l.set(1,"DHT");
l.addFirst("10");
System.out.println(l);
}
}

Output of the above program



Scenarios When To Choose LinkedList And When Not To.

LinkedList is best choice when our main function is insertion at middle or deletion from middle. LinkedList could be worst choice if our main function is retrial of data from middle of the List.

More details:


If we want to insert new node at 2 place, we need not to perform shift operation. 


If you want to go to Node 2 of the list , it will first go to node 1 since node 1 has the address of node 2 then it will go to node 2.

Think of the same problem when we have 10 millions elements in the LinkedList and at some point if you want to retrieve some data element at 10000 position, it will have to go through 9999 nodes starting from node 1.

Retrieval of data from the middle of list is a performance violating task in LinkedList.

Read about ArrayList here



 

© 2014 DieHardTechy . All rights resevered. Designed by Diehardtechy