Sunday, August 26, 2012

Thread Programming Interview Questions in Java 2


Q) How to set & get Priority in Threads using java?

public class ThreadExample implements Runnable{

public  void run(){
System.out.println("Thread Starting");

{
for(int i=0;i<9;i++)
System.out.print(i);
}
}

public static void main(String args[]){
Thread t1=new Thread(new ThreadExample());
t1.start();

Thread t2= new Thread(new ThreadExample());
t2.start();

System.out.println("Thread 1 Priority"+t1.getPriority());

t2.setPriority(9);

System.out.println("Thread 2 Priority "+t2.getPriority());

}

}

Output
=============
Thread Starting
Thread Starting
012345678Thread 1 Priority5
Thread 2 Priority 5
012345678

Q) Difference between green thread and native thread in Java?
A) Native threads can switch between threads pre-emptively, switching control from a running thread to a non-running thread at any time. Green threads only switch when control is explicitly given up by a thread (Thread.yield(), Object.wait(), etc.) or a thread performs a blocking operation (read(), etc.).
On multi-CPU machines, native threads can run more than one thread simultaneously by assigning different threads to different CPUs. Green threads run on only one CPU.

Q)  Difference between thread and process?
A) Threads share the address space of the process that created it; processes have their own address space.
Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.
Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes.

Q) Thread Life Cycle?



Q) What is context switching in multi-threading?
A) When doing context switching on a single-core processor, the code responsible is executed on the only CPU which takes care of switching the threads.
The kernel is multi-threaded. It can execute on any core. When a core comes to need to swap threads, it invokes the part of the kernel responsible for selecting the next thread it should execute.

5)  What thread-scheduling algorithm is used in Java?
6)  What is thread-scheduler in Java?
7)  How do you handle un-handled exception in thread?
8)  What is thread-group, why its advised not to use thread-group in Java?
9)  Why Executor framework is better than creating and managing thread by application ?
10) Difference between Executor and Executors in Java?
10) How to find which thread is taking maximum cpu in windows and Linux server?


Q) In which class would you find the methods sleep() and yield()?  Thread class

Q) Can you notify a particular thread? :   No

Q) How to make a normal thread as daemon thread?
A) We should call setDaemon(true) method on the thread object to make a thread as daemon thread.

Q) Give one good example of a daemon thread? : Garbage Collector is a low priority daemon thread.

Q) What are the two ways that a code can be synchronised?
A) Method can be declared as synchronised and A block of code be sychronised.


Q)What happens when I make a static method as synchronized?
A) Synchronized static methods have a lock on the class "Class", so when a thread enters a synchronized static method, the class itself gets locked by the thread monitor and no other thread can enter any static synchronized methods on that class. This is unlike instance methods, as multiple threads can access "same synchronized instance methods" at same time for different instances.


Q) Can a thread execute another objects run() method?
A) A thread can execute it's own run() method or another objects run() method.

Q) What are different ways in which a thread can enter the waiting state?
A) A thread can enter the waiting state by the following ways:
1. Invoking its sleep() method,
2. By blocking on I/O
3. By unsuccessfully attempting to acquire an object's lock
4. By invoking an object's wait() method.
5. It can also enter the waiting state by invoking its (deprecated) suspend() method.

Q) What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state, either from waiting, running or after its creation. When a task invokes its sleep() method, it returns to the waiting state from a running state.

Q)What is mutual exclusion? How can you take care of mutual exclusion using Java threads?
A)Mutual exclusion is a phenomenon where no two processes can access critical regions of memory at the same time. Using Java multithreading we can arrive at mutual exclusion. For mutual exclusion, you can simply use the synchronized keyword and explicitly or implicitly provide an Object, any Object, to synchronize on. The synchronized keyword can be applied to a class, to a method, or to a block of code. There are several methods in Java used for communicating mutually exclusive threads such as wait( ), notify( ), or notifyAll( ). For example, the notifyAll( ) method wakes up all threads that are in the wait list of an object.

Q) What is the difference between preemptive scheduling and time slicing?
A) Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then re-enters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

Q) run(): After a thread is started, via its start() method of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.

Q) wait(), notify(), and notifyAll() methods : Methods are used to provide an efficient way for thread inter-communication.

Q) Thread & States ?
A) A thread is an independent path of execution in a system. The high-level thread states are ready, running, waiting and dead.

Q) What are synchronized methods and synchronized statements?

Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

Q) What happens when a thread cannot acquire a lock on an object?
A) Yes. You can lock an object by putting it in a "synchronized" block. The locked object is inaccessible to any thread other than the one that explicitly claimed it. If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.

Q) What is the difference between process and thread?
A) A thread is a separate path of execution in a program. A Process is a program in execution.

Q) Why would you use a synchronized block vs. synchronized method?
A) Synchronized blocks place locks for shorter periods than synchronized methods.

Q) What is an object's lock and which objects have locks?
A) An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.

Q)Let`s say you have thread T1, T2 and T3, how will you ensure that thread T2 run after T1 and thread T3 run after T2?
(A) It can be achieved using join method of Thread class.

Q)How to know the thread priority?
A) isAlive() —it returns true when Thread is running
A) join() these two methods are used to know thread priority.

Q) What is a deadlock?
Deadlock is a situation where two or more threads are blocked forever, waiting for each other. This may occur when two threads, each having a lock on one resource, attempt to acquire a lock on the other's resource. Each thread would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. Deadlock ocurred on Two threads call Thread.join() on each other and Two threads use nested synchronized blocks to lock two objects and the blocks lock the same objects in different order.

Java Threading Programming Interview Questions 1


Q) Explain different way of using thread?
A) A Java thread could be implemented by using Runnable interface or by extending the Thread class. The Runnable is can be used for Thread because we can inherit one more class.

Q) What are the two types of multitasking?
A) process-based and Thread-based

Q) Thread Example by extending Thread Class
A) public class ThreadExample extends Thread{

public void run(){
System.out.println("Thread Starting");
for(int i=0;i<9;i++)
System.out.println(i);
}

public static void main(String args[]){
new ThreadExample().start();

}

}

Q) Thread Example by Implmenting runnable interface?
public class ThreadExample implements Runnable{

public void run(){
System.out.println("Thread Starting");
for(int i=0;i<9;i++)
System.out.println(i);
}

public static void main(String args[]){
Thread t1=new Thread(new ThreadExample());
t1.start();
}

}

Q) What is synchronization in respect to multi-threading in Java?
A) Synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one Java thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.
Example
=======
public class ThreadExample implements Runnable{

public  synchronized void run(){
System.out.println("Thread Starting");

{
for(int i=0;i<9;i++)
System.out.print(i);
}
}

public static void main(String args[]){
Thread t1=new Thread(new ThreadExample());
t1.start();

Thread t2= new Thread(new ThreadExample());
t2.start();

Thread t3= new Thread(new ThreadExample());
t3.start();

}

}

Q)Difference  Thread.start() & Thread.run() method?
A) Thread.start() method (native method) of Thread class actually does the job of running the Thread.run() method in a thread. If we directly call Thread.run() method it will executed in same thread, so does not solve the purpose of creating a new thread.

Q) Why do we need run() & start() method both. Can we achieve it with only run method?
A) We need run() & start() method both because JVM needs to create a separate thread which can not be differentiated from a normal method call. So this job is done by start method native implementation which has to be explicitly called. Another advantage of having these two methods is we can have any object run as a thread if it implements Runnable interface. This is to avoid Java’s multiple inheritance problems which will make it difficult to inherit another class with Thread.


Q) Can you declare a static method as synchronized?
A) Yes, we can declare static method as synchronized. But the calling thread should acquire lock on the class that owns the method.


Q) & A) Constrcutor in Thread Class : Thread(Runnable threadob,String threadName)

Q) & A) Metods available in the Runnable Interface? run()

Q) & A) What is the data type for the method isAlive() and this method is available in which class? : boolean, Thread

Q) What are all the methods available in the Thread class?
A)isAlive()
join()
resume()
suspend()
stop()
start()
sleep()
destroy()

Q) What are all the methods used for Inter Thread communication and what is the class in which these methods are defined?
A)wait(),notify() & notifyall() and Object class

Q) What is the mechanisam defind by java for the Resources to be used by only one Thread at a time? : Synchronisation

Q) Thread Priority values
A) MAX-10, MIN-1 NORMAL-5 and Method is setPriority()

Q)Default thread at the time of starting the program?: Main Method

Q) Thread States: new,runnable,blocked & dead

Q) The suspend()method is used to teriminate a thread? : False

Q) The run() method should necessary exists in clases created as subclass of thread? : True

Q) Which method waits for the thread to die ? : join() method

--wait(),notify(),notifyall() are defined as final & can be called only from with in a synchronized method
  wait(),notify(),notifyall() the wait() method only throws IOException

Q)Garbage collector thread belongs to which priority? : low-priority

Q) What is meant by daemon thread? In java runtime, what is it's role?
A) Daemon thread is a low priority thread which runs intermittently in the background doing the garbage collection operation for the java runtime system.

Java Exception Handling Programming Questions


Q) What are the two types of Exceptions?
A)Checked Exceptions and Unchecked Exceptions.

Q) What is the base class of all exceptions?
A) java.lang.Throwable

Q)If the overridden method in super class A throws FileNotFoundException, then the overriding method present in class B which is a subclass of class A can throw IOException. If the above statement true?
A) The overriding method can not throw any checked exception other than the exception classes or sub-classes of those classes which are thrown by the overridden method.
In the scenario described in question, the method in class B can not throw IOException but can throw FileNotFoundException exception.

Q)Can we have a try block without a catch block?
public class JExample {

public static void main(String args[]){
int i=0;
int j=4;

try
{
int k=j/i;
}
finally{
System.out.println("finally");
}
}
}

Output:
=======
finally
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.test.JExample.main(JExample.java:11)

Q) What is the difference between checked and unchecked exception handling in Java? What are the disadvantages of checked exception handling?
A) Checked exceptions are the one for which there is a check by the compiler that these exceptions have to be caught or specified with throws keyword. These kind of exceptions occur because of conditions which are out of control of the application like Network error, File Access Denied etc.
Unchecked exceptions are the one which arise because of logic written by the developer. e.g. Trying to access an array element which doesn’t exist.

Q)Explain try,catch and finally statements in Java ?
The try/catch statement encloses some code and is used to handle errors and exceptions that might occur in that code.

try {
   
} catch (Exception e) {
   
}finally{

}

Example
======

public class JExample {

public static void main(String args[]){
int i=0;
int j=4;

try
{
int k=j/i;
}catch(Exception e)
{
System.out.println("Exception caught");
e.printStackTrace();
}
finally{
System.out.println("finally");
}
}
}

Output:
======
Exception caught
java.lang.ArithmeticException: / by zero
at com.test.JExample.main(JExample.java:11)
finally


Q) If there is common code to be executed  in the catch block of 10 exceptions which are thrown from a single try block, then how that common code can be written with minimum effort?
A) In pre JDK 7, a method can be written and all catch blocks can invoke this method containing the common code.
In JDK 7, the | operator can be used in catch block in order to execute common code for multiple exceptions. e.g. catch(SQLException sqle | IOException ioe){}
4) Have you every created custom exceptions? Explain the scenario?
Ans: Custom exceptions are useful when the JDK exception classes don’t capture the essence of erroneous situation which has come up in the application. A custom exception can be created by extending any subclass of Exception class or by implementing Throwable interface.

Q) What is the difference between Validation, Exception and Error?
A)Validation is the process of making user enter data in a format which the application can handle.
Exception handling is the process when the application logic didn’t work as expected by the Java compiler.
Error occurs in a situation where the normal application execution can not continue. For e.g. out of memory.

Q) What is the purpose of finally block? In which scenario, the code in finally block will not be executed?
A) finally block is used to execute code which should be executed irrespective of whether an exception occurs or not. The kind of code written in a finally block consists of clean up code such as closing of database/file connection.
But JDK 7 has come up with try with resources block which automatically handles the closing of resources.

Q) Can a finally block exist with a try block but without a catch?
A)Yes. The following are the combinations try/catch or try/catch/finally or try/finally.

Q) What is the difference between throw and throws?
Throw is used to explicitly raise a exception within the program, the statement would be throw new Exception(); throws clause is used to indicate the exceptions that are not handled by the method. It must specify this behavior so the callers of the method can guard against the exceptions.
Throws is specified in the method signature. If multiple exceptions are not handled, then they are separated by a comma. the statement would be as follows: public void doSomething() throws IOException,MyException{}

Q) How to create Custom Exception in Java?
package com.test;

//NullException is the user exception defined
class NullException extends Exception{

int a;

public NullException(int i) {
i=a;
}

public String toString(){
return "Created NullException:"+a;
}
}
public class CustomException
{

public static void Divide(int a,int b) throws NullException{

int k=a/b;
throw new NullException(k);
}
public static void main(String args[]){

try{

CustomException c=new CustomException();
c.Divide(5, 2);
}catch(Exception e){
System.out.println("Main CustomExceptionm:" +e);
}finally{
System.out.println("Finally Exceuting");
}

}
}

Output
=========
Main CustomExceptionm:Created NullException:0
Finally Exceuting

Q) What are the differences between NoClassDefFoundError and ClassNotFoundException?
A) NoClassDefFoundError occurs when a class was found during compilation but could not be located in the classpath while executing the program.
For example: class A invokes method from class B and both compile fine but before executing the program, an ANT script deleted B.class by mistake. Now on executing the program NoClassDefFoundError is thrown.
ClassNotFoundException occurs when a class is not found while dynamically loading a class using the class loaders.
For example: The database driver is not found when trying to load the driver using Class.forName() method.


Q) Can a catch block exist without a try block?
A)No. A catch block should always go with a try block.

Q) What will happen to the Exception object after exception handling?
A)Exception object will be garbage collected.

Q)How does finally block differ from finalize() metho
Finally block will be executed whether or not an exception is thrown. So it is used to free resoources. finalize() is a protected method in the Object class which is called by the JVM just before an object is garbage collected.

Q) What is the purpose of throw keyword? What happens if we write “throw null;” statement in a Java program?
A) ”throw” keyword is used to re-throw an exception which has been caught in a catch block. The syntax is “throw e;” where e is the reference to the exception being caught. The exception is re-thrown to the client.
This keyword is useful when some part of the exception is to be handled by the caller of the method in which throw keyword is used.
The use of “throw null;” statement causes NullPointerException to be thrown.


Q) return statement in try,catch and finally ?
public class ExceptionDemo {

public int chkException(int arr[]){

int k=0;
int t=1,c=2,f=3;
try
{
for(k=0;k<5;k++)
System.out.println("arr Element"+arr[k]);
System.out.println("Try Catch");
return t;
}catch(Exception e){
System.out.println("Failed on exception"+e.getMessage());
System.out.println("Catch Retrun");
return c;
}finally{
System.out.println("Finally Return");
return f;
}
}

public static void main(String args[]){

int arr[]={1,4,5};

ExceptionDemo e=new ExceptionDemo();
e.chkException(arr);

}
}

Output
============
arr Element1
arr Element4
arr Element5
Failed on exception3
Catch Retrun
Finally Return

Wednesday, August 22, 2012

Thread Example in Java


public class ThreadExample extends Thread{

public synchronized  void run(){
for(int i=0;i<11;i++)
System.out.print(i);
System.out.println(" ");
}
public static void main(String args[]){
Thread t1=new ThreadExample();
Thread t2=new ThreadExample();
Thread t3=new ThreadExample();

t1.start();
t2.start();
t3.start();

t1.setPriority(MAX_PRIORITY);
System.out.println("Thread 1 Priority"+t1.getPriority());

System.out.println("Thread 1 Group"+t1.getThreadGroup());

System.out.println("State of Thread2"+t2.getState());

}
}

Tuesday, August 21, 2012

Basic String Operations in Java


public class StringOperations {

public static void main(String args[]){
String str1="Hello";
String str2="Ja va";
String str3="Hello";

// String Operations

System.out.println("String1 == String3"+ str1.equals(str3));
System.out.println("String2 at Index 2:"+str2.charAt(2));
System.out.println("Compare Str2 and Str3"+str2.compareTo(str3));
System.out.println("Compare str1 and str3"+str1.compareTo(str3));
System.out.println("String2 contains Ja: "+str2.contains("Ja"));
System.out.println("String is empty ?"+str1.isEmpty());
System.out.println("Sting HashCode"+ str1.hashCode());
System.out.println("Substring of String1"+str1.substring(2, 3));
System.out.println("Remove whitespaces in String2"+str2.trim());
System.out.println("Convert to LowerCase"+str2.toLowerCase());
System.out.println("Replace a with A"+str3.replace('a','A'));
}
}

OutPut:
========
String1 == String3true
String2 at Index 2: 
Compare Str2 and Str32
Compare str1 and str30
String2 contains Ja: true
String is empty ?false
Sting HashCode69609650
Substring of String1l
Remove whitespaces in String2Ja va
Convert to LowerCaseja va
Replace a with AHello

Vector Operations Using Java Programming


import java.util.Iterator;
import java.util.Vector;

public class VectorOperations {

public static void main(String args[]){
Vector vt=new Vector();

vt.add(21);
vt.add(12);
vt.add(57);
vt.add(29);
vt.add(43);

System.out.println("Vector"+vt);

//Adding elements in Vector
vt.add(2, 25);
System.out.println("Vector"+vt);
vt.addElement(23);
System.out.println("Vector"+vt);

//Vector Operations.
System.out.println("Capacity"+vt.capacity());
System.out.println("Conatains 43:"+vt.contains(43));
System.out.println("First element"+vt.firstElement());
System.out.println("Value at Index 4: "+vt.get(4));
System.out.println("Remove value at 3"+vt.remove(3));

vt.add(43);
vt.add(45);
vt.add(46);
vt.add(47);
vt.add(48);
vt.add(49);
vt.add(32);
vt.add(33);
vt.add(34);

System.out.println("Vector Elements afte insertion more than 10 elements");
Iterator it=vt.iterator();
while(it.hasNext())
System.out.print(" "+it.next());
}

}


Output:

Vector[21, 12, 25, 57, 29, 43, 23]
Capacity10
Conatains 43:true
First element21
Value at Index 4: 29
Remove value at 357
Vector Elements afte insertion more than 10 elements
 21 12 25 29 43 23 43 45 46 47 48 49 32 33 34

Queue Operations Using LinkedList in Java



import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;


public class QueueOperations {

public static void main(String args[]){

Queue que=new LinkedList();

//Insert elements into Queue
que.offer(12);
que.offer(25);
que.offer(75);
que.offer(9);

System.out.println("Queue"+que);

//Queue Operations
System.out.println("Queue Peek the elmenet  "+que.peek());
System.out.println("Queue Remove Element "+que.poll());

System.out.println("isEmpty :?"+que.isEmpty());
}
}

Output:
Queue[12, 25, 75, 9]
Queue Peek the elmenet  12
Queue Remove Element 12
isEmpty :?false

Stack Operations Using Java Programming


import java.util.Iterator;
import java.util.Stack;

public class StackOperations {

public static void main(String args[]){
Stack st=new Stack();

//Push the elments into stack
st.push(12);
st.push(9);
st.push(15);
st.push(76);
st.push(55);

//Elements in stack
System.out.println("Stack"+st);

//Pop the Elements
System.out.println("Top of the Stack:"+st.peek());
System.out.println("Pop the element from stack "+st.pop());

//Display elements using iterator
Iterator it=st.iterator();
while(it.hasNext())
System.out.println(it.next());

//Check stack is Empty or not
System.out.println("Stack is empty ?"+st.isEmpty());

}
}

Output:
Stack[12, 9, 15, 76, 55]
Top of the Stack:55
Pop the element from stack 55
12
9
15
76
Stack is empty ?false

Inserting an element into Linked List in C Programming Language


#include<stdlib.h>
typedef struct Node
{
        int data;
        struct Node *next;
}node;


void insert(node *pointer, int data)
{
       while(pointer->next!=NULL)
        {
                pointer = pointer -> next;
        }
        pointer->next = (node *)malloc(sizeof(node));
        pointer = pointer->next;
        pointer->data = data;
        pointer->next = NULL;
}

//Printing the elements in linkedlist.
void print(node *pointer)
{
        if(pointer==NULL)
        {
                return;
        }
        printf("%d ",pointer->data);
        print(pointer->next);
}

int main()
{
        node *start,*temp;
        start = (node *)malloc(sizeof(node));
        temp = start;
        temp -> next = NULL;

         // Inserting elements into linked List
          insert(start,2);
          insert(start,3);
          insert(start,4);

        // Printing the elements in linked list
         print(start->next);


}

Monday, August 20, 2012

Thread Interview Questions in Java


1) What is the difference between checked and unchecked exception handling in Java? What are the disadvantages of checked exception handling?
Ans: Checked exceptions are the one for which there is a check by the compiler that these exceptions have to be caught or specified with throws keyword. These kind of exceptions occur because of conditions which are out of control of the application like Network error, File Access Denied etc.
Unchecked exceptions are the one which arise because of logic written by the developer. e.g. Trying to access an array element which doesn’t exist.

Multiple exceptions in single catch block
catch(FileNotFoundExcpetion fne | Exception e){}

What are the differences between NoClassDefFoundError and ClassNotFoundException?
Ans: NoClassDefFoundError occurs when a class was found during compilation but could not be located in the classpath while executing the program.
For example: class A invokes method from class B and both compile fine but before executing the program, an ANT script deleted B.class by mistake. Now on executing the program NoClassDefFoundError is thrown.
ClassNotFoundException occurs when a class is not found while dynamically loading a class using the class loaders.
For example: The database driver is not found when trying to load the driver using Class.forName() method.

What is the purpose of throw keyword? What happens if we write “throw null;” statement in a Java program?
Ans: ”throw” keyword is used to re-throw an exception which has been caught in a catch block. The syntax is “throw e;” where e is the reference to the exception being caught. The exception is re-thrown to the client.
This keyword is useful when some part of the exception is to be handled by the caller of the method in which throw keyword is used.
The use of “throw null;” statement causes NullPointerException to be thrown.
The answers are brief. Do post your comments if you think I have missed anything or discuss any other exception handling question.

Java Collection Programming Interview Questions



What is the Difference between Enumeration and Iterator interface?
1. Enumeration contains 2 methods namely hasMoreElements() & nextElement() whereas Iterator contains three methods namely hasNext(), next(),remove().
2. Iterator adds an optional remove operation, and has shorter method names. Using remove() we can delete the objects but Enumeration interface does not support this feature.
3. Enumeration interface is used by legacy classes. Vector.elements() & Hashtable.elements() method returns Enumeration. Iterator is returned by all Java Collections Framework classes. java.util.Collection.iterator() method returns an instance of Iterator.
4. Enumeration act as read-only elements. Iterator we can manipulate the objects also like adding and removing the objects.

Where will you use Hashtable and where will you use HashMap?
The basic difference between a Hashtable and an HashMap is that, Hashtable is synchronized while HashMap is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Hashtable. While if not multiple threads are going to access the same instance then use HashMap. Non synchronized data structure will give better performance than the synchronized one.
If there is a possibility in future that - there can be a scenario when you may require to retain the order of objects in the Collection with key-value pair then HashMap can be a good choice. As one of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you can easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable. Also if you have multiple thread accessing you HashMap then Collections.synchronizedMap() method can be leveraged. Overall HashMap gives you more flexibility in terms of possible future changes.

Which one will provide the faster insertion of a new element into the middle positoin. Vector / ArrayList / LinkedList 
ArrayList and Vector both use an array to store the elements of the list. When an element is inserted into the middle of the list the elements that follow the insertion point must be shifted to make room for the new element. The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList allows for fast insertions and deletions.

List - this is an ordered list of objects, insertion order is maintained and retrieval order is in the list order but items can also be random accessed, duplicate items are allowed, generally allow storage of null values (the ones below do), generally fast to iterate and find items by position but slow to do lockups

ArrayList - Unsychronized, nulls allowed (fastest)
Vector - Synchronized, only slightly slower in tests of sizes under 100000
Stack - Synchronized, same speed as Vector, LIFO queue
LinkedList - Unsynchronized, allows two way iteration and modification of items (like a stack or queue)

Set - this a set of items with no duplicates (no two items can compare as equal), ordering is typically inconsistent over multiple set iterations depending on the implementation but you should assume the order is effectively random unless the set specifies ordered iteration, generally ok to iterate and fast to do lookups
HashSet - Unsychronized (fastest), slower than HashMap which it is built on, allows nulls
LinkedHashSet - Unsychronized, ordered by insertion, allows nulls
TreeSet - Unsychronized, ordered by the natural ordering of the items or a comparator provided at construction, allows nulls but there are issues with removing them

Map - Stores key/value pairs (maps keys to values) where the keys must be unique, order of iteration over keys, values, or pairs is highly dependent on the implementation of the map, allowed nulls also vary by implementation, generally very fast to lookup keys and slow to lookup values
LinkedHashMap - Unsychronized, all iterators are ordered based on insertion order of the original key (does not change if a key is reinserted), allows null values but null keys are not allowed
TreeMap - Unsychronized, iterators are ordered by the natural or comparator ordering of the keys, allows null keys and values but the comparator needs to understand them

Reference: http://docs.oracle.com/javase/tutorial/collections/TOC.html


Collection interview Questions in Java 2


ArrayList vs LinkedList

Adding new elements is pretty fast for either type of list. For the ArrayList, doing  random lookup using "get" is fast, but for LinkedList, it's slow. It's slow because there's no efficient way to index into the middle of a linked list. When removing elements, using ArrayList is slow. This is because all remaining elements in the underlying array of Object instances must be shifted down for each remove operation. But here LinkedList is fast, because deletion can be done simply by changing a couple of links. So an ArrayList works best for cases where you're doing random access on the list, and a LinkedList works better if you're doing a lot of editing in the middle of the list.

Array vs ArrayList vs LinkedList vs Vector in java

Array vs ArrayList:
ArrayList is much better than Array, when the size need to be increased dynamically. Efficiency is possible with arrays. ArrayList permits null elements.
ArrayList has group of objects. Array it treated as an object.

LinkedList vs Vector:
A vector is a growable array which can store many objects of different classes.
A linked list is a linear list where each item has a link to the next item in the list. It can be used to implement queue or stack operations.

ArrayList vs LinkedList
Array list is better than linked list for accessing elements.Linked list is better than array list to perform insertion and deletion operations at arbitrary locations.

Vector Vs ArrayList
Vector is synchronized whereas ArrayList is not. Even though Vector class is synchronized, still when you want programs to run in multithreading environment using ArrayList with Collections.synchronizedList() is recommended over Vector.
ArrayList has no default size while vector has a default size of 10.

What is an enumeration?
An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the collection. It allows sequential access to all the elements stored in the collection.

equals vs toString vs hashcod are methods in Object

Sort Diff b/w Arrays and Collections

Both use the same algorithm the only difference is type of input to them. Collections.sort() has a input as List so it does a translation of List to array. So this should be used when you are trying to sort a list. Arrays.sort is for arrays so the sorting is done directly on the array.

Collection Java Programming Interview Questions 1


Collection API ?
Java Collections framework API is a unified architecture for representing and manipulating collections. All collections frameworks contains interface, implementations and algorithms. Following are the benefits of collection framework.
Reduces programming efforts. - Increases program speed and quality.
Allows interoperability among unrelated APIs.
Reduces effort to learn and to use new APIs.
Reduces effort to design new APIs.
Encourages & Fosters software reuse.
Collection contains six interfaces.
Set, List and SortedSet: extends collection interface
Map and SortedMap : don’t extend collection interface.a

What is HashMap and Map?
Maps stores key Value pair, and Hashmap is class that implements that using hashing technique.

Diff  HashTable Vs HashMap Vs HashSet

Hashtable
Hashtable is basically a datastructure to retain values of key-value pair. Doesnot allow null for key and values
It is synchronized. So it comes with its cost. Only one thread can access in one time
Synchronized means only one thread can modify a hash table at one point of time. Any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.

Hashtable<Integer,String> rank= new Hashtable<Integer,String>();

rank.put(1,"A");
rank.put(1,"B");
rank.put(1,"C");

rank.put(null,"E"); NullPointerException at runtime

System.out.println(rank.get(1));
System.out.println(rank.get(2));


HashMap
Like Hashtable it also accepts key value pair.Allows null values
It is unsynchronized. So come up with better performance
By using following command Hashmap can be synchronized.
Map m = Collections.synchronizedMap(hashMap);

HashMap<Integer,String> Lang= new HashMap<Integer,String>();

Lang.put(1, "java");
Lang.put(2, null);

HashSet
HashSet does not allow duplicate values.
It can be used where you want to maintain a unique list. You also use its contain method to check whether the object is already available in HashSet.
It provides add method rather put method.

HashSet<String> str= new HashSet<String>();

str.add ("Apple");
str.add ("Boy");
str.add ("Cat");

if (str.contains("Apple"))

Iterator and implementation
An iterator is an object that enables a programmer to traverse a collection.
Iterator iter = list.iterator();
while (iter.hasNext()) {
    System.out.print(iter.next());
    if (iter.hasNext())
      System.out.print(", ");
}

Diff Iterator Vs ListIterator
Iterator : Enables you to traverse through a collection in the forward direction only, for obtaining or removing elements
ListIterator : extends Iterator, and allows bidirectional traversal of list and also allows the modification of elements.


Interface Implementation:


Implementations
InterfaceArrayBalanced TreeLinked ListHash table
ListArrayList LinkedList 
Map TreeMap HashMap
Set TreeSet HashSet
DequeArrayDeque LinkedList 


Adding assertion Methods to Selenium Library



Add following code to user extensions js file

Method is getCurrentTime and it returns the currenTime\

// Return the currentTime in the format HH:MM:SS

Selenium.prototype.assertCurrentTime = function(locator,value) {

   var expValue = value; //Getting excepted Value

   // Get Actual Value
   var d = new Date();
        var curr_hour = d.getHours();
        var curr_min = d.getMinutes();
        var curr_sec = d.getSeconds();

        var actValue = curr_hour+':' + curr_min + ':'+ curr_sec;

  //Doing assertion for excepted and Matches Value
   Assert.matches(expValue, actValue);
};

Adding new method to Selenium User Extensions

Below steps are required for adding the method to user extension js file. User can use the following method "getCurrentTime" as selenium function for returning the currentTime.


Add following code to user extensions js file

Method is getCurrentTime and it returns the currenTime\

// Return the currentTime in the format HH:MM:SS

Selenium.prototype.getCurrentTime = function(currentTime){

        var d = new Date();
        var curr_hour = d.getHours();
        var curr_min = d.getMinutes();
        var curr_sec = d.getSeconds();

        currentTime = curr_hour+':' + curr_min + ':'+ curr_sec;
        return currentTime;

};

Linked List Operations in Java Using LinkedList Utility Class


package com.test;

import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class LinkedListFunctions {

public static void main(String args[]){
LinkedList list=new LinkedList();

//Adding elements in Linked List
list.add(12);
list.add(17);
list.add(4);
list.add(45);
list.add(3);

// Printing elements in Linked List;
System.out.println(list);

//Printing the elements using iterator
Iterator itr=list.iterator();
while(itr.hasNext())
System.out.println(itr.next());

//Adding elements First and Last
list.addFirst(1);
System.out.println(list);

list.addLast(99);
System.out.println(list);

System.out.println("Get the size of List"+list.size());

//Sort the list using Collections Sort
Collections.sort(list);
System.out.println(list);

//Get the sublist from list
System.out.println(list.subList(2, 4));

//Stack Operations Using Linked List
System.out.println(list.peek());
System.out.println(list.poll());
System.out.println(list.pop());

}
}

Sunday, August 19, 2012

Count the number of leaf nodes in Binary Tree and Print the leaf nodes



package com.test;

public class BinaryTree {

 public static void main(String args[]){
 
    // Tree root node.
       int rootValue = 5;
       TreeNode rootnode = new TreeNode(rootValue);
       System.out.println("root node created. " + rootnode.nodeValue);
     
       // Inserting elements into binary tree
       insertion(rootnode, 3);
       insertion(rootnode, 7);
       insertion(rootnode, 1);
       insertion(rootnode, 4);
       insertion(rootnode, 6);
       insertion(rootnode, 8);
       
       System.out.println("Binary Tree");

       printTree(rootnode);

      System.out.println("Number of leaf nodes"+printLeafNodes(rootnode));
    
   }

// Counting and Printing the number of leaf nodes
  private static int printLeafNodes(TreeNode rootnode) {

  if(rootnode==null)
  return 0;
 if(rootnode.leftReference==null && rootnode.rightReference==null)
  {
  System.out.println(rootnode.nodeValue);
  return 1;
  }
 return printLeafNodes(rootnode.leftReference) + printLeafNodes(rootnode.rightReference);   
}

     
  // Printing Tree contents
   public static void printTree(TreeNode node) {
       if (node != null) {
           printTree(node.leftReference);
           System.out.println("Node" + node.nodeValue);
           printTree(node.rightReference);
       }
   }
}

Frequently Used Selenium Commands


}selenium.start() - Takes you to the location where selenium server is and runs the server.
}selenium.open() - Takes you to the provied URL/Website address.
}selenium.getTitle() - Get the title of the current browser window.
}selenium.windowFocus() - Get the focus on the current window.
}selenium.windowMaximize() - Maximizes the current window.
}selenium.close() - Close the session

Selenium Commands – “Selenese”


ActionsAccessors, and Assertions.
}Actions are commands that generally manipulate the state of the application. They do things like “click this link” and “select that option”. If an Action fails, or has an error, the execution of the current test is stopped.
Øselenium.click("id=gbztms");
Øselenium.select("id=citytravel_city", "label=Bangalore");
}Accessors examine the state of the application and store the results in variables, e.g. “storeTitle”. They are also used to automatically generate Assertions.
ØString Google = selenium.getTitle(); 
Øselenium.type("id=gbqfq", Google);
}Assertions are like Accessors, but they verify that the state of the application conforms to what is expected. Examples include “make sure the page title is X” and “verify that this checkbox is checked”.
ØassertTrue(selenium.isElementPresent("id=lga"));
ØassertEquals(selenium.getTitle(), "Google");

Finding the locators using selenium


Direct Reference  Using one of the direct references to the HTML element
Id=MyButton (note in this case, “Id =” is not even required)
Name=Description_Field
Value=ABC XYZ
Link=Contact Us

XPath, (XML Path Language)  :xpath, for locators starting with "//"
Reference: http://www.w3schools.com/xpath/default.asp Relatively straightforward to compose and read later down the track.
xpath=//img[@alt='The image alt text']
xpath=//table[@id='table1']//tr[4]/td[2]
xpath=//a[contains(@href,'#id1')]
xpath=//a[contains(@href,'#id1')]/@class
xpath=(//table[@class='stylee'])//th[text()='theHeaderText']/../td
xpath=//input[@name='name2' and @value='yes']
xpath=//*[text()="right"]
/html/body/div[1]/div[5]/div/table/tbody/tr/td/p/a[3] (An example bad XPath – it will break as soon as the page layout changes a bit)


DOM and CSS : 
dom=document.images[0] (the first image in the page)
css=H1.topic (the first heading with the class name of topic) or css=h1.topic[value="Topic Index"] (the heading with the specific text)
dom=document.forms['myForm'].myDropdown
dom=document.images[56]
dom=function foo() { return document.links[1]; }; foo();
css=a[href="#id3"]
css=span#firstChild + span

Keyboard and Coordinates
You can also go to the extreme of KeyDown and KeyUp

Selenium Example Using Junit: Home Page Test


Junit example Using Selenium

import static org.junit.Assert.*;

import com.thoughtworks.selenium.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class HomePageJunitTest {

Selenium selenium;

@Before
public void setUp() throws Exception {
selenium = new DefaultSelenium("localhost", 4444, "*iexploreproxy", "https://www.google.co.in/");
selenium.start();
}

@Test
public void testJunit() throws Exception {
selenium.open("/");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isElementPresent("id=gbqfq")) break; } catch (Exception e) {}
Thread.sleep(1000);
}

selenium.type("id=gbqfq", "selenium hq");
Thread.sleep(2000);
selenium.click("//span[@class=\"gbqfi\"]");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isElementPresent("link=Selenium - Web Browser Automation")) break; } catch (Exception e) {}
Thread.sleep(1000);
}

boolean res=selenium.isElementPresent("link=Selenium - Web Browser Automation");
assertEquals(res, true);
boolean res2=selenium.isTextPresent("What is Selenium? Selenium automates browsers.");
assertEquals(res2, true);
}

@After
public void tearDown() throws Exception {
selenium.stop();
}
}

Selenium Using testNG example: Home Page Test


Selenium Example Using testNG.

import com.thoughtworks.selenium.*;
import org.testng.annotations.*;

public class HomePageTest extends SeleneseTestCase {

@BeforeMethod
public void setUp() throws Exception {

selenium = new DefaultSelenium ("localhost", 4444, "*iexploreproxy", "https://www.google.co.in/");
selenium.start();
}

@Test
public void testHomePageTest() throws Exception {


selenium.open("/");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isElementPresent("id=gbqfq")) break; } catch (Exception e) {}
Thread.sleep(1000);
}

selenium.type("id=gbqfq", "seleniumhq");
Thread.sleep(2000);
selenium.click("//span[@class=\"gbqfi\"]");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isElementPresent("link=Selenium - Web Browser Automation")) break; } catch (Exception e) {}
Thread.sleep(1000);
}

verifyTrue(selenium.isElementPresent("link=Selenium - Web Browser Automation"));
verifyTrue(selenium.isTextPresent("What is Selenium? Selenium automates browsers."));
}

@AfterMethod
public void tearDown() {
selenium.close();
selenium.stop();
}
}