Java Interview Questions
Currently there are many articles online which summarize the list of Java interview questions. Some cover lots of basic questions and some cover some specific questions in specific area such as multithreading. In this post, we will not cover the really basic questions, we will cover something different. For basic question, you can read Java Interview Questions。
What is primitive data type? How many primitive data types in Java? What are they?-- A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values.
-- There are 8 primitive data types in Java. They are boolean, byte, char, short, int, long, float, double.
What is value of b in byte b = (byte)-256? What is the casting process?-- b will be 0. Here -256 will be first casted to an int type(because the smallest data unit in Java is 32 bits) then it will be downcasted to a byte. When downcasting, the first three bytes are dropped and only the last byte will be the value of b.
What is difference between StringBuffer and StringBuilder?-- StringBuffer is introduced in Java 1.0 while StringBuilder is introduced in Java 1.5
-- StringBuffer is thread-safe
-- StringBuilder is faster given no synchronization is performed
What are diffeernt throwable types?-- UncheckedException, CheckedException and Error
-- UncheckedExceptions including RuntimeException, Error and their subclasses. For example, ArrayIndexOutOfBoundsException, DivideByZeroException, ArithmaticException
-- CheckedExceptions are others and they have to be caught explicitly
Why does Java 8 introduce default method to interface?-- It's because Java 8 introduces some other features including lambda and stream API. To utilize this features, some exiting APIs including Collections need to be updated to add more methods. But given the characteristic of interface, if we add a method to the interface, the classes which implement this interface have to implement the method as well. This enforce developers to update their existing code to implement the new methods. So to be backward compatible, default method is introduced to provide default behavior to these interfaces. All classes implement the interface are welcome to override the default method as they want but it's NOT compulsory anymore.
What is the difference between interface with default method and abstract class?-- Interface is designed to provide interface to external users without knowing the exact implementation of the interface
-- Default method is to add additional functions the interface and mainly for backward compatibility
-- Abstract class is class defined to be extended, it can have state and constructor
-- A class can implement multiple interfaces while a class can only extend one abstract class
What if a class implements two interface with the same default method?-- A compilation error will occur if the class implementing these interface doesn't implement this method itself. It's because the compiler doesn't know which method to use.
What is the difference between Enumeration and Iterator?-- Both Enumeration and Iterator provide method to traverse a Collection without knowing the detailed data structured in implemented in the Collection.
-- Iterator provides more functionality than Enumeration and its is to replace the Enumeration. The detailed difference can be found at Difference between Enumeration and Iterator in java interview question and answer.
Will String.length() and String.getBytes().length return the same value always?-- No. String.length() returns the number of characters in the string while String.getBytes().length return the number of bytes to represent the string. Since character in Java represents two bytes if the string is encoded with URF-16, then String.getBytes().length will be 2x of String.length(). If it's UTF-8, then the two values will not be equal if the string
contains non-ASCII character. For details, please refer to String.length() vs String.getBytes().length in Java
What are differences between Hashtable and HashMap?-- Hashtable is thread-safe while HashMap is not thread-safe
-- Hashtable doesn't allow null keys and null values, while HashMap allows one null key and any number of null values
Why hashCode) needs to be overriden when equals() is overriden?According to Java documentation on hashCode(), the general contracts about hashCode() are :
* 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.And by default, the hashCode() method from Object will return an integer value converted from the internal address of the object. Each object will have a different internal address, hence the hashCode() will return different value. To ensure the hashCode() returns the same value if equals() returns true, the hashCode() needs to be overriden. The hashCode() value will be used in HashMap and Hashtable.
* 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 unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
What does String.intern() do?-- When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. It is frequently used to compare two String objects created by new String(). Details can be found at String intern in Java.
ConcurrentHashMap vs Collections.synchronizedMap()?-- Refer to ConcurrentHashMap vs Collections.synchronizedMap().
When will a ConcurrentModificationException happen?-- A ConcurrentModificationException will happen if an iterator of a collection is being traversed while at the time the collection is being modified. For example, if you are looping through an iterator of a set and at the time you try to remove or add element to the set.
Why do we need to be cautious when using ThreadLocal?-- The object reference by a ThreadLocal belongs to the thread, i.e, the object will be referenced as long as the thread is not terminated. This will pose a potential memory issue if multiple threads are reused such as in a web container. Read Use Java ThreadLocal with caution
When will a lock happen? When will a deadlock happen?-- A lock will happen when a resource is to be accessed by two or more threads and is currently accessed by one thread.
-- In simple, a deadlock will happen when one thread is locking some resource A and waiting for some resource B, while at the same time another thread is locking resource B and waiting for resource A.
What is difference between Thread.start() and Thread.run()?-- Thread.start() will first call system API to start a new thread and then call the Thread.run() method to run the tasks in the thread. It will create a new AccessControlContext and Stack for the thread.
-- Thread.run() will execute the tasks in Thread but it will not create a new thread. Instead it will execute the tasks in the same thread whee this method is called. Do not call this method manually. Always call Thread.start().
What are different reference types in Java?-- StrongReference, SoftReference, WeakReference and PhantomReference
What is the difference between SoftReference and WeakReference?-- SoftReference will be GCed only when memory usage is high and an OOM error is about to occur
-- WeakReference will be GCed when the GC starts to recycle the memory
When is the difference between NoClassDefFoundError and ClassNotFoundException?-- NoClassDefFoundError means that the class was present during compile time but cannot be found during runtime. This may be caused because the class is removed during runtime or the class is loaded by different class loaders or there is some exceptions happening during previous loading
-- ClassNotFoundException means the class is not found while the class is dynamically loaded. For example while calling Class.forName("someClass"). The someClass is not there.
-- Since NoClassDefFoundError is an Error, so need to catch Throwable when trying to handle the error instead of catching Exception.
What is AbstractMethodError and when it will occur?-- AbstractMethodError is a kind of runtime error where the application is having some incompatible changes which leads to a missing implementation of an abstract method.
-- It happens when some implementation has changed which violates the abstract method definition. It is frequently seen during application upgrade where the interface is defined in one jar while the implementation is implemented in another jar and the two jars are not upgraded together. For a detailed demonstration, refer to Java AbstractMethodError explained and demonstrated
The list is being updated continuously.