Friday, 27 May 2016

Interview questions on Java File IO

File IO in java

  1. What is a IO stream?
    • It is a stream of data that flows from source to destination. Good example is file copying. Two streams are involved – input stream and output stream. An input stream reads from the file and stores the data in the process (generally in a temporary variable). The output stream reads from the process and writes to the destination file.
  2. What are the super most classes of all streams?
    • All the byte stream classes can be divided into two categories (input stream classes and output stream classes) and all character streams classes into two (reader classes and writer classes). There are four abstract classes from which all these streams are derived. The super most class of all byte stream classes is and for all output stream classes, Similarly for all reader classes is and for all writer classes is
  3. What is the necessity of two types of streams – byte streams and character streams?
    • Byte streams were introduced with JDK 1.0 and operate on the files containing ASCII characters. We know Java supports other language characters also known as Unicode characters. To read the files containing Unicode characters, the designers introduced character streams with JDK 1.1. As ASCII is a subset of Unicode, for the files of English characters, we can go with either byte streams or character streams.
  4. What are FileInputStream and FileOutputStream?
    • These two are general purpose classes used by the programmer very often to copy file to file. These classes work well with files containing less data of a few thousand bytes as by performance these are very poor. For larger data, it is preferred to useBufferedInputStream (or BufferedReader) and BufferedOutputStream (or BufferedWriter).
  5. Which you feel better to use – byte streams or character streams?
    • I feel personally to go with character streams as they are the latest. Many features exist in character streams that do not in byte streams like a) using BufferedReader in place of BufferedInputStreams and DataInputStream (one stream for two) and b) using newLine()method to go for next line and for this effect we must go for extra coding in byte streams etc.
  6. What is PrintStream and PrintWriter?
    • Functionally both are same but belong to two different categories – byte streams and character streams. println() method exists in both classes.
  7. Which streams are advised to use to have maximum performance in file copying? 
    • BufferedInputStream and BufferedOutputStream on byte streams side and BufferedReader and BufferedWriter on character streams side.
  8. What are piped streams?
    • There are four piped streams – PipedInputStream, PipedOutputStream, PipedReader and PipedWriter. These streams are very useful to pass data between two running threads (say, processes).
  9. What is File class?
    • It is a non-stream (not used for file operations) class used to know the properties of a file like when it was created (or modified), has read and write permissions, size etc.
  10. What is RandomAccessFile?
    • It is a special class from package which is neither a input stream nor a output stream (because it can do both). It is directly a subclass of Object class. Generally, a stream does only one purpose of either reading or writing; but RandomAccessFile can do both reading from a file and writing to a file. All the methods of DataInputStream and DataOutStream exist in RandomAccessFile.
Example : How to use FileWriter

import*;  class Simple{

public static void main(String args[]){  


FileWriter fw=new FileWriter("abc.txt");
fw.write("my name is sachin"); 
}catch(Exception e){System.out.println(e);}    

Buy New Phone :)

Tuesday, 24 May 2016

Interview questions on Java Thread

Thread in Java

  1. What is Thread in Java?
    1. Thread is an independent path of execution. It's way to take advantage of multiple CPU available in a machine. By employing multiple threads you can speed up CPU bound task. For example, if one thread takes 100 millisecond to do a job, you can use 10 thread to reduce that task into 10 millisecond. Java provides excellent support for multi-threading at language level, and its also one of strong selling point.
  2. Difference between Thread and Process in Java?
    1. Thread is subset of Process, in other words one process can contain multiple threads. Two process runs on different memory space, but all threads share same memory space. Don't confuse this with stack memory, which is different for different thread and used to store local data to that thread.
  3. What is a life-cycle of thread

  4. How do you implement Thread in Java?
    1. At language level, there are two ways to implement Thread in Java. An instance of java.lang.Thread represent a thread but it need a task to execute, which is instance of interface java.lang.Runnable. Since Thread class itself implement Runnable, you can override run() method either by extending Thread class or just implementing Runnable interface.
  5. When to use Runnable vs Thread in Java?
    1. This is follow-up of previous multi-threading interview question. As we know we can implement thread either by extending Thread class or implementing Runnable interface, question arise, which one is better and when to use one? This question will be easy to answer, if you know that Java programming language doesn't support multiple inheritance of class, but it allows you to implement multiple interface. Which means, its better to implement Runnable than extends Thread, if you also want to extend another class e.g. Canvas or CommandListener.
  6. Difference between start() and run() method of Thread class?
    1. One of trick Java question from early days, but still good enough to differentiate between shallow understanding of Java threading model start() method is used to start newly created thread, while start() internally calls run() method, there is difference calling run() method directly. When you invoke run() as normal method, its called in the same thread, no new thread is started, which is the case when you callstart() method.
  7. Difference between Runnable and Callable in Java?
    1. Both Runnable and Callable represent task which is intended to be executed in separate thread. Runnable is there from JDK 1.0, while Callable was added on JDK 1.5. Main difference between these two is that Callable's call() method can return value and throw Exception, which was not possible with Runnable's run() method. Callable return Future object, which can hold result of computation.
  8. What is volatile variable in Java?
    • volatile is a special modifier, which can only be used with instance variables. In concurrent Java programs, changes made by multiple threads on instance variables is not visible to other in absence of any synchronizers e.g. synchronized keyword or locks. Volatile variable guarantees that a write will happen before any subsequent read.
  9. What is thread-safety? is Vector a thread-safe class?
    • Thread-safety is a property of an object or code which guarantees that if executed or used by multiple thread in any manner e.g. read vs write it will behave as expected. For example, a thread-safe counter object will not miss any count if same instance of that counter is shared among multiple threads. Apparently, you can also divide collection classes in two category, thread-safe and non-thread-safe. Vector is indeed a thread-safe class and it achieves thread-safety by synchronizing methods which modifies state of Vector, on the other hand, its counterpart ArrayList is not thread-safe.
  10. What is race condition in Java? Given one example?
    • Race condition are cause of some subtle programming bugs when Java programs are exposed to concurrent execution environment. As name suggests, race condition occurs due to race between multiple threads, if a thread which is supposed to execute first lost the race and executed second, behaviour of code changes, which surface as non-deterministic bugs. This is one of the hardest bugs to find and re-produce because of random nature of racing between threads. One example of race condition is out-of-order processing.
  11. How to find Race Conditions in Java ?
    • Finding Race conditions in any language is most difficult job and Java is no different, though since readability of Java code is very good and synchronized constructs are well defined heaps to find race conditions by code review. finding race conditions by unit testing is not reliable due to random nature of race conditions. since race conditions surfaces only some time your unit test may passed without facing any race condition. only sure shot way to find race condition is reviewing code manually or using code review tools which can alert you on potential race conditions based on code pattern and use of synchronization in Java.
  12. How to stop thread in Java?
    • I always said that Java provides rich APIs for everything but ironically Java doesn't provide a sure shot way of stopping thread. There was some control methods in JDK 1.0 e.g. stop(), suspend() and resume() which was deprecated in later releases due to potential deadlock threats, from then Java API designers has not made any effort to provide a consistent, thread-safe and elegant way to stop threads. Programmers mainly rely on the fact that thread stops automatically as soon as they finish execution of run() or call() method. To manually stop, programmers either take advantage of volatile boolean variable and check in every iteration if run method has loops or interrupt threads to abruptly cancel tasks.
  13. What happens when an Exception occurs in a thread?
    • This is one of the good tricky Java question I have seen on interviews. In simple words, If not caught thread will die, if an uncaught exception handler is registered then it will get a call back. Thread.UncaughtExceptionHandler is an interface, defined as nested interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception. When a thread is about to terminate due to an uncaught exception the Java Virtual Machine will query the thread for its UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() and will invoke the handler's uncaughtException() method, passing the thread and the exception as arguments.
  14. How to register an uncaught exception handler for a thread.
    1. public class ThreadDemo {
        public static void main(String[] args) {
      Thread t = new Thread(new adminThread());
         t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(Thread t, Throwable e) {
             System.out.println(t + " throws exception: " + e);
         // this will call run() function
      class adminThread implements Runnable {
        public void run() {
         throw new RuntimeException();
      Output : Thread[Thread-0,5,main] throws exception: java.lang.RuntimeException
  15. How do you share data between two thread in Java?
    • You can share data between threads by using shared object, or concurrent data-structure like BlockingQueue.
    • One Standard Example is Producer and Consumer problem.
  16. Difference between notify and notifyAll in Java?
    • This is another tricky questions from core Java interviews, since multiple threads can wait on single monitor lock, Java API designer provides method to inform only one of them or all of them, once waiting condition changes, but they provide half implementation. There notify() method doesn't provide any way to choose a particular thread, that's why its only useful when you know that there is only one thread is waiting. On the other hand, notifyAll() sends notification to all threads and allows them to compete for locks, which ensures that at-least one thread will proceed further.
  17. Why wait, notify and notifyAll are not inside thread class?
    • This is a design related question, which checks what candidate thinks about existing system or does he ever thought of something which is so common but looks in-appropriate at first. In order to answer this question, you have to give some reasons why it make sense for these three method to be in Object class, and why not on Thread class. One reason which is obvious is that Java provides lock at object level not at thread level. Every object has lock, which is acquired by thread. Now if thread needs to wait for certain lock it make sense to call wait() on that object rather than on that thread. Had wait() method declared on Thread class, it was not clear that for which lock thread was waiting. In short, since wait, notify and notifyAll operate at lock level, it make sense to defined it on object class because lock belongs to object.
  18. Why wait and notify method are called from synchronized block?
    • Main reason for calling wait and notify method from either synchronized block or method is that it made mandatory by Java API. If you don't call them from synchronized context, your code will throw IllegalMonitorStateException. A more subtle reason is to avoid race condition between wait and notify calls.
  19. Difference between Stack and Heap in Java?
    • Why do someone this question as part of multi-threading and concurrency? because Stack is a memory area which is closely associated with threads. To answer this question, both stack and heap are specific memories in Java application. Each thread has their own stack, which is used to store local variables, method parameters and call stack. Variable stored in one Thread's stack is not visible to other. On other hand, heap is a common memory area which is shared by all threads. Objects whether local or at any level is created inside heap. To improve performance thread tends to cache values from heap into their stack, which can create problems if that variable is modified by more than one thread, this is where volatile variables comes in picture. volatile suggest threads to read value of variable always from main memory.
  20. How do you check if a Thread holds a lock or not?
    • There is a method called holdsLock() on java.lang.Thread, it returns true if and only if the current thread holds the monitor lock on the specified object.
  21. There are three threads T1, T2 and T3? How do you ensure sequence T1, T2, T3 in Java?
    • Sequencing in multi-threading can be achieved by different means but you can simply use join() method of thread class to start a thread when another one is finished its execution. To ensure three threads execute you need to start the last one first e.g. T3 and then call join methods in reverse order e.g. T3 calls T2. join, and T2 calls T1.join, this ways T1 will finish first and T3 will finish last.
  22. What does yield method of Thread class do?
    • Yield method is one way to request current thread to relinquish CPU so that other thread can get chance to execute. Yield is a static method and only guarantees that current thread will relinquish the CPU but doesn't say anything about which other thread will get CPU. Its possible for same thread to get CPU back and start its execution again.

Friday, 13 May 2016

Serialization Interview Questions

Serialization in Java

  1. What is Serialization in Java?
    1. Object Serialization in Java is a process used to convert Object into a binary format which can be persisted into disk or sent over network to any other running Java virtual machine; the reverse process of creating object from binary stream is called deserialization in Java. Java provides Serialization API for serializing and deserializing object which includes,, ObjectInputStream and ObjectOutputStream etc.
  2. How to make a Java class Serializable?
    1. Making a class Serializable in Java is very easy, Your Java class just needs to implements interface and JVM will take care of serializing object in default format.
  3. What is the difference between Serializable and Externalizable interface in Java?
    1. This is most frequently asked question in Java serialization interview. Here is my version Externalizable provides us writeExternal() and readExternal() method which gives us flexibility to control java serialization mechanism instead of relying on Java's default serialization. Correct implementation of Externalizable interface can improve performance of application drastically.
  4. How many methods Serializable has? If no method then what is the purpose of Serializable interface?
    1. Serializable interface exists in package and forms core of java serialization mechanism. It doesn't have any method and also called Marker Interface in Java. When your class implements interface it becomes Serializable in Java and gives compiler an indication that use Java Serialization mechanism to serialize this object.
  5. What is Marker interfaces in Java and why required?
    1. Looking carefully on marker interface in Java e.g. Serializable, Clonnable and Remote it looks they are used to indicate something to compiler or JVM. So if JVM sees a Class is Serializable it done some special operation on it, similar way if JVM sees one Class is implement Clonnable it performs some operation to support cloning. Same is true for RMI and Remote interface. So in short Marker interface indicate, signal or a command to Compiler or JVM.
  6. While serializing you want some of the members not to serialize? How do you achieve it?
    1. if you don't want any field to be part of object's state then declare it either static or transient based on your need and it will not be included during Java serialization process.
  7. What will happen if one of the members in the class doesn't implement Serializable interface?
    1. One of the easy question about Serialization process in Java. If you try to serialize an object of a class which implements Serializable, but the object includes a reference to an non- Serializable class then a 'NotSerializableException’ will be thrown at runtime.

Tuesday, 22 March 2016

Create Java object from a XML

In this post you will learn how to get a Java object from a given XML.

Step1: Add maven dependency.


Step2: Create a pojo model class

package com.sumit.xmlJava;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
public class Employee
   private Integer id;
   private String firstName;
   public Employee(){}
   public Employee(Integer id, String name){ = id; = name;
   public Integer getId(){
      return id;
   public void setId(Integer id){ = id;
   public String getFirstName(){
      return name;
   public void setFirstName(String name){ = name;
   public String toString()
      return "Employee [id=" + id + ", name=" + name "]";

Step3: Create Java Object from Json

package com.sumit.xmlJava;
import org.codehaus.jackson.JsonGenerationException;
public class JSONToJavaExample
   public static void main(String[] args){
      try {
File file=new File("/home/sumit/Desktop/sample.xml");
JAXBContext jaxbContext=JAXBContext.newInstance(Employee.class);
Unmarshaller jaxbUnmarshaller=jaxbContext.createUnmarshaller();
Employee employee=(Employee)jaxbUnmarshaller.unmarshal(file);

Output: Employee [id=1, name=Sumit Kumar]

Note: File /home/sumit/Desktop/sample.xml Contains following data

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<name>Sumit Kumar</name>


Sumit Kumar