Java Interview Questions


Some of the most common interview questions I generally ask java programmers. For more comprehensive list , check Java Interview Questions

Q) What is polymorphism ?

Ans) The ability to define a function in multiple forms is called Polymorphism. In java,c++ there are two types of polymorphism: compile time polymorphism (overloading) and runtime polymorphism (overriding). Mehtod overriding Overriding occurs when a child class implements the method with same signature as a method in parent class. When you override methods, JVM determines the proper methods to call at the program’s run time, not at the compile time.

Overloading occurs when several methods have same names but different number or type of parameters.

  • Overloading is determined at the compile time.
  • Different method signature and different number or type of parameters.
  • Same method signature but different number of parameters.
  • Same method signature and same number of parameters but of different type

Example of Overloading

int add(int a,int b)
   float add(float a,int b)
   float add(int a ,float b)
   void add(float a)
   int add(int a)
   void add(int a) //error conflict with the  method int add(int a)
class BookDetails{
  String title;
  setBook(String title){}
}
class ScienceBook extends BookDetails{
  setBook(String title){} //overriding
  setBook(String title, String publisher,float price){} //overloading

Q) What is the difference between final, finally and finalize() in Java?

Ans) final – A final variable acts as a constant, a final class is immutable and a final method cannot be ovrriden while doing inheritance.

finally – handles exception. The finally block is optional and provides a mechanism to clean up regardless of what happens within the try block (except System.exit(0) call). Use the finally block to close files or to release other system resources like database connections, statements etc.

finalize() – method belongs to Object class. The method that is invoked while doing the garbage collection of the object. It could be used for allowing it to clean up its state. Good use cases will be to free connection pools , deallocate resources etc.

Q)What is difference between HashMap and HashTable ?

Ans) 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. Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn’t.
    Fail-safe -if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationException?
  3. HashMap permits null values and only one null key, while Hashtable doesn’t allow key or value as null.

Q) What is difference between abstract class and interface ?

Ans)

  • A class is called abstract when it contains at least one abstract method. It can also contain n numbers of concrete method.Interface can contain only abstract( non implemented) methods.
  • The abstract class can have public,private,protect or default variables and also constants. In interface the variable is by default public final. In nutshell the interface doesnt have any variables it only has constants.
  • A class can extend only one abstract class but a class can implement multipleinterfaces.
  • If an interface is implemented its compulsory to implement all of its methods but if an abstract class is extended its not compulsory to implement all methods.
  • The issue with an interface is, if you want to add a new feature (method) in its contract, then you MUST implement those method in all of the classes which implement that interface. However, in the case of an abstract class, the method can be simply implemented in the abstract class and the same can be called by its subclass.

Q) What is the difference between equals() and == ?

Ans) == operator is used to compare the references of the objects.
public bollean equals(Object o) is the method provided by the Object class. The default implementation uses == operator to compare two objects. But since the method can be overriden like for String class. equals() method can be used to compare the values of two objects.

String str1 = "MyName"; 
String str2 = "MyName";
String str3 = new String(str2);

if (str1 == str2) {
  System.out.println("Objects are equal")
}else{
  System.out.println("Objects are not equal")
}
if(str1.equals(str2)) {
  System.out.println("Objects are equal")
} else {
  System.out.println("Objects are not equal")
}

Output:
Objects are not equal
Objects are equal
String str2 = "MyName";
String str3 = str2;
if (str2 == str3) {
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}
if (str3.equals(str2)) {
  System.out.println("Objects are equal")
} else {
  System.out.println("Objects are not equal")
}

Output:
Objects are equal
Objects are equal

Q) What is difference between an ArrayList and a vector?

Ans)

  • Synchronization – ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block, thus making Vector class thread-safe.
  • 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.
  • Performance – Since vector is thread-safe, the performance is slower than ArrayList.

Q) Which all classes implement Set interface ?

Ans) A Set is a collection that contains no duplicate elements. More formally, a set contains no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. HashSet,SortedSet and TreeSet are the commonly used class which implements Set interface.

  • 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.
  • 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. The class uses Red-Black tree data structure.
  • 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. This class permits the null element. This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets

 

 

Q) Explain the exception hierarchy in java.

Ans) The hierarchy is as follows:

java exception hierarchy

Throwable is a parent class of all Exception classes. There are two types of Exceptions: Checked exceptions and UncheckedExceptions or RunTimeExceptions. Both type of exceptions extends Exception class.

Difference between final, finally and finalize in Java ?

Tags


final – final keyword can be used with a class, variable or a method.

  • A variable declared as final acts as constant, which means one a variable is declared and assigned , the value cannot be changed. An object can also be final, which means that the once the object is created it cannot be assigned a different object, although the properties or fields of the object can be changed.
  • A final class is immutable, which means that no other class can extend from it. E.g String, Integer.
  • A final method in a class cannot be overridden in the child class.

The underlying behavior of using final keyword is to act as constant.

public class Test {
    private static final String PREFIX = "test." 
    private final MyClass obj = new Myclass();

    publc Test() {
      obj = new MyClass() ;// throws error 
    }
  }
  public class Test {
    private static final String PREFIX = "test." 
    private final MyClass obj;

    publc Test() {
      obj = new MyClass() ;// this works
    }
  }

finally – finally keyword is used with try-catch block for handling exception. The finally block is optional in try-catch block. The finally code block is always executed after try or catch block is completed. The general use case for finally block is close the resources used in try block. For e.g. Closing a FileStream, I/O stream objects, Database connections, HTTP connections are generally closed in a finally block.

public class Test {
  public static void main(String[] args) {
    BufferedReader br = null;
    try {
      String sCurrentLine = "";
      br = new BufferedReader(new FileReader("C:\\testing.txt"));
      while ((sCurrentLine = br.readLine()) != null) {
        System.out.println(sCurrentLine);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally { // close the resource. 
      try {
        if (br != null)br.close();
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }
}

finalize() – This is the method of Object class.It is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.

How to code URL shortener from scratch?

Tags


I am going to explain one of the common approaches used to create URL shortner.

  1. Think of an alphabet we want to use. In your case that’s [a-zA-Z0-9]. It contains 62 letters.
  2. Take an auto-generated, unique numerical key (the auto-incremented id of a MySQL table for example).

    For this example I will use 12510 (125 with a base of 10).

  3. Now you have to convert 12510 to X62 (base 62).

    12510 = 2×621 + 1×620 = [2,1]

    Now map the indices 2 and 1 to your alphabet. This is how your mapping (with an array for example) could look like:

    0  → a
    1  → b
    ...
    25 → z
    ...
    52 → 0
    61 → 9
    

    With 2 → c and 1 → b you will receive cb62 as the shortened URL.

    http://shor.ty/cb
    

How to resolve a shortened URL to the initial ID

The reverse is even easier. You just do a reverse lookup in your alphabet.

  1. e9a62 will be resolved to “4th, 61st, and 0th letter in alphabet”.

    e9a62 = [4,61,0] = 4×622 + 61×621 + 0×620 = 1915810

  2. Now find your database-record with WHERE id = 19158 and do the redirect.

Use of hashcode() and equals()


Tech Read..

Use of hashCode() and equals(). 

Object class provides two methods hashcode() and equals() to represent the identity of an object. It is a common convention that if one method is overridden then other should also be implemented.

Before explaining why, let see what the contract these two methods hold. As per the Java API documentation:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashcode() method must consistently return the same integer, provided no information used in equals() comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(object) method, then calling the hashCode() method on each of the two objects must produce the same integer result.
  • It is NOT required that if two objects are…

View original post 958 more words

Quick Tip: How to Work with GitHub and Multiple Accounts

Tags


Sometimes you may need to have multiple github accounts (one for office, one for work , one for girl friend, whatever) .

Lets say you have ssh keys already setup and github is set for one account. Now for new account:

  • Create a new ssh key

ssh-keygen -t rsa -C "your-email-address"

     Careful while name the file , dont overwrite the existing one .I named it as ~/.ssh/id_rsa_xxx

  • Add the new key to github account

     This is simple enough. Copy the id_rsa_xxx.pub in github > Settings > SSH Keys

  • Create a new config file in  vi ~.ssh/config

        Add following :

#Default GitHub
Host github.com
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa
Host github-COMPANY
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa_xxxx
 
You are done . Try it out ..
Vola !! Happy coding !!
Follow

Get every new post delivered to your Inbox.

Join 198 other followers