Friday, 5 August 2011

Java Interview Questions

Java Threads Interview Questions - 1

1)What is threaded programming and when is it used?

Threaded programming is normally used when a program is required to do more than one task at the same time. Threading is often used in applications with graphical user interfaces; a new thread may be created to do some processor-intensive work while the main thread keeps the interface responsive to human interaction.
The Java programming language has threaded programming facilities built in, so it is relatively easy to create threaded programs. However, multi-threaded programs introduce a degree of complexity that is not justified for most simple command line applications.

  2)Why are wait(), notify() and notifyall() methods defined in the Object class?

A: These methods are detailed on the Java Software Development Kit JavaDoc page for the Object class, they are to implement threaded programming for all subclasses of Object.

  3)Why are there separate wait and sleep methods?

A: The static Thread.sleep(long) method maintains control of thread execution but delays the next action until the sleep time expires. The wait method gives up control over thread execution indefinitely so that other threads can run.

  4)What's the difference between Thread and Runnable types?

A: A Java Thread controls the main path of execution in an application. When you invoke the Java Virtual Machine with the java command, it creates an implicit thread in which to execute the main method. The Thread class provides a mechanism for the first thread to start-up other threads to run in parallel with it.
The Runnable interface defines a type of class that can be run by a thread. The only method it requires is run, which makes the interface very easy to to fulfil by extending existing classes. A runnable class may have custom constructors and any number of other methods for configuration and manipulation.

  5)How does the run() method in Runnable work?

A: It may help to think of the run method like the main method in standard single threaded applications. The run method is a standard entry point to run or execute a class. The run method is normally only executed in the context of an independent Thread, but is a normal method in all other respects.

  6)A Thread is runnable, how does that work?

A: The Thread class' run method normally invokes the run method of the Runnable type it is passed in its constructor. However, it is possible to override the thread's run method with your own.

  7)Why not override Thread to make a Runnable?

A: There is little difference in the work required to override the Thread class compared with implementing the Runnable interface, both require the body of the run() method. However, it is much simpler to make an existing class hierarchy runnable because any class can be adapted to implement the run() method. A subclass of Thread cannot extend any other type, so application-specific code would have to be added to it rather than inherited.
Separating the Thread class from the Runnable implementation also avoids potential synchronization problems between the thread and the run() method. A separate Runnable generally gives greater flexibility in the way that runnable code is referenced and executed.

  8)What's the difference between a thread's start() and run() methods?

A: The separate start() and run() methods in the Thread class provide two ways to create threaded programs. The start() method starts the execution of the new thread and calls the run() method. The start() method returns immediately and the new thread normally continues until the run() method returns.
The Thread class' run() method does nothing, so sub-classes should override the method with code to execute in the second thread. If a Thread is instantiated with a Runnable argument, the thread's run() method executes the run() method of the Runnable object in the new thread instead.
Depending on the nature of your threaded program, calling the Thread run() method directly can give the same output as calling via the start() method, but in the latter case the code is actually executed in a new thread.

  9)Can I implement my own start() method?

A: The Thread start() method is not marked final, but should not be overridden. This method contains the code that creates a new executable thread and is very specialised. Your threaded application should either pass a Runnable type to a new Thread, or extend Thread and override the run() method.

  10)Do I need to use synchronized on setValue(int)?

A: It depends whether the method affects method local variables, class static or instance variables. If only method local variables are changed, the value is said to be confined by the method and is not prone to threading issues.

Monday, 11 July 2011

To find given string is palindrom or not using stack in java

Write a function to test if a string is a palindrome using a stack. You can push characters in the stack one by one. When you reach the end of the string, you can pop the characters and form a new string. If the two strings are exactly the same, the string is a palindrome. Note: Palindrome ignores spacing, punctuation, and capitalization. Test your program with the following test cases.
  1. Go Dog
  2. Madam, I'm Adam
  3. Madam, I'm not a palindrome 

Here I am creating 3 files       1. StackADT.java       2. JCStack.java            3. Palindrome.java

// 1.  StackADT.java

package Stack;
public interface StackADT
{
    public int size();
    public void push(char element);
    public String pop();


}


// 2.  2. JCStack.java  

 import Stack.*;
import java.io.*;
import java.util.*;
import java.lang.*;
public class JCStack implements StackADT
{
    Stack st=new Stack();
    int top=-1;
  
    public int size()
    {
        return st.size();
    }
    public boolean isEmpty()
    {
        return st.isEmpty();
    }
  
    public void push(char element)
    {
        Character c=element;
        try
        {
            st.push(new Character(element));
            top++;
        }
        catch (Exception e)
        {
        }
  
    }
    public String pop()
    {
        String str="";
        if(st.size()==0)
        {
            System.out.println("\nSorry stack is empty");
            System.exit(0);
          
        }
        else
        {

        int i=st.size();
        for (int j=0;j<i;j++ )
        {
         Character ob=ob=(Character)st.pop();
         str=str+ob.charValue();
        }
        }
      
        return str;
          
      
  
      
    }
    public void exit()
    {
        System.exit(0);
    }

}


3. 3. Palindrome.java

import java.util.Scanner;
import java.lang.Character;
class Palindrome
{
    public static void main(String[] args)
    {
                        JCStack ST=new JCStack();
                        Scanner sc=new Scanner(System.in);
                        int choice;
                        String el,el1;
                        String st="";
                        System.out.println("Please enter Enter you new string line");
                       
                        el1=sc.nextLine();

                        el1=el1.replaceAll(" ", ""); // removning places in string
                        el1=el1.replaceAll(",","");
                        el1=el1.replaceAll("'", "");
                       
                        el=el1.toLowerCase();      // converting all the characters to lower case
                       

                        while (true)
                        {
                            System.out.println("\nPlease enter you choice\n");
                            System.out.println(" 1 to insert or push \n 2 to check given string is palindrom");
                            System.out.println(" 3 to exit \n");
                            choice=sc.nextInt();
                            switch (choice)
                            {
                            case 1:

                               
                                int k=el.length();
                                for(int i=0;i<k;i++)
                                {
                                    char ch=el.charAt(i);
                                           
                                     ST.push(ch);   
                                                                  
                                   
                                }
                                break;       
                            case 2:
                               
                               
                                if(ST.size()!=0)
                                {
                                    String str=ST.pop();
                               
                                    if(el.equals(str))
                                    {

                                        System.out.println("\nString is palindrom\n");
                                    }
                                    else
                                    {
                                        System.out.println("\nString is not palindrom\n");
                                    }
                                }

                               
                                break;
                            case 3:
                                ST.exit();
                            default:
                                System.out.println("Plese choose correct choice");
                               
                           
                            }
                                   

                        }
       
    }
}

Saturday, 9 July 2011

Queue Implementation using Linked List in java

Here I am creating 3 files in order to implement the Queue using Linked list in java

1.QueueADT.java                   2. LLQueue.java              3. LLQueue_Test.java

//  QueueADT.java

package Queue;
public interface QueueADT<E>
{
    public Object getFront();
    public void enqueue(Object a);
    public Object dequeue();
    public boolean isEmpty();
   
}

// 2. LLQueu.java

import java.util.Scanner;
import Queue.*;
import java.util.*;
public class LLQueue<E> implements QueueADT<E>
{
    public ListNode front;
    public ListNode back;
   
    /*public LLQueue()
    {
        front=back=null;
    }*/
    // Test if the queue is logically empty, return true if empty else false
    public boolean isEmpty()
    {

        return front==null;
    }

    // Insert a new item in to queue;
    public void enqueue(Object x)
    {
        ListNode n=new ListNode(x);
        if(isEmpty())
            back=front=n;
        else
            back=back.next=n;
    }

    //Retun and remove the lest recently inserted item from the queue
   
    public Object dequeue()
    {
        if(isEmpty())
            throw new UnderflowException("Queue is empty");
        Object val=front.element;
        front=front.next;
        return val;
    }
   
    // get the least recently inserted element from the queue;

    public Object getFront()
    {
        if(isEmpty())
            throw new UnderflowException("Queue is empty");
        else
       
        return front.element;
    }
    // Make queue empty

    public void makeEmpty()
    {
        back=front=null;
    }
   
    // exit program
    public void exit()
    {
        System.exit(0);
    }
   
    // display all the itmes in the queue
    public void display()
    {
        if(!isEmpty())
        {

            ListNode current=front;
            while (current!=null)
            {
                System.out.println(current.element);
                current=current.next;
            }
        }
        System.out.println("\nQueue is empty\n");
    }
   
   
};

//Exception class for access in empty containers
 //* such as stacks, queues, and priority queues.
class UnderflowException extends RuntimeException
    {
        
        // Construct this exception object
        // Messages the error message
        public UnderflowException( String message )
        {
            super( message );
        }
    }
// class List Node
class ListNode
{
    public Object element;
    public ListNode next;

    // constructors
    public ListNode(Object Elem)
    {
        element=Elem;
    }

    public ListNode(ListNode n, Object Ele)
    {
        element=Ele;
        next=n;
    }

};
 
// LLQueue_Test.java

import java.util.*;
class Queue_Test
{
    public static void main(String[] args)
    {
        int choice,el;
     Scanner sc=new Scanner(System.in);
     LLQueue LLQ=new LLQueue();
        //size=sc.nextInt();
       
        while (true)
        {
            System.out.println("Please enter you choice\n");
            System.out.println(" 1 for insert or enqueue \n 2 for is Queue empty \n 3 to get front element \n 4 to dequeue the element");
            System.out.println(" 5 to display \n 6 to make Queue empty\n 7 to exit  ");
            System.out.print("\n Choice --> ");
            choice=sc.nextInt();
            switch (choice)
            {
            case 1:
                System.out.print("Please enter Enter your element --> ");
                el=sc.nextInt();
                LLQ.enqueue(el);
                System.out.println();
                break;
            case 2:
                System.out.println(LLQ.isEmpty());
            break;
            case 3:
                if(!LLQ.isEmpty())
                {

                    System.out.println("Front element is ");
                    System.out.println(LLQ.getFront());
                }
                else
                    System.out.println("\nArray stack is empty\n");
                break;
            case 4:
                System.out.println("\nPoped element is ");
                System.out.print(LLQ.dequeue());
                System.out.println();
                break;
            case 5:
                LLQ.display();
                break;
            case 6:
                LLQ.makeEmpty();
            break;
            case 7:
                LLQ.exit();
            default:
                System.out.println("Please choose correct choice");
               
           
            }
        }
    }
}

Stack implementation using Singly linked list

Here I am creating 3 files 1. StackADT.java          2. SLStack.java           3. SLStack_Test.java

// Save the following StackADT inter face code with the above mentioned name

public interface StackADT
{
    public int size();
    public boolean isEmpty();
    public Object top();
    public void push(Object element);
    public Object pop();


}

//  2. SLStack.java

import java.util.*;
class Node
{
    public Object element;
    public Node next;
    public Node()
    {
        this(null,null);
    }
    public Node(Object element, Node next)
    {
        this.element=element;
        this.next=next;
    }
   
    public Object getElement()
    {
        return element;
    }
    public Node getNode()
    {
        return next;
    }
    public void seElement(Object obj)
    {
        this.element=obj;
    }
    public void setNode(Node node)
    {
        this.next=node;
    }

}
public class SLStack implements StackADT
{
    private Node top;
    private int size;
    public boolean isEmpty()
    {
        return (size==0);
    }
    public void makeEmpty()
    {
        top=null;
        size=0;
    }
    public Object pop()
    {
        if (top==null)
        {
            return null;
        }
        Object val=top.getElement();
        top=top.getNode();
        size--;
        return val;
    }
    public void push(Object obj)
    {
        Node v=new Node(obj,top);
        size++;
        top=v;
    }
    public int size()
    {
        return size;
    }
    public Object top()
    {
        Node temp=top;
        if(!isEmpty())
       

        try
        {
            return temp.getElement();
        }
        catch (Exception e)
        {
            return e.getMessage();
        }
        else
            return null;

       
        //return null;
    }
    public void display()
    {
        Node current=top;
        while (current!=null)
        {
            System.out.println(current.getElement());
            current=current.next;
        }
       
    }
    public void exit()
    {
        System.exit(0);
    }

};

//  3. SLStack_Test.java

import java.util.*;
public class SLStack_Test
{
    public static void main(String[] args)
    {
     int choice,el;
     Scanner sc=new Scanner(System.in);
     SLStack SLS=new SLStack();
        //size=sc.nextInt();
       
        while (true)
        {
            System.out.println("Please enter you choice\n");
            System.out.println(" 1 for insert or push \n 2 for is Stack empty \n 3 to get top element \n 4 to pop the lement");
            System.out.println(" 5 to display \n 6 to exit");
            choice=sc.nextInt();
            switch (choice)
            {
            case 1:
                System.out.print("Please enter Enter your element --> ");
                el=sc.nextInt();
                SLS.push(el);
                System.out.println();
                break;
            case 2:
                System.out.println(SLS.isEmpty());
            break;
            case 3:
                if(!SLS.isEmpty())
                {

                    System.out.println("top element is ");
                    System.out.println(SLS.top());
                }
                else
                    System.out.println("\nArray stack is empty\n");
                break;
            case 4:
                System.out.println("\nPoped element is ");
                System.out.print(SLS.pop());
                System.out.println();
                break;
            case 5:
                SLS.display();
                break;
            case 6:
                SLS.exit();
            default:
                System.out.println("Please choose correct choice");
               
           
            }
        }

    }
}

Stack Array in java

Here I am implementing Stack Array in java with StackADT, I have created 3 files
 1. StackADT.java               2. AStack.java                     3. AStack_Test.java

// StackADT.java 

public interface StackADT
{
    public int size();
    public boolean isEmpty();
    public Object top();
    public void push(Object element);
    public Object pop();


}

// 2. AStack.java


public class AStack implements StackADT
{
    Object Array[];
    int top=-1;

    AStack(int size)
    {
     Array=new Object[size];
    }
   
    public int size()
    {
        return top;
    }

    public boolean isEmpty()
    {
        if (top<0)
        {
            return true;
        }
        else
            return false;
    }

    public Object top()
    {
        return Array[top];
    }

    public void push(Object element)
    {
        try
        {
                Array[++top]=element;
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
   

    }
    public Object pop()
    {
        try
        {
            Object result=Array[top];
        top=top-1;
        return result;
        }
        catch (ArrayIndexOutOfBoundsException e)
        {
            return e.getMessage();
        }
       
    }
    public void exit()
    {
        System.exit(0);
    }

   
}

// 3.  AStack_Test.java

import java.util.Scanner;
class AStack_Test
{
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        int choice,size,el;
        System.out.println("Please enter size of the Array stack");
        size=sc.nextInt();
        AStack AS=new AStack(size);
        while (true)
        {
            System.out.println("Please enter you choice");
            System.out.println(" 1 for insert or push \n 2 for is Stack empty \n 3 to get top element \n 4 to pop the lement");
            System.out.println(" 5 to exit");
            choice=sc.nextInt();
            switch (choice)
            {
            case 1:
                System.out.println("Please enter Enter your element");
                el=sc.nextInt();
                AS.push(el);
                break;
            case 2:
                System.out.println(AS.isEmpty());
            break;
            case 3:
                if(!AS.isEmpty())
                {

                    System.out.println("top element is ");
                    System.out.println(AS.top());
                }
                else
                    System.out.println("\nArray stack is empty\n");
                break;
            case 4:
                System.out.println("\nPoped element is\n ");
                System.out.println(AS.pop());
                break;
            case 5:
                AS.exit();
            default:
                System.out.println("Please choose correct choice");
               
           
            }
        }
    }
}

Java Collection Stack implementation

Here I am implementing Java collection stack, here I am creating three files
1 is StackADT.java. 2 JCStack.java. 3 JCStack_Test.java

// save it as StackADT
public interface StackADT
{
public int size();
public boolean isEmpty();
public Object top();
public void push(Object element);
public Object pop();


}

// save it as JCStack.java
import java.util.Scanner;
import java.util.Stack;
import java.util.EmptyStackException;
public class JCStack implements StackADT
{
Stack st=new Stack();
int top=0;
public int size()
{
return st.size();
}
public boolean isEmpty()
{
return st.isEmpty();
}
public Object top()
{
return st.peek();
}
public void push(Object element)
{
st.push(element);
top++;
}
public Object pop()
{
try
{
return st.pop();
}
catch (EmptyStackException e )
{
return e.getMessage();
}

}
public void exit()
{
System.exit(0);
}

}

// Save it as JCStack_Test.java
import java.util.Scanner;
class JCStack_Test
{
public static void main(String[] args)
{
JCStack ST=new JCStack();
Scanner sc=new Scanner(System.in);
int choice,el;
while (true)
{
System.out.println("Please enter you choice");
System.out.println(" 1 for insert or push \n 2 for is Stack empty \n 3 to get top element \n 4 to pop the lement");
System.out.println(" 5 to exit");
choice=sc.nextInt();
switch (choice)
{
case 1:
System.out.println("Please enter Enter your element");
el=sc.nextInt();
ST.push(el);
break;
case 2:
System.out.println(ST.isEmpty());
break;
case 3:
System.out.println("top element is ");
System.out.println(ST.top());
break;
case 4:
System.out.println("Poped element is ");
System.out.println(ST.pop());
break;
case 5:
ST.exit();
default:
System.out.println("Plese choose correct choice");


}
}
}
}

Singly linked List

import java.util.*;
class Elem
{
public Elem next;
public Object data;
};
class Link
{
static Elem front=null;
static Elem back=null;
public static void main(String[] args)
{
Link l= new Link();
Scanner sc=new Scanner(System.in);
int a;
while(true)
{

System.out.println("enter your choice\n 1 for insert\n 2 for display\n 3 for exit");
a=sc.nextInt();
switch (a)
{

case 1:
System.out.println("enter a number");
String b=sc.next();
l.insert(b);
break;
case 2:
l.display();
break;
case 3:
exit();
break;
default:
System.out.println("Please enter correct choice");


}
}
}
public static void insert(Object a)
{
Elem e=new Elem(); // Create a new list element.
e.data=a; // Set the data field.
if (front==null)
{
front=e; // Back element will be set below.

}
else
{
back.next=e; // Link last elem to new element.
}
back=e; // Update back to link to new element.
}

public static void display()
{
Elem curr=front;
while (curr!=null)
{
System.out.println(curr.data);
curr=curr.next;
}

}

public static void exit()
{
System.exit(0);
}
}

doubly Linked list in java

import java.util.*;
class Elem2
{
    public Elem2 next;
    public Elem2 prev;
    public Object data;

};
class  SimpleDoublyList
{
    static Elem2 front = null;
    static Elem2 back = null;
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        SimpleDoublyList ll=new SimpleDoublyList();
        while (true)
        {
            System.out.println("Please enter your choice\n 1 for insertion \n 2 for display \n 3 for delete\n 4 for exit");
            int a=sc.nextInt();
            switch (a)
            {
            case 1:
                System.out.println("Please enter data");
                String s=sc.next();
                ll.insert(s);
            break;
            case 2:
                ll.display();
            break;
            case 3:
                System.out.println("Enter the element that you want to delete");
                String el=sc.next();
                ll.delete(el);
            case 4:
                ll.exit();
            break;
            default:
                System.out.println("Please enter correct choice");

           
            }
        }
    }
    public static void insert(Object o)
    {
      Elem2 e=new Elem2();
      e.data=o;
      if (front==null)
      {
          front = e;
      }
      else
        {
          back.next=e;
        }
        e.prev=back;
        back=e;
     
    }
    public static void display()
    {
        for (Elem2 e=front;e!=null ;e=e.next )
        {
            System.out.println(e.data);
        }
    }
    private static void exit()
    {
        System.exit(0);
    }
    private static void delete(Object o)
    {

        Elem2 temp=front;
        Elem2 prev=null;
        do
        {
            if(temp.data.equals(o))
            {
                prev.next=temp.next;
                break;
            }
            prev=temp;
            temp=temp.next;
        }
        while (temp!=null);
        System.out.println("List after deletion");
        for (Elem2 e=front;e!=null ;e=e.next )
        {
            System.out.println(e.data);
        }


    }
}