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.

Post a Comment