Wednesday, March 20, 2019

Java interview questions

Most Common Java interview questions

  • String vs StringBuffer vs StringBuilder 
  1. String : immutable 
  2. StringBuffer : mutable , synchronized
  3. StringBuilder : mutable , not tread safe .

  • Explain toString method.

getClass().getName() + '@' + Integer.toHexString(hashCode())


  • Explain hashcode

it is a native method in object Class , returns integer code .
Two unequal objects can have same hashcode


  • Explain finalize

called before Garbage Collection .
  • How to create a immutable class ?
  1. make the class as final
  2. attributes as private and remove setters .
  3. getters should return a copy of object .
  • what is transient ?
Transient attributes are not serialized .
  • What is volatile ?
Changes made by one thread is immediately reflected on other thread .

  • What is static inner class 
  1. can be accessed without creating object of outer class , does not have access to instance variables .
  • What is Stack
    LIFO 
    1. push : add element on the top of stack
    2. pop : remove element from the top of stack
    3. peek : returns element at top of stack without removing it .
  • What is Queue 
FIFO .
  1. add : adds to last , in case of capacity restriction throws IllegalStateException.
  2. remove : returns and remove the element on the top of the queue , throws NoSuchElementException if the queue is empty .
  3. element : returns the element on the top of the queue , throws NoSuchElementException if the queue is empty .
  4. offer :  adds to last , in case of capacity restriction returns false .
  5. poll: returns and remove the element on the top of the queue , returns null if the queue is empty 
  6. peek: returns  the element on the top of the queue , returns null if the queue is empty .
  • What is Dqueue ?
supports insertion and removal from both ends .
  1. push  (addFirst)  : add element on the top of stack
  2. pop : remove element from the top of stack
  3. peek : returns element at top of stack without removing it .
  4. add : adds to last , in case of capacity restriction throws IllegalStateException.
  5. remove : returns and remove the element on the top of the queue , throws NoSuchElementException if the queue is empty .
  6. element : returns the element on the top of the queue , throws NoSuchElementException if the queue is empty .
  7. offer :  adds to last , in case of capacity restriction returns false .
  8. poll: returns and remove the element on the top of the queue , returns null if the queue is empty 
  9. peek: returns  the element on the top of the queue , returns null if the queue is empty .

  • What is the difference between ArrayList and Vector?
Vector increase of capacity by double of its current capacity , ArrayList increase its capacity by 50%.
  • What is the difference between ArrayList and LinkedList ?
  1. LinkedList implements Dqueue has additional methods .
    1. decendingIterator
    2. getFirst
    3. getLast
    4. addFirst
    5. addLast
  2. Add and remove is faster , get and set is slower in LinkedList.
  3. ArrayList stores data in contiguous locations LinkedList store data using pointers and reference 
  4. LinkedList is better if we need to perform data manipulation , arrayList is better if we just want to send the data.
  • Explain Legacy collection in  java ?
All are synchronized
  1. Vector , Stack (LIFO ) :  dynamic array
  2. Dictionary (abstract) , Hashtable (concrete ), Properties ( string key and value , loaded to/from file)  :  key value pair ,null key not allowed 
  3. Enumeration : Iterate over legacy collection

  • How to make ArrayList thread safe.
  1. Use Collections.synchronizedList
  2. CopyOnWriteArrayList : can be modified during iteration but modified values will not be reflected .


  • How do HashMap handles different key with same hashcode ?
takes the hashcode of the key and check if it matches a with the hashcode of existing key . If the same hashcode exists then it compares both the keys using equals method . If both the keys are same it replaces the existing value with the new one . If both the keys does not match then it adds a new entry  in the same bucker .

  • What is BlockingQueue
Thread-safe , does not accept null value . FIFO . It is used to implement producer / consumer issues .
  1. put : add the element to the queue , if space is not available it waits for the space to be available.
  2. take : returns element from head of the queue , if no elements wait for the element to come.
  • What are the new features added in Java 7?
  1. Try with resources : the resources will be closed automatically (ARM), 
    • should implement AutoCloseable introduced in Java 7 .
    • to support ARM Suppressed Exceptions are introduced .
    • the exceptions originating at try block is propagated and the exceptions occurring in finally block is suppressed . 
    • addSuppressed and getSuppressed methods added in Throwable class
    • Closeable interface now extends AutoClosable interface .
  2. Multiple Exception in single catch separated by | . 
  3. Underscore in numeric literals
  4. Binary literals 0b,0B
  5. Switch case with string
  6.  Type interface for generic instance.using <> .
  7. Java.nio.file package : used to create, delete , copy , move etc. files and directories.
  8. @SafeVarargs : used by programmer to mark that no unsafe operations are performed in the constructor with var args .
  9. String constant pool is stored in heap instead of perm gen.

  • New features in Java 8
  1. Perm gen is removed.
  2. Functional interface
  3. Lambda support
  4. Interface default and static 
  5. For each in iterator
  6. Java stream API.
  7. Optional class : avoid null pointer
  • Explain interface default method :
  1. The implementing class does need not implement the default method.
  2. Sub interfaces can override or make it abstract .

  • Explain method reference
Static method 
Class name :: method name
Instance method
Object name:: method name


  • How does multiple inheritance issue for default method is handled .
It is mandatory for the implementing class to implement a default method in case of multiple inheritance issue .

  • What is optional class in Java 8
Pre defined action instead of throwing null pointer exception.


  • Explain functional interface

@FunctionalInterface annotation will add a compile time check for an interface to have only one abstract method. It will be used for lambda expressions.
  • Explain memory management in Java.
  1. Heap : stores object data.
  2. Permgen : stores class data ,method local initialization , string contact pool.
  3. Stack : store data required while returning from method
  • How to manage memory ?
  1. System.gc() or Runtime.gc() : garbage collector may be called .
  2. Runtime.freeMemory() : free memory 
  3. Runtime.totalMemory() : total memory available
  4. Runtime.maxMemory() : maximum memory that JVM is going to use
      • What is just in time compiler(JIT)
      converts byte code to native code to boost performance .
      • Explain Creational Design Patterns .
      1. Factory 
      2. Abstract Factory
      3. Builder : create complex object , method chaining .
      4. Singleton
      5. Prototype
      • Explain Structural Design Patter .
      1. Adapter
      2. Bridge
      3. Composite
      4. Decorator
      5. Facade
      6. Flywheel
      7. Proxy
      • Explain Behavioral Design Patter .
      1. Chain of Responsibility
      2. Command
      3. Interpretor : how to include language  elements
      4. Iterator
      5. Mediator : simplify communication between objects
      6. Observer : multiple objects notification
      7. State : modify the behavior on state change
      8. Template : abstract definition of algorithm
      9. Visitor : add polymorphic functions to class noninvasively .

      • How can we make singleton class thread safe.
      Null check for instance and creation of new object should be done inside a synchronized block.
      • What is executor service?
      It provides a pool of threads and API to assign task for it.Simplifies task execution in async mode.

      • What is Thread.yeald?
      Thread Scheduler checks if any other thread available with same or higher priority and transfer the processor to it .


      • Explain serialization

      1. Serializable interface should be implemented .
      2. Serializable is a marker interface for identification .
      3. sub class must be serializable ,  super class need not be serializable .
      4. Transient and static attributes are not serialized.
      5. readresolve method can be implemented and same instance can be returned, while deserialization of singleton class.
      6. Write replace is called before write object .

      • Explain serialVersionUID .
      1.  if it not present java compiler adds it .
      2.  it is static final and long . 
      3. It is used to check the sender and receiver are compatible if there is mismatch in the serialVersionUID InvalidClassException is thrown .
      4. If there is no serialVersionUID and we have serialized an object  , we added some field and now if we want to deserialize it we get InvalidClassException .


      • Explain Externalizable interface 
      used for custom serialization 

      1. readExternal
      2. writeExternal


      • Explain classloaders 
      they load classes during runtime dynamically .

      1. Bootstrap : parent of all , first to be loaded
      2. extension : load all classes from .jar from  java.ext.dirs
      3. system : loads the classes at java.class.path or classes specified at -classpath .

      No comments:

      Post a Comment

      ec2-user@ec2 Permission denied