Tuesday, November 8, 2011

Java Interview Questions

--> This is one of the important post that I decided to give it to you all, it contains most of the questions asked (worth asking) to me in various technical job interviews. This is not a one time post, I will be regularly updating it like any other wiki page, so you might encounter some new questions and facts once you come back again.

[Q-01] What are the use of static variables also state the ways how it is different from a constant ?

[A-01] Static variables are class variables, as local variables cannot be declared as static. In most of the cases 'static' is accompanied by 'final' as by definition it should be used as CONSTANTS, some very special cases includes the statistics-gathering for that class where non-final-static member variables are used to deal with rare and specific conditions like counting the number of instances created.

[Q-02] Give the code for singleton pattern implementation, also take care of multi-threaded environment.

[A-02] The code are given below for the same:
public class Singleton
   private static Singleton singleInstance = null;

   private Singleton()
      // Exists only to defeat instantiation.
   public static Singleton getSingleInstance()
      if(singleInstance == null)
              synchronised (Singleton class)
                      if(singleInstance == null)
                             singleInstance = new Singleton();

      return singleInstance;

 [Q-03] What are the two methods that every object class overrides ?

[A-03] 'hashcode()' and 'equals()' are the methods which overrides object class. 

[Q-04] What property will a Class and a Method acquires when subjected to association with the 'final' keyword ?

[A-04] A final Class cannot be subclasses or extended while a final method cannot be overridden, in case of final member variable it is counted as constant. 

[Q-05] How many types of exceptions do we have in java, what are the differences between them?

[A-05]  Here we have following types of exceptions:
Checked Exceptions
Environmental error that cannot necessarily be detected by testing; e.g. disk full, broken socket, database unavailable, etc.
Virtual machine error: class not found, out of memory, no such method, illegal access to private field, etc.
Run-time Exceptions
Programming errors that should be detected in testing: index out of bounds, null pointer, illegal argument, etc.
Checked exceptions must be handled at compile time. Run-time exceptions do not need to be. Errors often cannot be.

[Q-06] Can we stop the execution of finally block in exception handling ?

[A-06] Generally a finally block is something meant to be executed irrespective of the occurrences of the exceptions, but however it can be by passed if we irreversibly terminate the execution of the program like this - System.exit(1);

[Q-07] Discuss multiple inheritance in java ?

[A-07] Some object oriented languages, allow a class to inherit from more than one unrelated class. This is called multiple inheritance which java eventually does not supports and is different from the multi-level inheritance in this section. Most of the things that can be accomplished via multiple inheritance can be handled by interfaces in Java.

[Q-08] Why java cannot have multiple inheritance ?

[A-08] The simple answer to the big question is that it will add too much complexity with a very little benefit, in terms of literal basics, we can say that "Classes" in java represents "Noun", whereas "interfaces" represents "adjectives". A child cannot have more than one father, but they can have multiple behaviors (interfaces). A specific problem is associated when we used multiple inherited classes object which is known as "Double Diamond Inheritance Problem". 
The following example explains more about it... 
class Base {
    protected String text;
class SuperOne extends Base {
    protected SuperOne() {
class SuperTwo extends Base {
    protected SuperTwo() {
// Impossible multiple inheritance class; just to explain the problem
class Derived extends SuperOne, SuperTwo {
    public void printText() {
What would you expect that the method printText() prints? Should it print "one" or "two"? Are there two instances of class Base that are part of the instance of class Derived? You don't have this problem with multiple interface inheritance, because an interface does not contain data. Multiple interface inheritance is something completely different from multiple class inheritance, and I don't see any big problems with multiple interface inheritance.

[Q-08] What is JVM memory types ?

[A-08] Java has two types of memory when we talk about JVM, that is Heap Memory and Non Heap Memory.

# Heap Memory 
                          Its a shared memory where multiple threads share the same data, class instances and arrays are stored in heap memory.
# Non-Heap Memory
                                  It comprises of ‘Method Area’ and other memory required for internal processing. So here the major player is ‘Method Area’. As given in the last line, method area is part of non-heap memory. It stores per-class structures, code for methods and constructors. Per-class structure means runtime constants and static fields.

[Q-09] Explain the significance of 'this' keyword in java programming ?

[A-09] 'this' refers to the current instance of the method in which it is used. The following are the scenarios which uses 'this' keyword in java programming - 
# 1 - To specifically differentiate between instance variable to arguments or other local variables.
protected String _userName;

public void setUserName(String _userName)
        this._userName = _userName; //extensively used in case of writing getters/setters
# 2 - To pass the current java instance as parameter.
# 3 - To return the current java instance.
ClassName someMethod() {
        return this;
Note: Should be used carefully while dealing with inner class context, which returns inner class instance rather than outer class.

# 4 - To get the handle of current class. 
Class SampleClass = this.getClass(); // this methodology is preferable in java
Though this can be done by, Class className = ABC.class; // here ABC refers to the class name and you need to know that! 
As always, java this is associated with its instance and this will not work in static methods.

[Q-10] Elaborate the association of keyword 'static' in java programming ?

[A-10] Lets take it as in term of parts starting from -

# static variables
  1. variable that belongs to a class not to an object or instance.
  2. They are initialized only once at the very beginning, these are initialized first before any instance variable.
  3. A single copy to be shared by all the instances.
  4. It can be accessed directly by class name without any need for creation of instances.
#static methods
  1. method that belongs to class not to an object or instance.
  2. It can only access static data, cannot use instance variables.
  3. It can only call static methods not any instance method.
  4. It can be called using class name no need for object creation.
  5. It cannot refer to 'this' or 'super' keywords in anyway.
  6. It can be shadowed by another static method in a subclass, as long as original method is not declared as final.
  7. A static method cannot be overridden by a non-static method (instance method).
  8. Static method is implicitly final in nature.
A main method is always static in nature because it must be accessible for an application to run, before any instantiation should take place.

# static block
The static block, is a block of statement inside a Java class that will be executed when a class is first loaded in to the JVM. A static block helps to initialize the static data members, just like constructors help to initialize instance members

[Q-11] Why Strings are immutable (Objects) ?

[A-11] - First of lets understand what the term immutable stands for. In generic terminology immutable objects are the ones whose every modification creates a new String (Object)or more over an immutable object is something whose state cannot be modified when after it has been created.

- Referenced Variables - In a string pool facility a same string can be referenced through many “referenced variables” for example “sampleStr” can be denoted by two String objects Str1=”sampleStr”; and Str2 = “sampleStr”;  in case of mutable scenario changes in sampleStr for Str1 will be reflected everywhere which is not required.

- Security Threat - Strings are passed as the parameters for various secure methods if make it mutable then anyone can gain access or modify it, that leads to serious vulnerabilities.

- Sync issues - immutability offers safe handling of strings in multi-threaded environments, needn’t to synchronize the string operations externally.

- Caching hashcode -  Being immutable Strings caches its hashcode and don’t re-calculate them again and again making it fast and usable as hashmap key, thus guarantees hashcode to be same on multiple occurences.

- Class Loading -  Strings is used by class loading mechanism and have profound and fundamental aspects of security with it.

[Q-12] Why Char arrays are preferred over Strings for storing passwords?

[A-12] - Since strings are immutable they might be present in string pool till garbage collector truncates them, thats why the probability of their reuse by someone who have access to memory dump (as if the password is stored in plain text). java itself recommends the same. printing of plain text on consoles and logs is pretty high as in case of char array only memory location gets printed.

[Q-13] What is the difference between String Builder and String Buffer classes ?

[A-13] - String Buffer’s all public methods are synchronized which make it thread-safe but at the same time slow. String Builder is not synchronized thus fast, else everything is nearly same. These are the used to get rid of String class immutable problem which overwhelms the memory heap on various operations over string.

[Q-14] Why use of == comparison operator in comparing Strings are discouraged ?

[A-14] - Because ‘==’ just check the if the compared reference variables points towards the same string in the java heap (reference equality) and since strings are immutable thats why it gives sense to the fact that two string literals in the string pool set refer same string object which gives sense that ‘==’ comparison is almost wrong way to do this.

[Q-15] Significance of Runnable interface ?

[A-15] - Implementing runnable interface is one of the ways to create java thread, public void run() is the only method that needs to be overridden for the same.
- Runnable provides the means for the class to be active while not sub-classing it.
- Runnable should be used by any class whose instances are intented to be used by a thread.
- Runnable interface should be used when you are planning to override the run() method not any other Thread Class method.

[Q-16] What is an Adapter Class ?

[A-16] -  Adapter Class is normal class that acts as an Adapter between the Interface and the Class implementing it, such as it only contains empty implementations of all the interface methods.
Benefit - Concrete class using adapter class needn't to implement all the methods unlike implementing the interface. Thus reducing code length and code complexity.
Example - Generic Servlet acts as adapter class for Servlet Interface.

Sunday, October 23, 2011

BIS - Scientist 'B' Written Exam Questions

Today (Sunday Oct 23, 2011) I have given the exam of Bureau of Indian Standards for the post of Scientist - 'B'.
Here are some of the questions which I remember from it:-

Computer Engineering Section
  1. If a Non-Finite-Automata (NFA) has N states then what are the number of states will its minimized Definite-Finite-Automata will have ? 
  2. How many test cases of robustness are possible for the function with 2 variables?
  3. What is the probability that the divisor of 10^99 is the multiple of 10^96?
  4. How many substrings of 00 this automata will hold (0+1)*0(0+1)*0(0+1)* ?
  5. Solve T(1) = 1 and T(n) = 2 + (n-1) + n where n >= 2 
  6. A fair dice is rolled 360 times find out the range of probability of getting '6' on the face 70 times?
  7. What are the state of 2-SAT and 3-SAT problems are they NP-Complete ?
  8. A LAN is 2 Kilometers long and has the bandwidth of 10^7 and is using CSMA/CD the signals travels inside it with the speed of 2 X 10^8 mts/sec what it the minimum packet size ? 
  9. What is Ackerman's Function ?
  10. To solve the root of 13 and find the value after one iteration using Newton Raphson Method.
  11. What is the high level abstraction over Semaphore ?
  12. Using boolean rules simplify x'y' + xy +x'y ? 
  13. Solve finite integral - Integration [0, Pie/4] ( 1 - Tan X ) / (1 + Tan X) dx = 0.
  14. A 6 MHZ channel used by digital signaling system utilizing 4 level signals, what is the maximum possible transfer value ? 
  15. What is the value of i when i = (++i) / (i ++) ; with initial value of 5 ?
  16. An double dimensional integer array in 'C' S[6][6] was filled like - 
          for ( i = 0; i < 6; i++  )
                for ( j = 0; j < 6; j++) { s[i][j] == (i+j)%6; }

          then what is the value for S [ S[5][3] ] [ S[1][3] ] = ?          

All of the above questions gives you the glimpse of the paper and also signifies that it covers almost all the questions of computer engineering course, mainly the paper seen by me in this discipline is flooded with Digital Systems questions on combination circuits , Signals and Systems, Binary conversions with 2's complement, LAN subnet questions max (8-9 questions), Data Structures questions from Binary tree, BST and AVL Tree with few questions on sorting also, Compiler based conceptual questions on Linkers and Loaders, algorithms with minimum spanning trees and shortest path methods, Operating Systems questions like reading disk, paging, addressing memory etc.

General Knowledge, Reasoning and General English Section 

  1. When was Magna Carta signed in England ? 
  2. When is world health day celebrated ?
  3. Where will the summit of NAM in 2012 will held ? 
  4. Which country is the largest producer of wheat?
  5. Which emperor built GT roads in India?
Question in these three sections were easy and requires a fair general knowledge to do the best, 10 questions were of English comprising of synonyms and antonyms checking sentences with errors and filling the appropriate words in the blanks. reasoning was like also easy with some positions and blood relations questions.

Thats all folks, I hoped it may give you the fair idea about how to give the exam in future, if you are motivated towards it.

Good Luck ... All the best
- Bharat Verma 

Friday, July 29, 2011

Java Collections - A Relative Study

Collection refers to a group of multiple elements kept together to do a specific task of choice. A collection can be of same or different types as per the need but it could be relational. Collection is used to store, retrieve, manipulate and communicate aggregated data. Collections are used to ease our need of implementation of new data structure which has required functionality by reducing our programming effort and also reduces the complexity in terms of space and time by increasing the program speed and quality.

Core Collection Interfaces 

Collection          |         Set          |         List          |         Queue          |         Map

  • Collection - it is the basic root of the collection hierarchy. We doesn't have any direct implementation of this interface but there is more specific sub interfaces, such as Set and List.
  • Set - it cannot contains duplicate. It signifies the mathematical abstraction of set theory, like wise you can add the same element many times but you will see it only once when you iterates the collection. Implemented by HashSet and TreeSet.
  • List - its a kind of sequence, a ordered collection. It can have duplicate elements. It is useful in the terms like positional access, search, iteration and range view. Implemented by ArrayList and Linked List.
  • Map - a object that maps keys to values. A Map cannot contain duplicate keys; each key can map to at most one value. It models the mathematical function abstraction. Implemented by HashMap, TreeMap and LinkedHashMap
  • Queue - is a special collection used to hold multiple elements prior to processing. Queue provides additional insertion, extraction and inspection operations.
    Implementation of Collection Classes with source codes

    1.) ArrayList - Can expand automatically, access to any element O(1), insertions and deletions O(N), have methods for inserting, deleting and searching, can be traversed using foreach loop, iterators or indexes.

    Code Snippet:

    package questions;
    import java.util.*;
     * @author Bharat Verma
    public class ArrayListDemo
            public static void printArrayList (ArrayList p_arraylist)
                    System.out.println("Content of ArrayList : "+p_arraylist);
                    System.out.println("Size of ArrayList = "+p_arraylist.size());
            public static void main(String[] args)
                    ArrayList<Object> sampleArrayList =new ArrayList<Object>(); // you can specify the object type
                    Integer intr = new Integer(729);
                    String str ="Bharat";
                    double dtr = 169.721;
                    Integer i5=new Integer(50);
                    sampleArrayList.add(3, i5); // using add(int index, object obj)
                    sampleArrayList.remove(3); // using remove()
                    Object a=sampleArrayList.clone(); // using clone
                    System.out.println("The clone is: " + a);
                    System.out.println(sampleArrayList.contains("Bharat")); // True as it contains
                    // iteration using iterator
                    Iterator iter = sampleArrayList.iterator();
                    System.out.println("Using Iterator");
                    while (iter.hasNext())
                    // using for loop and indexes 
                    System.out.println("Using for loop and index");
                    for (int i=0; i<sampleArrayList.size(); i++)

    2.) Vector - initially it was commonly used in place of arrays just because of their expansion property. The main difference between ArrayList and Vector is the synchronization, ArrayLists are fast as they are unsynchronized as compared to Vectors but less secure in multithreaded environment. Vector can hold objects but not primitive data types (for that wrapper classes is used which is immutable).

    Code Snippet:
    package questions;
    import java.util.*;
     * @author Bharat Verma
    public class VectorDemo
            public static void printVector (Vector p_vector)
                    System.out.println("Content of Vector : "+p_vector);
                    System.out.println("Size of Vector = "+p_vector.size());
            public static void main(String[] args)
                    Vector<Object> vector = new Vector<Object>();
                    int primitiveType = 10;
                    Integer wrapperType = new Integer(20);
                    String str = "Bharat Verma";
                    vector.add(2, new Integer(30));
                    System.out.println("The elements at position 2 is: "
                                    + vector.elementAt(2));
                    System.out.println("The first element of vector is: "
                                    + vector.firstElement());
                    System.out.println("The last element of vector is: "
                                    + vector.lastElement());
                    vector.add(1 , new Integer(10));
                    vector.add(3 , new Integer(10));
                    System.out.println("The last index of 10 : "
                                    + vector.lastIndexOf(10));
                    Enumeration e=vector.elements();
                            System.out.println("The elements are: " + e.nextElement());

    3.) Linked List - it provides insertion of all the elements including NULL. It can be used for implementation of various other associated data structures like Arrays and Queues.

    Code Snippet:
    package questions;
    import java.util.*;
     * @author Bharat Verma
    public class LinkedListDemo
            public static void printLinkedList (LinkedList p_ll)
                    System.out.println("Content of LinkedList : "+p_ll);
                    System.out.println("Size of LinkedList = "+p_ll.size());
            public static void main(String[] args)
                    LinkedList link=new LinkedList();
                    link.add(new Integer(10));
                    link.offerFirst(new Integer(20));
                    System.out.println("The Last element : "+link.getLast());
                    link.offerLast(new Integer(123));
                    System.out.println("The First element : "+link.element());

    4.) HashTable -  Hash table similar to HashMap but is synchronized and comes with its cost, only a single thread can accesss it.
    Hash table does not allows NULL for either keys or values.
    Just like Hashmap you can add same or different values to one key but it will be overwrite them and will store only last one.
    Hash table stores only those objects which overrides the hashcode() and equals() methods defined by the Object Class.Fortunately many object comes with the built in implementation of it like String.

    Code Snippet:
    package collection;
    import java.util.Enumeration;
    import java.util.HashMap;
    import java.util.Hashtable;
    import java.util.Iterator;
    import java.util.Set;
     * @author Bharat Verma
    public class HashTableDemo
            public static void printHashTable (Hashtable hashtable)
                    System.out.println("Retrieving all keys from the Hashtable");
                    Enumeration e = hashtable.keys();
                    while( e. hasMoreElements() )
                    System.out.println("Retrieving all values from the Hashtable");
                    e = hashtable.elements();
                    while(e. hasMoreElements())
            public static void main(String[] args)
                    // First Constructor
                    Hashtable<String, Integer> hashtable = new Hashtable<String, Integer>();
                    // 2nd with initial Capacity 
                    Hashtable ht2 = new Hashtable(5);
                    // 3rd with intial capacity and fill Ratio [0.0 - 1.0]
                    //default load factor is 0.75
                    Hashtable ht3 = new Hashtable(10, (float) 0.50);
                    // 4th with initialisation from a Map
                    Hashtable ht4 = new Hashtable (new HashMap());
                    hashtable.put("One", new Integer(1));
                    hashtable.put("Two", new Integer(2));
                    hashtable.put("Three", new Integer(3));
                    hashtable.put("Four", new Integer(4));
                    // Get the number of key value pairs
                    System.out.println("Hashtable contains " + hashtable.size() + " key value pairs.");
                    // Finding the Element using "Contains"
                    if( hashtable.contains(new Integer(1))){
                            System.out.println("Hashtable contains 1 as value");
                            System.out.println("Hashtable does not contain 1 as value");
                    // Finding the element using the key and "contains key"
                            System.out.println("Hashtable contains One as key");
                            System.out.println("Hashtable does not contain One as value");
                    // we need to have set-view to use iterators 
                    Set set = hashtable.keySet();
                    Iterator itr = set.iterator();
                    String str;
                            str = (String) itr.next();
                            System.out.println(str + ": " +hashtable.get(str));
                    // String Representation of HashTable
                    System.out.println( hashtable.remove("One") + " is removed from the Hashtable.");

    Thursday, June 16, 2011

    Best way to embed source code in Blog

    I have came across to many ways in embedding source code in Blogger but found the best one as Vim. The best way is to write open your source code in Gvim and from the "Syntax" choose "Convert to HTML". gVim creates the file .html file with the same name, for example like if you are using "abc.py" it will create "abc.py.html". Following are the steps to use its code:

    1. The file generated would have code like given below you need to copy the text between the style tags an remove the body tag as it may distort your blog's main formatting. (although I have used "Consolas" it is by default "monospace") :
    2. <style type="text/css">
      pre { font-family: consolas; color: #000000; background-color: #ffffff; }
      .Constant { color: #ff00ff; }
      .Identifier { color: #008080; }
      .Statement { color: #804040; font-weight: bold; }
    3. Use <pre> </pre> tags to write the code in HTML editing mode for the blog just copy the converted code in between of it and the good thing is that gVim produces HTML escaped characters. Example of a python program has been given below for binary search.
    4. def search(sequence, number, lower=0, upper=None):
              if upper is None: upper = len(sequence)-1
              if lower == upper:
                      assert number == sequence[upper]
                      return upper+1
                      middle = (lower + upper) // 2
                      if number > sequence[middle]:
                              return search(sequence, number, middle+1, upper)
                              return search(sequence, number, lower, middle) 
    Other ways includes the use of Javascript Library (Syntax Highlighter Code Project) its client side scripting and support languages like C++, C#, CSS, Delphi, Pascal, Java, Javascript, PHP, Python, Ruby, SQL, Visual Basic, HTML, XML etc. Major issues in using this are adding .js and .css files and also making changes in master template and right angle characters must be HTML escaped, if you are a blogging novice, I advice not to use it.

    Some other uses methods include external code hosting projects like Pastie, Snipplr etc in which my personal favorite is pastie.org but it also have some issues of size and code syntax. see the code snippet below.

    As you can see the code in the 2nd line if haven't taken to the 3rd one it by passes the boundary and goes out of frame, so its also not well suited for this purpose. It comes with an advantage that it allows conversion into plain text and direct download of the code.

    Monday, May 23, 2011

    Git - Version Control System

    An Introduction to GIT - 
    Git is open source distributed version control system developed by Linus Torvalds to handle projects with great speed and efficiency ... Learn more

    Scenario (what I have been working in) - 
    I have a server of Ubuntu on Amazon EC2 and there I hosted one Django project on which I used to commit and deploy the code frequently.

    Checking Out ... 

    you need to generate an SSH key and set it up.
    (You can leave everything to default when keygen asks you questions, thats the easiest way to go along)
    Run this command next, and copy the output to clipboard or something..
    cat ~/.ssh/id_rsa.pub

    Now login to development server:
    ssh -i amazonkey.pem ubuntu@myproject.bharat.in 

    Then update the key as:
    cd .ssh
    cat >> authorized_keys
    (mind the double redirection operator to append to the file)
    paste the copied string, and you are good to go.

    Next, clone from GIT.
    git clone ubuntu@devel.bharat.in:/opt/repos/myproject.git

    (Afterwards, you'll pull to get the latest changes as)
    git pull origin master

    You'll get a directory called myproject in your working directory, cd into it and fire..

    python manage.py runserver

    (That should be all to run the development instance)

    Pushing/Commiting/Deploying etc etc

    When you are done working, you may want to commit the changes..

    git commit -a -m "Some message"

    IMP TIP: If the message contains refs #ISSUEID, the commit will automatically be associated with the issue in its log,
    if the message contains fixes #ISSUEID, the issue will be marked resolved,
    and if the message contains closes #ISSUEID, the issue will be closed. *

    Then you may push the changes to the server back as:
    git push origin master

    (All the commits from the last push in the branch master)

    Finally to deploy, add a remote (one time)
    git remote add stage ubuntu@myproject.bharat.in:/opt/repos/myprojectstage.git

    All you have to do is to push into this remote's master as:
    git push stage master

    (The changes will immediately reflect at http://myproject.bharat.in)

    Production remote:

    git remote add production ubuntu@bharat.in:/home/ubuntu/repos/myprojectprod

    Admin remote:

    git remote add admin ubuntu@stage.bharat.in:/opt/repos/admin.git

    Note for Beginners - 
    Don't loose your heart if you don't have a Amazon EC2 or stuff like that ... you can start doing it using GitHub Please have a note that you have Git installed on any of the operating system you use. You can have git download "Jargon" at Git - Fast Version Control System.

    # for this you need to first have a account on GitHub
    # open git bash through start up launcher and check for .ssh if not then do 
    ssh-keygen -t rsa -C "youremail@provider.domain"
    # now come to .ssh and copy public key's content to github site
    cat id_rsa.pub
    # After doing it fine to check use this command 
    ssh -T git@github.com
    # If it works well then do it like 
    git config --global user.name "FirstName LastName"
    git config --global user.email "handle@provider.domain"
    git config --global github.user githubusername (bindian0509)
    git config --global github.token the_token_you_have_seen_on_github_website
    # now go to the project directory which you have specified in the website (like mine "bharat")
    cd bharat
    git init
    # to add a sample file
    touch README.txt
    git add -A (to add all the files present in your directory)
    git add README (to add only readme)
    git commit -a -m "Message"
    git commit -m "Message"
    # for adding a remote origin to github repos
    git remote add origin git@github.com:bindian0509/bharat.git
    # now push the code to 
    git push origin master
    # and now you are done with it