Thursday 3 September 2015

Frequently Asked Core Java Question and Answer



1)  How Java achieves platform independence?
Answer : When we say Java is platform independent which means Java programs are not dependent on any platform, architecture or operating system like windows or Linux. Java achieve this by using Java virtual machine, when Java programs are compiled they are converted to .class file which is collection of byte code and directly understandable  by JVM. So the same Java program can run on any operating system only JVM can differ according to OS but all JVM can understand converted byte code that's how Java achieve platform independence. For a more detailed answer of this question, see
here.


2)  What is ClassLoader in Java?
Answer : This was one of advanced question few years ago, but in span of two to three years, this has become very common. When a Java program is converted into .class file by Java compiler  which is collection of byte code  class loader is responsible to load that class file from file system,network or any other location. This class loader is nothing but also a class from which location they are loading the class according to that class loaders are three types :
  1.Bootstrap
  2.Extension
  3.System class loader .
to learn more classloaders in Java, see my article
how classloader works in Java.


3)  Write a Java program to check if a number is Even or Odd?
Answer : This question is not particularly related to Java and also asked on other programming interviews e.g. C, C++ or C#. I have included this in my list of frequently asked questions from Java interviews because I have seen it more often than not.
import java.util.Scanner;

class TestEvenOdd {
 public static void main(String arg[]){
   int num;
   //Read a number
   Scanner input = new Scanner(System.in);
   System.out.println("Enter a number to check its Even or Odd");
   num = input.nextInt();
   // Conditional operator
   System.out.println((num%2)==0 ? "even number":"odd number");
  }
}


4)  Difference between ArrayList and HashSet in Java?
Answer : If I say that this is one of the most most frequently asked question to Java programmers, then it would not be wrong. Along with questions like
ArrayList vs LinkedList and ArrayList vs Vector, this question is most common on various Java interviews. Here are some important differences between these two classes :
  1. ArrayList implements List interface while HashSet implements Set interface in Java.
  2. ArrayList is an ordered collection and maintains insertion order of elements while HashSet is an unordered collection and doesn't maintain any order.
  3. ArrayList allow duplicates while HashSet doesn't allow duplicates.
  4. ArrayList is backed by an Array while HashSet is backed by an HashMap instance.
  5. One more difference between HashSet and ArrayList is that its index based you can retrieve object by calling get(index) or remove objects by calling remove(index) while HashSet is completely object based. HashSet also doesn't provide get() method.



5)  What is double checked locking in Singleton?
Answer : Interviewer will never stop asking this question. It's mother of all frequently asked question in Java. Singleton means we can create only one instance of that class,in term of singleton DCL is the way to  ensure that at any cost only  one instance is created in multi-threaded environment its possible that simultaneously two thread trying to create instance of singleton class in that situation we cant sure that only one instance is created so avoid this situation using double checked locking by using synchronized block where we creating the object.

Code Example :
class SingletonClass {
  private DCL dcl = null;
  public DCL getDCL() {
    if (dcl == null) {
      synchronized {
        if (dcl == null)
          dcl = new DCL();
      }
    }
    return dcl;
  }
}
To learn more about why double checked locking was broken before Java 1.5, see this article.

6)  How do you create thread-safe Singleton in Java?
Answer : This is usually follow-up of previous Java question. There are more than one ways to do it. You can  create thread safe Singleton class in Java by creating the one and only instance during class loading. static fields are initialized during class loading and Classloader will guarantee that instance will not be visible until its fully created.


7)  When to use volatile variable in Java?
Answer : Volatile keyword is used with only variable  in Java and it guarantees that value of volatile variable will always be read from main memory and not from Thread's local cache. So we can use volatile to achieve synchronization because its guaranteed that all reader thread will see updated value of volatile variable once write operation completed, without volatile keyword different reader thread may see different values. Volatile modifier also helps to prevent reordering of code by compiler and offer visibility guarantee by happens-before relationship. See this article to learn more about
volatile in Java.


8)  When to use transient variable in Java?
Answer : Transient in Java is  used to indicate that the variable should not be serialized. Serialization is a process of saving an object's state in Java. When we want to persist and object's state by default all instance variables in the object is stored. In some cases, if you want to avoid persisting some variables because we don’t have the necessity to transfer across the network. So, declare those variables as transient. If the variable is declared as transient, then it will not be persisted. This is the main purpose of the transient keyword, to learn more about transient variable in Java, see this
tutorial.


9)  Difference between transient and volatile variable in Java?
Answer : This is again follow-up of previous two Java questions. You will see this question on top 10 on any list of Java frequently asked question. Here are some of the important difference between them.
Transient variable : transient keyword is used with those instance variable which will not participate in serialization process.we cannot use static with transient variable as they are part of instance variable.
Volatile variable : volatile keyword is used with only variable  in Java and it guarantees that value of volatile variable will always be read from main memory and not from Thread's local cache, it can be static.
to learn more differences and answer this question in detail, see
here.


10) Difference between Serializable and Externalizable in Java?
Answer : If I say this is one of the most frequently asked Java question on both face-to-face and telephonic interview then it would be an exaggeration. Serialization is a default process of  serializing or persisting  any object's state in Java. It's triggered by implementing Serializable interface which is a marker interface (an interface without any method). While Externalizable is used to customize and control default serialization process which is implemented by application. Main difference between these two is that Externalizable interface provides complete control to the class implementing the interface whereas Serializable interface normally uses default implementation to handle the object serialization process.
Externalizable interface has two method
writeExternal(ObjectOutput) and readExternal(ObjectInput) method which are used to handle customized object serialize process and in terms of performance its good because everything is under control. to learn more about this classical question, see this answer as well.


11) Can we override private method in Java?
Answer : No, we cannot override private methods in Java as if we declare any variable ,method as private that variable or method will be visible for that class only and also if we declare any method as private than they are bonded with class at compile time not in run time so we cant reference those method using any object so we cannot override private method in Java.


12) Difference between Hashtable and HashMap in Java?
Answer : This is another frequently asked question from Java interview. Main difference between HaspMap and Hashtable are following :
  • HashMap allows null values as key and value whereas Hashtable doesn't allow nulls.
  • Hashtable is thread-safe and can be shared between multiple threads whereas HashMap cannot be shared between multiple threads without proper synchronization.
  • Because of synchronization, Hashtable is considerably slower than HashMap, even in case of single threaded application.
  • Hashtable is a legacy class, which was previously implemented Dictionary interface. It was later retrofitted into Collection framework by implementing Map interface. On the other hand, HashMap was part of framework from it's inception.
  • You can also make your HashMap thread-safe by using Collections.synchronizedMap() method. It's performance is similar to Hashtable.
See here to learn more and understand when to use Hashtable and HashMap in Java



13) Difference between List and Set in Java?
Answer : One more classic frequently asked question. List and set both are very useful interfaces of  collections in Java and  difference between these two is list allows duplicate element but set don't allows duplicate elements another difference is list maintain the insertion order of element but set is unordered collection .list can have many null objects but set permit only one null element. This question is some time also asked as difference between
Map, List and Set to make it more comprehensive as those three are major data structure from Java's Collection framework. To answer that question see this article.


14) Difference between ArrayList and Vector in Java
Answer : One more favourite of Java Interviewers, there is hardly any interview of junior Java developers, on which this question doesn't appear. In four and five round of interview, you will definitely going to see this question in some point of time. Vector and ArrayList both implement the list interface but main difference between these two is vector is synchronized and thread safe but list is not because of this list is faster than vector.


15) Difference between Hashtable and ConcurrentHashMap in Java?
Answer : Both Hashtable and ConcurrentHashMap is used in multi-threaded environment because both are therad-safe but main difference is on performance Hashtable's performance become poor if the size of Hashtable become large because it will be locked for long time during iteration but in case of concurrent HaspMap  only specific part is locked because concurrent HaspMap works on segmentation and other thread can access the element without iteration to complete. To learn more about how ConcurrentHashMap achieves it's thread-safety, scalability using lock stripping and non blocking algorithm, see this
article as well.


16) Which two methods you will override for an Object to be used as Key in HashMap?
Answer :
equals() and hashCode() methods needs to be override for an object to be used as key in HaspMap. In Map objects are stored as key and value.  put(key ,value) method is used to store objects in HashMap at this time hashCode() method is used to calculate the hash-code of key object and both key and value object is stored as map.entry.if two key objects have same hash-code then only value object is stored in that same bucket location but as a linked list value is stored and if hash code is different then another bucket location is created. While retrieving get(key) method is used at this time hash code of key object is calculated and then equals() method is called to compare value object. to learn more about how get() method of HashMap or Hashtable works, see that article.


17) Difference between wait and sleep in Java?
Answer:  Here are some important differences between wait and sleep in Java
  1. wait() method release the lock when thread is waiting but sleep() method hold the lock when thread is waiting.
  2. wait() is a instance method and sleep is a static method .
  3. wait method is always called from synchronized block or method but for sleep there is no such requirement.
  4. waiting thread can be awake by calling notify() and notifyAll() while sleeping thread can not be awaken by calling notify method.
  5. wait method is condition based while sleep() method doesn't require any condition. It is just used to put current thread on sleep.
  6. wait() is defined in java.lang.Object class while sleep() is defined in java.lang.Thread class


18) Difference between notify and notifyAll in Java?
Answer : main difference between notify and notifyAll is notify method will wake up  or notify only one thread and notifyall will notify all threads. If you are sure that more than one thread is waiting on monitor and you want all of them to give equal chance to compete for CPU, use notifyAll method. See
here more differences between notify vs notifyAll.


19) What is load factor of HashMap means?
Answer : HashMap's performance depends on two things first initial capacity and second load factor whenever we create HashMap initial capacity number of bucket is created initially and load factor is criteria to decide when we have to increase the size of HashMap when its about to get full.


20) Difference between PATH and Classpath in Java?
Answer : PATH is a environment variable in Java which is used to help Java program to compile and run.To set the PATH variable we have to include
JDK_HOME/bin directory in PATH environment variable and also we cannot override this variable. On the other hand,  ClassPath variable is used by class loader to locate and load compiled Java codes stored in .class file. We can set classpath we need to include all those directory where we have put either our .class file or JAR file which is required by your Java application,also we can override this environment variable.


21) Difference between extends Thread and implements Runnable in Java
This is the 21st frequently asked question in my list. You will see this question as first or second on multi-threading topic. One of the main point to put across while answering this question is Java's multiple inheritance support. You cannot more than one class, but you can implement more than one interface. If you extend Thread class just to override
run() method, you lose power of extending another class, while in case of Runnable, you can still implement another interface or another class. One more difference is that Thread is abstraction of independent path of execution, while Runnable is abstraction of independent task, which can be executed by any thread. That's why it's better to implement Runnable than extending Thread class in Java. If you like to dig more, see this answer.


That's all on this list of 20 most frequently asked Java interview questions and answers. By the way, this is not just the only list you got here, I have shared a lot of interview questions on topic wise e.g. you can find frequently asked questions from Thread, Collections, Strings and other important Java classes. Apart from coding questions, these fact based Java programming language questions are very important to do well on any interview. It's even more important for freshers and less experienced developer because they are usually asked these questions more frequently than experienced developers. By the way, you are most welcome to contribute in this list.



Top 25  Java Interview Questions :

1. Which two method you need to implement for key Object in HashMap ?
In order to use any object as Key in HashMap, it must implements equals and hashcode method in Java. Read How HashMap works in Java  for detailed explanation on how equals and hashcode method is used to put and get object from HashMap. 

2. What is immutable object? Can you write immutable object?
Immutable classes are Java classes whose objects can not be modified once created. Any modification in Immutable object result in new object. For example is String is immutable in Java. Mostly Immutable are also final in Java, in order to prevent sub class from overriding methods in Java which can compromise Immutability. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.

3. What is the difference between creating String as new() and literal?
When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.

String s = new String("Test");
 

does not  put the object in String pool , we need to call String.intern() method which is used to put  them into String pool explicitly. its only when you create String object as String literal e.g. String s = "Test" Java automatically put that into String pool.




Classic Java questions which some people thing tricky and some consider very easy. StringBuilder in Java is introduced in Java 5 and only difference between both of them is that Stringbuffer methods are synchronized while StringBuilder is non synchronized. See StringBuilder vs StringBuffer for more differences.

5.  Write code to find the First non repeated character in the String  ?
Another good Java interview question, This question is mainly asked by Amazon and equivalent companies. See first non repeated character in the string : Amazon interview question


6. What is the difference between ArrayList and Vector ?
This question is mostly used as a start up question in Technical interviews  on the topic of Collection framework . Answer is explained in detail here
Difference between ArrayList and Vector .


7. How do you handle error condition  while writing stored procedure or accessing stored procedure from java?
This is one of the tough Java interview question and its open for all, my friend didn't know the answer so he didn't mind telling me. my take is that stored procedure should return error code if some operation fails but if stored procedure itself fail than catching SQLException is only choice.

8. What is difference between Executor.submit() and Executer.execute() method ?
There is a difference when looking at exception handling. If your tasks throws an exception and if it was submitted with execute this exception will go to the uncaught exception handler (when you don't have provided one explicitly, the default one will just print the stack trace to System.err). If you submitted the task with submit any thrown exception, checked exception or not, is then part of the task's return status. For a task that was submitted with submit and that terminates with an exception, the Future.get will re-throw this exception, wrapped in an ExecutionException.


9. What is the difference between factory and abstract factory pattern?
Abstract Factory provides one more level of abstraction. Consider different factories each extended from an Abstract Factory and responsible for creation of different hierarchies of objects based on the type of factory. E.g. AbstractFactory extended by AutomobileFactory, UserFactory, RoleFactory etc. Each individual factory would be responsible for creation of objects in that genre.
You can also refer What is Factory method design pattern in Java to know more details.

10. What is Singleton? is it better to make whole method synchronized or only critical section synchronized ?
Singleton in Java is a class with just one instance in whole Java application, for example java.lang.Runtime is a Singleton class. Creating Singleton was tricky prior Java 4 but once Java 5 introduced Enum its very easy. see my article How to create thread-safe Singleton in Java for more details on writing Singleton using enum and double checked locking which is purpose of this Java interview question.


11. Can you write critical section code for singleton?
This core Java question is followup of previous question and expecting candidate to write Java singleton using double checked locking. Remember to use volatile variable to make Singleton thread-safe.

12. Can you write code for
iterating over hashmap in Java 4 and Java 5 ?
Tricky one but he managed to write using while and for loop.

13. When do you override hashcode and equals() ?
Whenever necessary especially if you want to do equality check or want to use your object as key in HashMap.

14. What will be the problem if you don't override hashcode() method ?
You will not be able to recover your object from hash Map if that is used as key in HashMap.
See here  
How HashMap works in Java for detailed explanation.

15. Is it better to synchronize critical section of getInstance() method or whole getInstance() method ?
Answer is critical section because if we lock whole method than every time some one call this method will have to wait even though we are not creating any object)

16. What is the difference when String is gets created using literal or new() operator ?
When we create string with new() its created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.

17. Does not overriding hashcode() method has any performance implication ?
This is a good question and open to all , as per my knowledge a poor hashcode function will result in frequent collision in HashMap which eventually increase time for adding an object into Hash Map.

18. What’s wrong using HashMap in multithreaded environment? When get() method go to infinite loop ?
Another good question. His answer was during concurrent access and re-sizing.

19.  What do you understand by thread-safety ? Why is it required ? And finally, how to achieve thread-safety in Java Applications ?


Java Memory Model defines the legal interaction of threads with the memory in a real computer system. In a way, it describes what behaviors are legal in multi-threaded code. It determines when a Thread can reliably see writes to variables made by other threads. It defines semantics for volatile, final & synchronized, that makes guarantee of visibility of memory operations across the Threads.

Let's first discuss about Memory Barrier which are the base for our further discussions. There are two type of memory barrier instructions in JMM - read barriers and write barrier.

A read barrier invalidates the local memory (cache, registers, etc) and then reads the contents from the main memory, so that changes made by other threads becomes visible to the current Thread.
A write barrier flushes out the contents of the processor's local memory to the main memory, so that changes made by the current Thread becomes visible to the other threads.
JMM semantics for synchronized
When a thread acquires monitor of an object, by entering into a synchronized block of code, it performs a read barrier (invalidates the local memory and reads from the heap instead). Similarly exiting from a synchronized block as part of releasing the associated monitor, it performs a write barrier (flushes changes to the main memory)
Thus modifications to a shared state using synchronized block by one Thread, is guaranteed to be visible to subsequent synchronized reads by other threads. This guarantee is provided by JMM in presence of synchronized code block.

JMM semantics for Volatile  fields
Read & write to volatile variables have same memory semantics as that of acquiring and releasing a monitor using synchronized code block. So the visibility of volatile field is guaranteed by the JMM. Moreover afterwards Java 1.5, volatile reads and writes are not reorderable with any other memory operations (volatile and non-volatile both). Thus when Thread A writes to a volatile variable V, and afterwards Thread B reads from variable V, any variable values that were visible to A at the time V was written are guaranteed now to be visible to B.

Let's try to understand the same using the following code

Data data = null;
volatile boolean flag = false;

Thread A
-------------
data = new Data();
flag = true;  <-- writing to volatile will flush data as well as flag to main memory

Thread B
-------------
if(flag==true){ <-- as="" barrier="" data.="" flag="" font="" for="" from="" perform="" read="" reading="" volatile="" well="" will="">
use data;  <!--- data is guaranteed to visible even though it is not declared volatile because of the JMM semantics of volatile flag.
}

20.  What will happen if you call return statement or System.exit on try or catch block ? will finally block execute?
This is a very popular tricky Java question and its tricky because many programmer think that finally block always executed. This question challenge that concept by putting return statement in try or catch block or calling System.exit from try or catch block. Answer of this tricky question in Java is that finally block will execute even if you put return statement in try block or catch block but finally block won't run if you call System.exit form try or catch.

19. Can you override private or static method in Java ?
Another popular Java tricky question, As I said method overriding is a good topic to ask trick questions in Java.  Anyway, you can not override private or static method in Java, if you create similar method with same return type and same method arguments that's called method hiding. 

20. What will happen if we put a key object in a HashMap which is already there ?
This tricky Java questions is part of How HashMap works in Java, which is also a popular topic to create confusing and tricky question in Java. well if you put the same key again than it will replace the old mapping because HashMap doesn't allow duplicate keys. 

21. If a method throws NullPointerException in super class, can we override it with a method which throws RuntimeException?
One more tricky Java questions from overloading and overriding concept. Answer is you can very well throw super class of RuntimeException in overridden method but you can not do same if its checked Exception. 

22. What is the issue with following implementation of compareTo() method in Java

public int compareTo(Object o){
   Employee emp = (Employee) emp;
   return this.id - o.id;
}


23. How do you ensure that N thread can access N resources without deadlock
If you are not well versed in writing multi-threading code then this is real tricky question for you. This Java question can be tricky even for experienced and senior programmer, who are not really exposed to deadlock and race conditions. Key point here is order, if you acquire resources in a particular order and release resources in reverse order you can prevent deadlock. 

24. What is difference between CyclicBarrier and CountDownLatch in Java
Relatively newer Java tricky question, only been introduced form Java 5. Main difference between both of them is that you can reuse CyclicBarrier even if Barrier is broken but you can not reuse CountDownLatch in Java. See CyclicBarrier vs CountDownLatch in Java for more differences.

25. Can you access non static variable in static context?
Another tricky Java question from Java fundamentals. No you can not access static variable in non static context in Java.

No comments:

Post a Comment