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>
    

    Chained DropDown in Javascript

    You might have seen chained drop-downs in some sites, where changing a value in one drop-down causes new values to be populated in another drop-down. This chain effect can be simply implemented using Javascript.

            At first, we will create the two drop-downs for which we are implementing the chained effect. We will provide the options in the 1st drop-down. No options need to be given for the 2nd drop-down and it values will be populated dynamically based upon the value of the 1st drop-down. We have named the first drop-down 'Company' which lists some mobile companies. The second drop-down 'Model' will list out few 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>
    

            Now on to the coding part. The configureDropDown method is fired on the change of value in the Company drop-down and populates the values in the 'Model' drop-down. We will first define the arrays containing the value of models for each company. Now we will check the value of the Company drop-down and based on it get the values for the Model drop-down.
    /* Configure the DropDown ddl2 based on the value selected in DropDown ddl1. */
    function configureDropDown(ddl1,ddl2) {
    
     // Arrays holding the value for ddl2 (model comboBox).
     var Nokia = new Array('Lumia', 'PureView');
     var Samsung = new Array('Galaxy S3', 'Galaxy S2');
     var Apple = new Array('iPhone4', 'iPhone5');
      
     // Check the value in ddl1 (Company comboBox).
     switch (ddl1.value) {
      case 'Samsung':
       getOptionsFromArray(Samsung, document.getElementById(ddl2));
       break;
      case 'Apple':
       getOptionsFromArray(Apple, document.getElementById(ddl2));
       break;
      case 'Nokia':                 
       getOptionsFromArray(Nokia, document.getElementById(ddl2));
       break;
      default:
       document.getElementById(ddl2).options.length = 0;
       break; 
     }
    }
    

            The getOptionsFromArray method retrieves the options for the model combobox from the respective array. The method loops through the entire array and adds the array values as options to the drop-down.
    // Get the options for the model combobox from the respective array. 
    function getOptionsFromArray(selectArray, select) {
     select.options.length = 0;
     // Create option for the comboBox.
     for (i = 0; i < selectArray.length; i++) {
            var opt = document.createElement('option');
      opt.value = selectArray[i];
      opt.text = selectArray[i];
      select.options.add(opt);
     }
    }
    
    Now call this method on the onChange event of the company drop-down.
    <select id="Company" onchange="configureDropDown(this,'Model')">

            This finishes our tutorial. We now have a 'Model' drop-down whose values changes depending on the value of Company drop-down. You can get the entire code from below.
    <html>
    <head>
    <script type="text/javascript">
    
         /* Configure the DropDown ddl2 based on the value selected in DropDown ddl1. */
         function configureDropDown(ddl1,ddl2) {
    
     // Arrays holding the value for ddl2 (model comboBox).
     var Nokia = new Array('Lumia', 'PureView');
     var Samsung = new Array('Galaxy S3', 'Galaxy S2');
     var Apple = new Array('iPhone4', 'iPhone5');
      
     // Check the value in ddl1 (Company comboBox).
     switch (ddl1.value) {
          case 'Samsung':
               getOptionsFromArray(Samsung, document.getElementById(ddl2));
               break;
          case 'Apple':
               getOptionsFromArray(Apple, document.getElementById(ddl2));
               break;
          case 'Nokia':                 
               getOptionsFromArray(Nokia, document.getElementById(ddl2));
               break;
          default:
               document.getElementById(ddl2).options.length = 0;
               break; 
     }
        }
     
         // Get the options for the model combobox from the respective array. 
         function getOptionsFromArray(selectArray, select) {
     select.options.length = 0;
     // Create option for the comboBox.
     for (i = 0; i < selectArray.length; i++) {
            var opt = document.createElement('option');
          opt.value = selectArray[i];
          opt.text = selectArray[i];
          select.options.add(opt);
     }
         }
    </script>
    </head>
    <body>
    
    <h2>Chained Drop-Downs</h2><br/>
    
    <select id="Company" onchange="configureDropDown(this,'Model')">
     <option value=""></option> 
     <option value="Samsung">Samsung</option>
     <option value="Apple">Apple</option> 
     <option value="Nokia">Nokia</option>
    </select>  
    <br/>
    
    <select id="Model"> </select>
    
    </body>
    </html>
    
    Your comments and suggestions are welcome.
    Related Posts Plugin for WordPress, Blogger...
     

    Copyright © 2012 | ScriptSplash | Powered by Blogger Templates