Java Interview Questions - MultiThreading

This set of Java Interview Questions covers MultiThreading topics like Threads, Synchronization, DeadLock, Thread Pool and more.

You can find the previous set of Interview Questions from here:

1. What is the difference between processes and threads?
A process is an execution of a program but a thread is a single execution sequence within the process. A process can contain multiple threads. A thread is sometimes called a lightweight process.
A JVM runs in a single process and threads in a JVM share the heap belonging to that process. That is why several threads may access the same object. Threads share the heap and have their own stack space. This is how one thread’s invocation of a method and its local variables are kept thread safe from other threads. But the heap is not thread-safe and must be synchronized for thread safety.
2. Explain different ways of creating a thread? Which one is preferred?
Threads can be used by either
  • Extending the Thread class.
    class Counter extends Thread {
        
        //method where the thread execution will start
        public void run(){
            //logic to execute in a thread   
        }
     
        //let’s see how to start the threads
        public static void main(String[] args){
           Thread t1 = new Counter();
           Thread t2 = new Counter();
           t1.start();  //start the first thread.
           t2.start(); //this starts the 2nd thread.
        }
    }
  • Implementing the Runnable interface.
    class Counter extends Base implements Runnable{
       
        //method where the thread execution will start
        public void run(){
            //logic to execute in a thread   
        }
     
        //let us see how to start the threads
        public static void main(String[] args){
             Thread t1 = new Thread(new Counter());
             Thread t2 = new Thread(new Counter());
             t1.start();  //start the first thread.
             t2.start();  //this starts the 2nd thread.
        }
    }
The Runnable interface is preferred, as it does not require your object to inherit a thread because when you need multiple inheritance, only interfaces can help you.
3. Briefly explain high-level thread states?
A Thread can have the below states:
  1. Runnable: A thread becomes runnable when you call the start( ), but does not necessarily start running immediately. It will be pooled waiting for its turn to be picked for execution by the thread scheduler based on thread priorities.
  2. Running: The processor is actively executing the thread code. It runs until it becomes blocked, or voluntarily gives up its turn with this static method Thread.yield( ). Because of context switching overhead, yield( ) should not be used very frequently
  3. Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish.A call to currObject.wait( ) method causes the current thread to wait until some other thread invokes currObject.notify( ) or the currObject.notifyAll( ) is executed.
  4. Sleeping: Java threads are forcibly put to sleep (suspended) with this overloaded method: Thread.sleep(milliseconds), Thread.sleep(milliseconds, nanoseconds);
  5. Blocked :Will move to runnable after chnage in I/O condition or when lock is acquired.
  6. Dead: The thread is finished working.
4. What is multithreading and what are the methods for inter-thread communication?
Multithreading is the mechanism in which more than one thread run independent of each other within the process. wait (), notify () and notifyAll() methods can be used for inter-thread communication and these methods are in Object class.
  • wait() : When a thread executes a call to wait() method, it surrenders the object lock and enters into a waiting state.
  • notify() or notifyAll() : To remove a thread from the waiting state, some other thread must make a call to notify() or notifyAll() method on the same object.
5. What's the difference between the methods sleep() and wait()?
  • The code sleep(1000); puts thread aside for exactly one second whereas the code wait(1000), causes a wait of up to one second.
  • A thread could stop waiting earlier if it receives the notify() or notifyAll() call.
  • The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.
6. Why wait, notify, and notifyall methods are defined in the Object class, and not in the Thread class?
Every Java Object has a monitor associated with it. The threads using that object can lock or unlock the monitor associated with the object. Wait and notify/notifyAll methods are responsible for acquiring and relinquishing the lock associated with the particular object. Calling wait causes the current thread to wait to acquire the lock of the Object, and calling notify/notifyAll relinquishes the lock and notify the threads waiting for that lock.
7. What do you understand by Synchronization?
Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption.

E.g. Synchronizing a function:
public synchronized void Method1 () {
    // Appropriate method-related code. 
}
E.g. Synchronizing a block of code inside a function:
public myFunction (){
    synchronized (this) { 
    // Synchronized code here.
  }
}
8. What are the disadvantages of synchronization?
The disadvantage of synchronize is it will end up in slowing down the program. Also if not handled properly it will end up in dead lock.
9. Why would you use a synchronized block vs. synchronized method?
Synchronized blocks place locks for shorter periods than synchronized methods.
10. When you will synchronize a piece of your code?
When you expect your code will be accessed by different threads and these threads may change a particular data causing data corruption.
11. What is a ThreadLocal class?
ThreadLocal is a handy class for simplifying development of thread-safe concurrent programs by making the object stored in this class not sharable between threads.
Below are some key points about ThreadLocal variables :
  • A thread-local variable effectively provides a separate copy of its value for each thread that uses it.
  • ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread
  • In case when multiple threads access a ThreadLocal instance, separate copy of Threadlocal variable is maintained for each thread.
  • Common use is seen in DAO pattern where the DAO class can be singleton but the Database connection can be maintained separately for each thread. (Per Thread Singleton)
12. What is deadlock?
When two threads are waiting each other and can’t precede the program is said to be deadlock. Deadlock may occur when two threads, each having a lock on the same resource, attempt to acquire a lock on the other's resource. Each thread would wait indefinitely for the other resource to release the lock, unless one of the user processes is terminated.
The thread deadlock can occur in conditions such as:
  1. two threads calling Thread.join() on each other.
  2. two threads use nested synchronized blocks to lock two objects and blocks lock the same objects in different order.
13. What is daemon thread and which method is used to create the daemon thread?
Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.
14. What is immutable object? How does it help in writing concurrent application?
An object is considered immutable if its state cannot change after it is constructed. Immutable objects are particularly useful in concurrent applications, since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state. Examples of immutable objects from the JDK include String and Integer.
Immutable objects greatly simplify your multi threaded program, since they are
  • Simple to construct, test, and use.
  • Automatically thread-safe and have no synchronization issues.
To create a object immutable You need to make the class final and all its member final so that once objects gets crated no one can modify its state. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.
15. What is Starvation? and What is a Livelock?
Starvation and livelock are much less common a problem than deadlock, but are still problems that every designer of concurrent software is likely to encounter.
  • LiveLock : Livelock occurs when all threads are blocked, or are otherwise unable to proceed due to unavailability of required resources, and the non-existence of any unblocked thread to make those resources available. In terms of Java API, thread livelock can occur in following conditions:
    1. When all the threads in a program execute Object.wait(0) on an object with zero parameter. The program is live-locked and cannot proceed until one or more threads call Object.notify() or Object.notifyAll() on the relevant objects. Because all the threads are blocked, neither call can be made.
    2. When all the threads in a program are stuck in infinite loops.
  • Starvation : Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by "greedy" threads. In Java, thread starvation can be caused by setting thread priorities inappropriately. A lower-priority thread can be starved by higher-priority threads if the higher-priority threads do not yield control of the CPU from time to time.
16. What is thread pool? Why should we use thread pools?
A thread pool is a collection of threads on which task can be scheduled. Instead of creating a new thread for each task, you can have one of the threads from the thread pool pulled out of the pool and assigned to the task. When the thread is finished with the task, it adds itself back to the pool and waits for another assignment.
One common type of thread pool is the fixed thread pool. This type of pool always has a specified number of threads running; if a thread is somehow terminated while it is still in use, it is automatically replaced with a new thread.
Below are key reasons to use a Thread Pool :
  1. Using thread pools minimizes the JVM overhead due to thread creation.
  2. You have control over the maximum number of tasks that are being processed in parallel (= number of threads in the pool).

Java Interview Questions - Exception

Here is a set of Java Interview Questions which focuses on Exceptions and the Exception Handling framework. You can find the previous set of Interview Questions from here:

1. What is an exception?
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
2. How does exception handling work in Java?
  1. It separates the working/functional code from the error-handling code by way of try-catch clauses.
  2. It allows a clean path for error propagation. If the called method encounters a situation it can’t manage, it can throw an exception and let the calling method deal with it.
  3. By enlisting the compiler to ensure that "exceptional" situations are anticipated and accounted for, it enforces powerful coding.
3. What are the different ways to generate an Exception?
There are two different ways to generate an Exception:
  1. Exceptions can be generated by the Java run-time system. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment.
  2. Exceptions can be manually generated by your code.Manually generated exceptions are typically used to report some error condition to the caller of a method.
4. What are the two types of Exception in Java?
Exceptions are of two types: Compiler-enforced exceptions, or checked exceptions and Runtime exceptions, or unchecked exceptions.
  • Compiler-enforced (checked) exceptions are instances of the Exception class or one of its subclasses — excluding the RuntimeException branch. The compiler expects all checked exceptions to be appropriately handled. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.
  • Runtime exception represent unexpected exceptional conditions which can be handled but not necessarily recovered from. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation.
5. Explain the User-defined or Custom Exceptions?
User defined Exceptions are the separate Exception classes defined by the user for specific purpose. An user defined exception can be created by simply sub-classing it to the Exception class. This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions.
Example:
class myCustomException extends Exception {
       // The class simply has to exist to be an exception
}
6. Does it matter in what order catch statements for FileNotFoundException and IOException are written?
Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.
7. What is error?
An Error indicates that a non-recoverable condition has occurred that should not be caught. Error, a subclass of Throwable, is intended for drastic problems, such as OutOfMemoryError, which would be reported by the JVM itself.
8. What is the difference between exception and error?
The exception class defines mild error conditions that your program encounters. Exceptions can occur when trying to open the file which does not exist, when the network connection is disrupted, or when operands being manipulated are out of prescribed ranges.
The error class defines serious error conditions that you should not attempt to recover from. In most cases it is advisable to let the program terminate when such an error is encountered.
9. What is the super class of java.lang.Exception
java.lang.Throwable, the parent class of all exception related classes.
10. Explain the significance of try-catch blocks?
Whenever the exception occurs in Java, we need a way to tell the JVM what code to execute. To do this, we use the try and catch keywords. The try is used to define a block of code in which exceptions may occur. One or more catch clauses match a specific exception to a block of code that handles it.
Eg:
try {
   // try block for code for which we want to catch exceptions.
} catch (Exception e) {
   // catch block to handle the exception.
}
11. What is the use of finally block?
The finally block encloses code that is always executed at some point after the try block, whether an exception was thrown or not. This is right place to close files, release your network sockets, connections, and perform any other cleanup your code requires.
If the try block executes with no exceptions, the finally block is executed immediately after the try block completes. It there was an exception thrown, the finally block executes immediately after the proper catch block completes.
12. What if there is a break or return statement in try block followed by finally block?
If there is a return statement in the try block, the finally block executes right after the return statement encountered, and before the return executes.
13. Can we have the try block without catch block?
Yes, we can have the try block without catch block, but finally block should follow the try block.
14. What is the difference throw and throws?
throws: Used in a method's signature if a method is capable of causing an exception that it does not handle, so that callers of the method can guard themselves against that exception. If a method is declared as throwing a particular class of exceptions, then any other method that calls it must either have a try-catch clause to handle that exception or must be declared to throw that exception (or its superclass) itself.
public void someMethod(g) throws someException {
      // Method body
}
throw: Used to trigger an exception. The exception will be caught by the nearest try-catch clause that can catch that type of exception. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.
throw new someException("Catch this one !!");

Core Java Interview Questions - Part 3

Here is the Third set of Core Java Interview Questions. You can find the previous set of interview questions from below :
1. Where and how can you use a private constructor.
Private constructor can be used if you do not want any other class to instanstiate the object , the instantiation is done from a static public method. This method is used when dealing with the factory method pattern when the designer wants only one controller (fatory method ) to create the object.
2. Can a top level class be private or protected?
No. A top level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected.
3. Differentiate between continue and break.
In break, control comes out of the loop whereas in continue control stops at “continue” statement. The remaining statements aren’t executed as control enters following loop.
4. What restrictions are placed on method overriding in Java Programming?
Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method.
5. Why equals should be overridden?
Two objects are considered equal if referring to the same object as the equals method uses only the operator == to compare. Hence while using the object as keys, equals() method needs to be overridden. Similarly while using hashmaps or hashtables the method hashcode needs to be overridden as the object is placed in the hash using hashcode value.
6. Can we override a static method?
The static methods cannot be overridden. If a subclass defines a static method with the same signature as a static method in the superclass, the method in the subclass hides the one in the superclass.
7. What are Transient and Volatile Modifiers?
Transient: Transient keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).
Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.
8. What is Garbage Collection?
When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection.
Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program can't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program.
9. How you can force the garbage collection?
Garbage collection automatic process and can't be forced. You could request it by calling System.gc() or Runtime.gc(). JVM does not guarantee that GC will be started immediately and when all the objects will garbage collected.
Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use.
10. What are immutable objects in Java? Can we change the value of an immutable object?
An object is considered to be immutable if its value cannot change after it is created. Immutable objects are particularly very useful in multi-threaded applications. Since they cannot change state, they won’t get corrupted by thread interference or observed in an inconsistent state. Objects of java.lang.Integer and java.lang.String classes are the examples of immutable objects. To create an immutable object You need to make the class final and all its members private or final, so that once objects gets created no one can modify its state.
11. What do you understand by numeric promotion?
The Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In the numerical promotion process the byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.
12. What is an applet?
Applet is a dynamic and interactive program that runs inside a web page displayed by a java capable browser. Applet needs no explicit installation on local machine and runs itself automatically in a java-enabled browser.
13. What is the lifecycle of an applet?
  1. init() method - Can be called when an applet is first loaded
  2. start() method - Can be called each time an applet is started.
  3. paint() method - Can be called when the applet is minimized or maximized.
  4. stop() method - Can be used when the browser moves off the applet’s page.
  5. destroy() method - Can be called when the browser is finished with the applet.
14. What is JVM (Java Virtual Machine)?
JVM stands for Java Virtual Machine. JVM is a software implementation which stands on the top of the real hardware platform and operating system. It provides abstraction between the compiled java program and the hardware and operating system. So the compiled program does not have to worry about what hardware and operating system he has to run in, it’s all handled by the JVM and thus attaining portability. All Java programs are compiled in to bytecodes. JVM can only understand and execute Java bytecodes.
15. Explain the advantages and disadvantages of JAVA.
JAVA offers a number of advantages to developers.
  1. Java is simple: Java was designed to be easy to use and learn than other programming languages. Java is much simpler than C++ as it uses automatic memory allocation and garbage collection where else C++ requires the programmer to allocate memory and to collect garbage.
  2. Java is object-oriented: Programming in Java is centered on creating objects, manipulating objects, and making objects work together. This allows you to create modular programs and reusable code.
  3. Java is platform-independent: Java programs are compiled into Java Virtual Machine code called bytecode. The bytecode is machine independent and is able to run on any machine that has a Java interpreter. With Java, the program need only be compiled once, and the bytecode generated by the Java compiler can run on any platform.
  4. Java is distributed: Distributed computing involves several computers on a network working together. Java is designed to make distributed computing easy with the networking capability that is inherently integrated into it.
  5. Java is secure: Java is one of the first programming languages to consider security as part of its design. The Java language, compiler, interpreter, and runtime environment were each developed with security in mind.
  6. Java is robust: Java puts a lot of emphasis on early checking for possible errors, as Java compilers are able to detect many problems that would first show up during execution time in other languages.
  7. Java is multithreaded: Multithreaded is the capability for a program to perform several tasks simultaneously within a program. In Java, multithreaded programming has been smoothly integrated into it.
Disadvantages of JAVA :
  1. Performance: Java can be perceived as significantly slower and more memory-consuming than natively compiled languages such as C or C++.
  2. Single-paradigm language: Java is predominantly a single-paradigm language. However, with the addition of static imports in Java 5.0 the procedural paradigm is better accommodated than in earlier versions of Java.

Please do comment if you find any discrepancies or want to suggest new questions.

Core Java Interview Questions - Part 2

Here is the Second set of Core Java Interview Questions. You can find the previous set of interview questions from below :
1. What would you use to compare two String variables - the operator == or the method equals()?
I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.
2. What does the "static" keyword mean in front of a variable? A method? A class? Curly braces {}?
  • static variable: means a class level variable
  • static method: Can be invoked even before a single instance of a class is created. It is not allowed to access the not static members of the class.
  • static class: no such thing.
  • static free floating block: is executed at the time the class is loaded. There can be multiple such blocks. This may be useful to load native libraries when using native methods.
3. What does the "final" keyword mean in front of a variable? A method? A class?
FINAL for a variable : value is constant
FINAL for a method : final method cannot be overridden or hidden by new access specifications.
FINAL for a class : cannot be derived, The best example of a final class is the String class.
4. What is difference between final, finalize() and finally?
final : final keyword can be used for class, method and variables. A final class cannot be subclassed and it prevents other programmers from subclassing a secure class to invoke insecure methods. A final method can’t be overridden. A final variable can’t change from its initialized value.
finalize() : finalize() method is used just before an object is destroyed and can be called just prior to garbage collection.
finally : finally, a key word used in exception handling, creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. For example, if a method opens a file upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism. This finally keyword is designed to address this contingency.
5. What is casting?
Casting is used to convert the value of one type to another. There are two types of casting in Java, these are Implicit casting and explicit casting. Casting operation is used to convert between types and the instanceof operator is used to check for type information at run time.
6. What are the types of casting?
There are two types of casting in Java, these are Implicit casting and explicit casting.
Implicit casting is the process of simply assigning one entity to another without any transformation guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not workout for all application scenarios.
Example:
int i = 4000;
long h = i; //Implicit casting
Explicit casting in the process in which the compiler are specifically informed to about transforming the object.
Example:
long ln = 700.20;
t = (int) ln; //Explicit casting
7. What do you understand by downcasting?
The process of Downcasting refers to the casting from a general to a more specific type, i.e. casting down the hierarchy.
8. What modifiers may be used with top-level class?
public, abstract and final can be used for top-level class.
9. What are inner class and anonymous class?
Inner class : classes defined in other classes, including those defined in methods are called inner classes. An inner class can have any accessibility including private.
Anonymous class : Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors.
10. Describe the wrapper classes in Java.
Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.
eg: boolean  - java.lang.Boolean
int - java.lang.Integer
void - java.lang.Void
11. What is the difference between StringBuffer and String class?
A StringBuffer implements a mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.
The String class represents character strings. All string literals in Java programs are immutable and their values cannot be changed after they are created.
12. What is the difference between the boolean '&' operator and the '&&' operator?
If an expression involving the boolean & operator is evaluated, both operands are evaluated.
Whereas when an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then only the second operand is evaluated. If the first operand evaluates to false, the evaluation of the second operand is skipped.
13. Why there are no global variables in Java?
Global variables are globally accessible. Java does not support globally accessible variables due to following reasons:
  1. The global variables breaks the referential transparency
  2. Global variables creates collisions in namespace.
14. Why Java does not support pointers?
Because pointers are unsafe. Java uses reference types to hide pointers and programmers feel easier to deal with reference types without pointers.
15. How is it possible for two String objects with identical values not to be equal under the == operator?
The '==' operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory.

Please do provide your valuable comments and suggestions. Thanks in Advance.

Java Interview Questions - Collections

Here is a set of Java Interview Questions which focuses on the Collections framework. You can find the previous set of Interview Questions from here:

1. What is Collection API?
The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.
2. What are the classes implementing List interface?
There are three classes that implement List interface:
  1. ArrayList : It is a resizable array implementation. The size of the ArrayList can be increased dynamically also operations like add,remove and get can be formed once the object is created. It also ensures that the data is retrieved in the manner it was stored. The ArrayList is not thread-safe.
  2. Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around a synchronized block.
  3. LinkedList: LinkedList implements Queue interface and provide FIFO(First In First Out) operation for add operation. It is faster than ArrayList for insertion and deletion of elements from the middle of a list.
3. Which all classes implement Set interface?
A Set is a collection that contains no duplicate elements. HashSet, SortedSet and TreeSet are the commonly used classes which implements Set interface.
  1. SortedSet - It is an interface which extends Set. A the name suggest , the interface allows the data to be iterated in the ascending order or sorted on the basis of Comparator or Comparable interface. All elements inserted into the interface must implement Comparable or Comparator interface.
  2. TreeSet - It is the implementation of SortedSet interface.This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). The class is not synchronized.
  3. HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.
4. What is difference between List and a Set?
  • List can contain duplicate values but Set allows only unique elements.
  • List allows retrieval of data to be in same order in the way it is inserted but Set doesnt ensures the sequence in which data can be retrieved.
5. What is difference between Arrays and ArrayList ?
  1. Arrays are created of fix size whereas ArrayList is of not fix size. i.e. the size of array cannot be incremented or decremented. But with arrayList the size is variable.
  2. Once the array is created elements cannot be added or deleted from it. But with ArrayList the elements can be added and deleted at runtime.
  3. ArrayList is one dimensional but array can be multidimensional.
  4. To create an array the size should be known or initalized to some value. If not initialized carefully there could me memory wastage. But arrayList is all about dynamic creation and there is no wastage of memory.
6. What are the main differences between a Vector and an ArrayList?
  1. Synchronization - Java Vector class is internally synchronized and ArrayList is not synchronized. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non synchronized data structure (ArrayList) will give better performance than the synchronized one (Vector).
  2. Data growth - Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.
7. Which implementation of the List interface provides for the fastest insertion of a new element into the middle of the list?
The LinkedList allows for fastest insertions and deletions into the middle of a list. The LinkedList is implemented using a doubly linked list; thus an insertion requires only the updating of the links at the point of insertion.Whereas 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, then the elements that follow the insertion point must be shifted to make room for the new element.
8. What is difference between HashMap and HashTable?
Both collections implements Map. Both collections store value as key-value pairs. The key differences between the two are
  1. Hashmap is not synchronized in nature but HashTable is.
  2. Iterator in the HashMap is fail-safe while the enumerator for the HashTable isn't.
  3. HashMap permits null values and only one null key, while HashTable doesn't allow key or value as null.
    9. Is Iterator a Class or Interface? What is its use?
    Iterator is an interface which is used to step through the elements of a Collection.
    10. If any ArrayList is used only for reading which way will be the faster, For loop or Iterator?
    Using a for loop is faster than using iterator. A for loop allows access of the element directly on the basis of index. The cursor of the datastructure can directly go to the 'n' location and get the element. It does not traverse through n-1 elements. Wheras in Iterator based access, the cursor has to traverse through each element to get the desired element.So to reach the 'n'th element it need to traverse through n-1 elements.
    11. When should be an Iterator preferred over a For loop?
    For loop does not allow the updation in the array(add or remove operation) inside the loop whereas Iterator does. Also Iterator can be used where the data type of the collection is not known.
    12. How do you traverse through a collection using its Iterator?
    To use an iterator to traverse through the contents of a collection, follow these steps:
    1. Obtain an iterator to the start of the collection by calling the collection’s iterator() method.
    2. Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true.
    3. Within the loop, obtain each element by calling next().
    13. How can Arraylist be synchronized without using Vector?
    Arraylist can be synchronized using:
    Collection.synchronizedList(List list) 
    
    14. What is identityHashMap?
    The IdentityHashMap uses == for equality checking instead of equals(). This can be used for both performance reasons, if you know that two different elements will never be equals and for preventing spoofing, where an object tries to imitate another.
    15. What are the main algorithms (methods) that the Collections framework provide?
    Most polymorphic algorithms in the Collections class apply specifically to List. Below listed are the commonly used algorithms :
    • sort — sorts a List using a merge sort algorithm, which provides a fast, stable sort. (A stable sort is one that does not reorder equal elements.)
    • shuffle — randomly permutes the elements in a List.
    • reverse — reverses the order of the elements in a List.
    • rotate — rotates all the elements in a List by a specified distance.
    • swap — swaps the elements at specified positions in a List.
    • replaceAll — replaces all occurrences of one specified value with another.
    • binarySearch — searches for an element in an ordered List using the binary search algorithm.

    Java Interview Questions - OOP

    Here is the Second set of Java Interview Questions which focuses on the Object Oriented Programming principles. Please comment if you want to add any other question to this list.

    1. What is OOP?
    OOP is the common abbreviation for Object-Oriented Programming. Object oriented programming organizes a program around its data, i. e. , objects and a set of well defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code.
    There are four main principals of oops which are called Abstraction, Polymorphism, Inheritance and Encapsulation.
    2. What is the difference between procedural and object-oriented programs?
    In procedural program, programming logic follows certain procedures and the instructions are executed one after another. In OOP program, unit of program is object, which is nothing but combination of data and code.
    In procedural program, data is exposed to the whole program whereas in OOPs program, it is accessible with in the object and which in turn assures the security of the code.
    3. What is Abstraction?
    Abstraction is the process of generalization by reducing the information content of an entity, typically to retain only information which is relevant for a particular purpose. For example, an Employee has various attributes like name, skin color, age, hair color, etc. But we consider only those attributes of employees which are required and relevant to program a system.
    In general, abstraction is the process of focusing on important thing without including background details in program.
    4. Explain the Encapsulation principle.
    Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.
    5. Explain the Inheritance principle.
    Inheritance is the process by which one object acquires the properties of another object. The advantages of inheritance are reusability of code and accessibility of variables and methods of the super class by subclasses.
    6. Explain the Polymorphism principle.
    The meaning of Polymorphism is something like one name many forms. Polymorphism enables one entity to be used as as general category for different types of actions. The specific action is determined by the exact nature of the situation. The concept of polymorphism can be explained as "one interface, multiple methods".
    From a practical programming viewpoint, polymorphism exists in three distinct forms in Java:
    • Method overloading
    • Method overriding through inheritance
    • Method overriding through the Java interface
    7. What is the advantage of OOP?
    The Major advantages of OOP are:
    1. Simplicity: software objects model real world objects, so the complexity is reduced and the program structure is very clear.
    2. Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system.
    3. Modifiability: it is easy to make minor changes in the data representation or the procedures in an OO program. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods.
    4. Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.
    5. Maintainability: objects can be maintained separately, making locating and fixing problems easier.
    6. Re-usability: objects can be reused in different programs.
    8. What is the Difference between Class and Object?
    A Class is actually a blueprint or a template to create an Object. Whereas an Object is a an actual instance of a Class. For example Employee is a class, while John is a real employee which is an Object of Employee Class.
    9. What is method overloading and method overriding?
    Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading.
    Method overriding : When a method in a class having the same method name with same arguments is said to be method overriding.
    10. What is difference between overloading and overriding?
    • In overloading, there is a relationship between methods available in the same class whereas in overriding, there is relationship between a superclass method and subclass method.
    • Overloading does not block inheritance from the superclass whereas overriding blocks inheritance from the superclass.
    • In overloading, separate methods share the same name whereas in overriding, subclass method replaces the superclass.
    • Overloading must have different method signatures whereas overriding must have same signature.
    11. What is message passing in object oriented programming?
    Message passing is a method by which an object sends data to another object or requests other object to invoke method. This is also known as interfacing. It acts like a messenger from one object to other object to convey specific instructions.
    12. What are data members and member functions?
    Classes use the concept of abstraction and are defined as a list of abstract attributes such as size, weight, and cost and uses functions to operate on these attributes.
    The attributes are sometimes called as data members because they hold information. The functions that operate on these data are called as methods or member functions.
    Eg: int a,b; // a,b are data members
    Void getdata ( ) ; // member function
    13. Write the process of programming in an object-oriented language?
    1. Create classes that define objects and their behavior.
    2. Creating objects from class definition.
    3. Establishing communication among objects.
    14. What is an Abstract class?
    Abstract class defines an abstract concept which can not be instantiated and comparing o interface it can have some implementation while interfaces can not. Below are some points for abstract class:-
    We can not create object of abstract class it can only be inherited in a below class.
    Normally abstract classes have base implementation and then child classes derive from the abstract class to make the class concrete.
    15. What are Abstract methods?
    Abstract class can contain abstract methods. Abstract methods do not have implementation. Abstract methods should be implemented in the subclasses which inherit them. So if an abstract class has an abstract method class inheriting the abstract class should implement the method or else java compiler will through an error. In this way, an abstract class can define a complete programming interface thereby providing its subclasses with the method declarations for all of the methods necessary to implement that programming interface. Abstract methods are defined using "abstract" keyword. Below is a sample code snippet.
    abstract class MyGraphics {
       abstract void draw();
    }
    
    Any class inheriting from 'MyGraphics' class should implement the 'draw' method or else the java compiler will throw an error. So if we do not implement a abstract method the program will not compile.
    16. What is the difference between Abstract classes and Interfaces?
    Difference between Abstract class and Interface is as follows:-
    • Abstract class can only be inherited while interfaces can not be it has to be implemented.
    • Interface cannot implement any methods, whereas an abstract class can have implementation.
    • Class can implement many interfaces but can have only one super class.
    • Interface is not part of the class hierarchy while Abstract class comes in through inheritance.
    • Unrelated classes can implement the same interface.
    17. What is difference between Static and Non-Static fields of a class?
    Non-Static values are also called as instance variables. Each object of the class has its own copy of Non-Static instance variables. So when a new object is created of the same class it will have completely its own copy of instance variables.
    Static values have only one copy of instance variables and will be shared among all the objects of the class.
    18. What are inner classes and what is the practical implementation of inner classes?
    Inner classes are nested inside other class. They have access to outer class fields and methods even if the fields of outer class are defined as private.
    Normally inner classes are used for data structures or some kind of helper classes.
    19. What is a constructor in class?
    Constructor has the same name as the class in which it resides and looks from syntax point of view it looks similar to a method. Constructor is automatically called immediately after the object is created, before the new operator completes. Constructors have no return type, not even void. This is because the implicit return type of a class' constructor is the class type itself. It is the constructor's job to initialize the internal state of an object so that the code creating an instance will have a fully initialized, usable object immediately.
    20. Can constructors be parameterized?
    Yes we can have parameterized constructor which can also be termed as constructor overloading. Below is a code snippet which shows two constructors for MathsPI class one default (parameter-less) and other with parameter.
    class MathsPI {
       double PI;
       // This is the constructor for the maths constant class.
       MathsPI() {
          PI = 3.14;
       }
       MathsPI(int pi) {
          PI = pi;
       }
    }
    
    21. What are access modifiers?
    Access modifiers decide whether a method or a data variable can be accessed by another method in another class or subclass.
    four types of access modifiers:
    • Public - Can be accessed by any other class anywhere.
    • Protected - Can be accessed by classes inside the package or by subclasses ( that means classes who inherit from this class).
    • Private - Can be accessed only within the class. Even methods in subclasses in the same package do not have access.
    • Default - (Its private access by default) accessible to classes in the same package but not by classes in other packages, even if these are subclasses.
    22. What is runtime polymorphism or dynamic method dispatch?
    In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.
    23. What is Dynamic Binding?
    Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance.
    24. How do you prevent a method from being overridden?
    To prevent a specific method from being overridden in a subclass, use the final modifier on the method declaration, which means "this is the final implementation of this method", the end of its inheritance hierarchy.
    25. Do interfaces have member variables?
    Interfaces may have member variables, but these are implicitly public, static, and final- in other words, interfaces can declare only constants, not instance variables that are available to all implementations and may be used as key references for method arguments.

    Core Java Interview Questions - Part 1

    Had an interview the other day for a java opening and just compiled a list of frequently asked Java Interview questions for different specializations. Thought of sharing the lists for the benefit of all those who are attending or planning for a Java Interview.

    This post focuses on Interview questions for the Java Fundamentals i.e the core functionality. If you feel that some important questions are missed or you want suggest a different answer to any Interview question, do comment and I will be glad to update on it.
    1. What are Class, Constructor and Primitive data types?
    Class is a template for multiple objects with similar features and it is a blue print for objects. It defines a type of object according to the data the object can hold and the operations the object can perform.
    Constructor is a special kind of method that determines how an object is initialized when created.
    Primitive data types are 8 types and they are: byte, short, int, long, float, double, boolean, char.
    2. What is an Object and describe what happens when an object is created in Java?
    Object is an instance of a class and it is a software unit that combines a structured set of data with a set of operations for inspecting and manipulating that data. When an object is created using new operator, memory is allocated to it.
    Several things happen in a particular order to ensure the object is constructed properly:
    1. Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implementation-specific data includes pointers to class and method data.
    2. The instance variables of the objects are initialized to their default values.
    3. The constructor for the most derived class is invoked. The first thing a constructor does is call the constructor for its uppercase. This process continues until the constructor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java.
    4. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.
    3. What is the difference between constructor and method?
    Constructor will be automatically invoked when an object is created whereas method has to be called explicitly.
    4. What are methods and how are they defined?
    Methods are functions that operate on instances of classes in which they are defined. Objects can communicate with each other using methods and can call methods in other classes.
    Method definition has four parts. They are :
    • name of the method
    • type of object or primitive type the method returns
    • a list of parameters
    • body of the method.
    A method’s signature is a combination of the first three parts mentioned above.
    5. How many ways can an argument be passed to a subroutine and explain them?
    An argument can be passed in two ways. They are passing by value and passing by reference.
    Passing by value: This method copies the value of an argument into the formal parameter of the subroutine.
    Passing by reference: In this method, a reference to an argument (not the value of the argument) is passed to the parameter.
    6. What is the difference between this() and super()?
    this() can be used to invoke a constructor of the same class. Use this() to call a constructor from another constructor.
    super() can be used to invoke a super class constructor. Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass's constructor.
    7. Explain the usage of Java packages.
    This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.
    8. If a class is located in a package, what do you need to change in the OS environment to be able to use it?
    You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable.
    Let's say a class Employee belongs to a package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java. In this case, you'd need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:
    c:\>java com.xyz.hr.Employee
    9. What's the difference between constructors and normal methods?
    Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times and it can return a value or can be void.
    10. What is the difference between superclass and subclass?
    A super class is a class that is inherited whereas sub class is a class that does the inheriting.
    11. What does the "abstract" keyword mean in front of a method? A class?
    If a method has a abstract keyword in front of it,it is called abstract method. Abstract method has no body.It has only arguments and return type.Abstract methods act as placeholder methods that are implemented in the subclasses.
    Abstract classes can’t be instantiated.If a class is declared as abstract,no objects of that class can be created.If a class contains any abstract method it must be declared as abstract.
    12. How to define an Abstract class?
    A class containing abstract method is called Abstract class. An Abstract class can't be instantiated.
    Example of Abstract class:
    abstract class testAbstractClass { 
        protected String myString; 
        public String getMyString() { 
        return myString; 
    } 
    public abstract string anyAbstractFunction();
    }
    13. How to define an Interface?
    In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.
    Example of Interface:
    public interface sampleInterface {
        public void functionOne();
        public long CONSTANT_ONE = 1000;
    }
    14. What are the advantages of interface?
    Interfaces are useful for:
    • Declaring methods that one or more classes are expected to implement
    • Capturing similarities between unrelated classes without forcing a class relationship.
    • Determining an object’s programming interface without revealing the actual body of the class.
    15. What's the difference between an interface and an abstract class? Also discuss the similarities. (Very Important)
    Abstract class is a class which contain one or more abstract methods, which has to be implemented by sub classes. Interface is a Java Object containing method declaration and doesn't contain implementation. The classes which have implementing the Interfaces must provide the method definition for all the methods

    Abstract classes are useful in a situation that Some general methods should be implemented and specialization behavior should be implemented by child classes. Interfaces are useful in a situation that all properties should be implemented.

    Differences:
    • Interfaces provide a form of multiple inheritance. A class can extend only one other class.
    • Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
    • A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
    • Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast.
    Similarities:
    • Neither Abstract classes or Interface can be instantiated.

    You can find the next set of Core Java Interview Questions from below :

    The Best Free jQuery Plugins

    To be successful as a blogger, you definitely need a helping hand with some of the best free jQuery plugins which can help you leverage your efforts. I have listed here some best free jQuery plugins of different functions like slider, layout, form validation, table, etc. Please feel free to suggest any new ones in the comment section.

    MotionCaptcha - Innovative Captcha Tool

    MotionCAPTCHA is a jQuery CAPTCHA plugin, based on the HTML5 Canvas Harmony procedural drawing tool, requiring users to sketch the shape they see in the canvas in order to submit a form.

    Power PWChecker - jQuery password strength checker

    Power PWChecker is a free jQuery plugin which ensures secure passwords for users. This simple jQuery plugin can be integrated seamlessly with any online form (sign up form/ user registration form) to check password strength and give users clues for creating strong and secure passwords.

    tablesorter - Sortable Table

    tablesorter is a jQuery plugin for turning a standard HTML table with THEAD and TBODY tags into a sortable table without page refreshes. tablesorter can successfully parse and sort many types of data including linked data in a cell. It has many useful features including Multi-column sorting and  Multi-type sorting.

    FancyBox - Image Gallery Box

    FancyBox is a tool for displaying images, html content and multi-media in a Mac-style "lightbox" that floats overtop of web page. It can display images, HTML elements, SWF movies, Iframes and also Ajax requests. It is customizable through settings and CSS and supports various fancy transitions.

    Akordeon - Stylish jQuery Accordion Plugin

    Akordeon is a stylish jQuery plugin for adding efficient accordion style menu to a web page. The idea behind Akordeon is to provide a lightweight and customizable interface for collapsible panels that can hold any kind of data in a limited space.

    Nivo Slider - Awesome jQuery slider

    The Nivo Slider is world renowned as the most beautiful and easy to use slider on the market. Completely free and totally open source, there literally is no better way to make your website look totally stunning.

    Snippet - jQuery Syntax Highlighter

    Snippet is a jQuery syntax highlighting plugin built on top of the SHJS script found on SourceForge. Snippet provides a quick and easy way of highlighting source code passages in HTML documents.

    jQZoom - Javascript image magnifier

    JQZoom is a javascript image magnifier built at the top of the popular jQuery javascript framework. jQzoom is a great and a really easy to use script to magnify what you want. It works on all modern browsers.

    jqFloat - Floating Effect with jQuery

    jqFloat.js is a jQuery plugin that able to make any HTML objects appear to be “floating” on your web page. It helps create simple floating animation and make your websites come alive with these little “floating” object.

    Uploadify - Multiple File Upload jQuery Plugin

    Uploadify is a jQuery plugin that integrates a fully-customizable multiple file upload utility on your website. It uses a mixture of JavaScript, ActionScript, and any server-side language to dynamically create an instance over any DOM element on a page.

    IdealForms - jQuery Form Plugin

    Ideal Forms is the ultimate framework for building and validating responsive HTML5 forms. It is fully responsive, has keyboard support, input customization, custom datepicker and 'On the spot' validation.

    Minimit - jQuery Gallery Plugin

    Minimit Gallery is the most custom slider plugin you’ll ever find. It’s tested for and supports Css3 transition and transform, drags, scrollers, and touch interactions.It is tested on IE7+, Firefox 3.5+, Safari 3+, Opera 9+, Chrome, Iphone, Ipad, Android.

    Recurly - jQuery Forms With Fully Customizable CSS

    Recurly.js is a Javascript library designed to be easily embedded and customized to match your website. The library performs in-line validation, real-time total calculations, and gracefully handles errors. Your customer stays on your website while their billing information is securely sent to Recurly for approval.

    Flexslider - Fully responsive jQuery slider plugin.

    FlexSlider is a fully responsive jQuery slider plugin. FlexSlider has been verified in Safari 4+, Chrome 4+, Firefox 3.6+, Opera 10+, and IE7+. iOS and Android devices are supported as well.

    Create a JDT Project in Eclipse

            JDT stands for Java development tools, the sub-project of the Eclipse project that develops tools for programming in Java. This includes a Java compiler, incremental builder, editors, wizards, content assist, and all the other features of a first class Java IDE.
            The JDT Core component is the plug-in that defines the core Java elements and API. This Core component can be included inside our own plugin and can be used to search, compile and manipulate Java code outside an IDE. This is because the JDT/Core infrastructure has no built-in JDK version dependencies, and it also does not depend on any particular Java UI.

    Below are some of the activities that can be performed by using the JDT Core plug-in :
    1. Programmatically manipulate Java resources, such as creating projects, generating Java source code, performing builds, or detecting problems in code.
    2. Searching the workspace's Java model for Java elements that match a particular description.
    3. Generating Abstract Syntax Trees (AST) that can be used for examining the structure of a compilation unit down to the statement level.
    4. Formatting of compilation units, types, statements, expressions, etc.

            JDT is supported by 3 pillars: Java Model, Search Engine, and AST. More info about JDT can be found from here. Here is couple of nice presentations which briefly describes all JDT fundamentals and features - JDT Fundamentals 2010 and JDT Fundamentals. JDT allows you to access Java Code using  AST (Abstract Syntax Tree). AST is a Document Object Model for Java, where each code element is represented as AST Nodes. It gives you a detailed tree structureof the Java source code. Some of the ASTNodes are MethodDeclaration, FieldDeclaration, MethodInvocation, VariableDeclarationStatement, ExpressionStatement etc. In this post we will be using this AST functionality to retrieve information from a Java Source File.

            At first we need to create a plug-in project which uses JDT Core plugin. Instructions on creating a plug-in project in eclipse can be found from here. Name the new project JDT_Basic. Now to use the JDT core functionality we need to add it as a plug-in to our project. We can do this from the 'Dependencies' tab (view this tab by opening the plugin.xml file). Click on the 'Add' button and add the 'org.eclipse.jdt.core' plug-in. This way we have included the JDT Core plug-in our project and thus will be able to use the AST functionalities.

     

            For running this plugin project we will be using the 'applications' extension. For this, double click on the plugin.xml file and open the 'Extensions' tab. Remove the 'actionSets' extension and add the 'applications' extension (org.eclipse.core.runtime.applications). Expand the extension in the window and create a new run by right clicking and choosing New > run. Specify the class as 'jdt_basic.JDTClass' and click on the 'class' label to create the Class.


            This class will be used to invoke our JDT application. The 'start' method of the application class denotes the starting point of the plug-in application, whereas the 'stop' method is invoked at the end of the application. Using this application class we will try to implement a simple activity, to list all the methods in a Java file.

            Here is how we are going to accomplish this. At first we will read the content of the Java file using a String Buffer. Using this content(source) we will create a CompilationUnit for the Java file. This CompilationUnit gives you an AST representation of the Java File. To traverse the various AST nodes of this CompilationUnit you can use the ASTVisitor pattern. In this example we will list out the Class methods by traversing the MethodDeclaration node.

            Here is the code for the JDTClass. Each step in the code has documented with comments for clear understanding. If you have any questions or queries, please comment. I will be more than happy to help you out.

    package jdt_basic;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import org.eclipse.equinox.app.IApplication;
    import org.eclipse.equinox.app.IApplicationContext;
    import org.eclipse.jdt.core.dom.AST;
    import org.eclipse.jdt.core.dom.ASTParser;
    import org.eclipse.jdt.core.dom.ASTVisitor;
    import org.eclipse.jdt.core.dom.CompilationUnit;
    import org.eclipse.jdt.core.dom.MethodDeclaration;
    
    /** 
     * This class provides basic JDT functionality.
    */
    public class JDTClass implements IApplication {
        
        /** 
         * The starting point of the plug-in application.
         * Visit the Code specified as path and list the methods inside the class.
         */
        @Override
        public Object start(IApplicationContext context) throws Exception {
    
            // Get the source code of the java class file - change path to your file's path.
            final StringBuffer sourceCode = getSource("d:\\HelloWorld.java");
            // Define a new ASTParser.
            ASTParser parser = ASTParser.newParser(AST.JLS3);
            // Parse the class as a compilation unit.
            parser.setKind(ASTParser.K_COMPILATION_UNIT);
            // Supply the class code as character array.
            parser.setSource(sourceCode.toString().toCharArray());
            parser.setResolveBindings(true);
            // Get the compiled class as a compilation unit  
            final CompilationUnit compiledClassUnit = (CompilationUnit) parser.createAST(null);
            // Instantiate a new ASTVisitor class that will determine which nodes are visited during an AST traversal
            compiledClassUnit.accept(new ASTVisitor() {
                @Override
                // Visit the MethodDeclaration node - denotes the declaration of methods in a class
                public boolean visit(MethodDeclaration node) {
                    // Show the visited method in console.
                    System.out.println("Method " + node.getName().getFullyQualifiedName() + " is visited");
                    return true;
                }
            });
            return IApplication.EXIT_OK;
        }
        
        /**
         * Returns the source code of the java class file as string buffer.
         * @param path the path of the Java class file
         * @return StringBuffer string buffer containing the source code
         */
        private static StringBuffer getSource(String path) {
    
            // Define string buffer for holding the source
            final StringBuffer buffer = new StringBuffer();
            try {
                // Read the file line by line and append to string buffer.
                File javaFile = new File(path);
                BufferedReader in = new BufferedReader(new FileReader(javaFile)); 
                String line = null;
                while (null != (line = in.readLine())) {
                    buffer.append(line).append("\n");
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return buffer;
        }
    
        /** 
         * The end point of the plug-in application.
         */
        public void stop() {
            // TODO Auto-generated method stub
        }
    }
    

    Chained DropDown in Javascript using XML

    Sample Chained HTML DropDown      
    In our previous post we have learned about how to create Chained Drop-downs using javascript. In that example, the values for the 2nd drop-down were being hard-coded in the javascript itself. Though this approach is fairly easy to implement, it doen't offer a fully dynamic approach. If we need to add/delete options or update any exisitng options, then we need to alter the javascript code each time. Also a person who has less or no previous experience with Javascript may not be able to use or modify that logic.

            This problem can be solved by externalizing your data from the code, say, in form of an XML. In order to change the drop-down values you just need to add, delete or modify the values in the XML file. In this post we will discuss how to implement such a dynamic Chained DropDown using javascript.

            We will create the two drop-downs, a 'Company' drop-down which lists mobile companies and 'Model' drop-down which list out models for the selected company.
    <select id="Company" >
     <option value=""></option>
     <option value="Samsung">Samsung</option>
     <option value="Apple">Apple</option>
     <option value="Nokia">Nokia</option>
    </select>
    
    <select id="Model"> </select>
    

            XML stands for Extensible Markup Language. It is classified as an extensible language because it allows its users to define their own tags. The XML file which has our data has a 'device' tag containing a 'name' attribute which holds the Company name. The model tag is contained inside a device tag and holds information about the Model name. Here is the content of the 'info.xml' file which holds the data for this example.
    <?xml version="1.0" ?> 
    <data>
        <device name="Nokia">
            <model>Lumia</model>
            <model>PureView</model>
        </device>
        <device name="Samsung">
            <model>Galaxy S2</model>
            <model>Galaxy S3</model>
        </device>
        <device name="Apple">
            <model>iPhone4</model>
            <model>iPhone5</model>
        </device>
    </data>
    

            Now we need to import this data from the XML file. To manipulate an XML document in javascript, we need an XML parser. Today all browsers come with in-built parsers that can parse the XML document. The parser loads the document into your computer’s memory and once loaded, its data can be manipulated using the DOM(Document Object Model). We are using a cross-browser function to import the XML as there is significant difference in implementation of Microsoft Browser based XML parser and the Mozilla browsers (Firefox, Chrome, Safari) based XML parser.
    /* Cross-Browser Import of XML document into a XML Document. */
    function importXML(xmlfile) {
        var xmlDoc;
        if (typeof window.ActiveXObject != 'undefined') {
            //code for IE
            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async = false;
            xmlDoc.load(xmlfile);
            } else {
                try {
                    // code for IE7+, Firefox, Chrome, Opera, Safari
                    xmlhttp=new XMLHttpRequest();
                    xmlhttp.open("GET", xmlfile, false);
                    xmlhttp.setRequestHeader('Content-Type', 'text/xml');
                    xmlhttp.send();
                    xmlDoc=xmlhttp.responseXML;
                } catch (Exception) {
                    alert("Your browser is not supported. Try firefox !!");
                }
            }
        return xmlDoc;
    }
    

            The loadXMLOption method retrieves the options for the model combobox from the XML file. This is to be called when user selects an option in the 'Company' drop-down. It first loads the XML file by using the 'importXML' method we have previously written. From the XML document object, we retrieve all the tags with tag name as 'device'. We then loop through each 'device' tag and check if its 'name' attribute's value is same as the one we have selected in the 'Company' drop-down. If found similar, we then retrieve all the 'model' tags under that specific 'device' tag and add each tag's node value as option to the 'Model' drop-down.
    /* Get the options for the model combobox from the XML. */
    function loadXMLOption() {
        // Load the xml file
        var xmlDoc=importXML("info.xml");
        xmlObj=xmlDoc.documentElement;
        // Get all Elements with Tag name 'device'
        DeviceObj = xmlObj.getElementsByTagName("device");
        for(var i=0; i < DeviceObj.length; i++) {
            // Loop through each device tag and check if its name is equal to the selected device value
            if (document.getElementById('Company').value == DeviceObj[i].getAttribute("name")) {  
                // If matching device found get the model tags under that device
                modelObj = DeviceObj[i].getElementsByTagName("model");
                document.getElementById('Model').options.length = 0;
                // Create options for the Model comboBox.
                for(var j=0; j < modelObj.length; j++) {
                    var opt = document.createElement('option');
                    opt.value = modelObj[j].firstChild.nodeValue;
                    opt.text = modelObj[j].firstChild.nodeValue;
                    document.getElementById('Model').options.add(opt);
                }
            }
        }
    }
    
    Now call this method on the onChange event of the company drop-down.
    <select id="Company" onchange="loadXMLOption();">
    
            Thats it and now we have a truly dynamic Chained Drop-downs. You can change or add the model values in the XML file. If you want an easy way to develop chained drop-down without involving XML, you can try this post.
    You can get the entire code from below. Comments and suggestions are welcome.
    <html>
    <head>
    
    <script language="javascript">
    /* Cross-Browser Import of XML document into a XML Document. */
    function importXML(xmlfile) {
        var xmlDoc;
        if (typeof window.ActiveXObject != 'undefined') {
            //code for IE
            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async = false;
            xmlDoc.load(xmlfile);
            } else {
                try {
                    // code for IE7+, Firefox, Chrome, Opera, Safari
                    xmlhttp=new XMLHttpRequest();
                    xmlhttp.open("GET", xmlfile, false);
                    xmlhttp.setRequestHeader('Content-Type', 'text/xml');
                    xmlhttp.send();
                    xmlDoc=xmlhttp.responseXML;
                } catch (Exception) {
                    alert("Your browser is not supported. Try firefox !!");
                }
            }
        return xmlDoc;
    }
    
    /* Get the options for the model combobox from the XML. */
    function loadXMLOption() {
        // Load the xml file
        var xmlDoc=importXML("info.xml");
        xmlObj=xmlDoc.documentElement;
        // Get all Elements with Tag name 'device'
        DeviceObj = xmlObj.getElementsByTagName("device");
        for(var i=0; i < DeviceObj.length; i++) {
            // Loop through each device tag and check if its name is equal to the selected device value
            if (document.getElementById('Company').value == DeviceObj[i].getAttribute("name")) {  
                // If matching device found get the model tags under that device
                modelObj = DeviceObj[i].getElementsByTagName("model");
                document.getElementById('Model').options.length = 0;
                // Create options for the Model comboBox.
                for(var j=0; j < modelObj.length; j++) {
                    var opt = document.createElement('option');
                    opt.value = modelObj[j].firstChild.nodeValue;
                    opt.text = modelObj[j].firstChild.nodeValue;
                    document.getElementById('Model').options.add(opt);
                }
            }
        }
    }
    </script>
    
    </head>
    <body>
    
    <h2>Chained Drop-Down - using XML</h2>
    
    Device : <select id="Company" onchange="loadXMLOption();">
      <option value=""></option> 
      <option value="Samsung">Samsung</option>
      <option value="Apple">Apple</option> 
      <option value="Nokia">Nokia</option>
    </select>
    
    Model : <select id="Model"> </select>
    
    </body>
    </html>
    
    Related Posts Plugin for WordPress, Blogger...
     

    Copyright © 2012 | ScriptSplash | Powered by Blogger Templates