Interview FAQJava

Best Core Java Interview Question and Answers

We have compiles a list of frequently asked questions during Java developer interviews. We have tried to cover all important topics here for the interview, Still if there is any core java interview question that have been asked to you, kindly post it in the ask question section we will include it here.

 

Core Java Interview Questions and Answers

 

Q1. How would you defensively copy a Date field in your immutable class?

 

 

Q2. What are the benefits of immutable objects?

In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created.  Benefits of Immutable objects:

  • Immutable classes are inherently thread-safe and you do not have to synchronize access to them to be used in a multi-threaded environment. So, there is no chance of negative performance consequences.
  • Eliminates the possibility of data becoming inaccessible when used as keys in HashMaps or as elements in

Read here why string is immutable in java.

Q3. What are the performance implications of Interfaces over abstract classes?

Basically, both interface methods and abstract methods make use of dynamic dispatching, so the difference is minimal. Even if there is any at all, Interfaces are slower in performance as compared to abstract classes as extra indirections are required for interfaces. The position of the method pointer in the dispatch vector would be static, while it is not for interface methods.

 

Q3. Can abstract class have constructors in Java?

Yes, abstract class can declare and define constructor in Java. Since you cannot create instance of abstract class, constructor can only be called during constructor chaining, i.e. when you create instance of concrete implementation class.

Now next follow-up question would be, What is the purpose of constructor, if you cannot instantiate abstract class? Well, it can still be used to initialize common variables, which are declared inside abstract class, and used by various implementation.

Also, even if you don’t provide any constructor, compiler will add default no argument constructor in an abstract class, without that your subclass will not compile.

 

Q4. Can abstract class implements interface in Java? does they require to implement all methods?

Yes, abstract class can implement interface by using implements keyword. Since they are abstract, they don’t need to implement all methods. It’s good practice to provide an abstract base class, along with an interface to declare Type. One example of this is java.util.List interface and corresponding java.util.AbstractList abstract class. Since AbstractList implements all common methods, concrete implementations like LinkedList and ArrayList are free from burden of implementing all methods, had they implemented List interface directly.

 

Q5. What are static initializers and when would you use them?

A static initializer gives you the opportunity to run code during the initial loading of a class and it guarantees that this code will only run once and will finish running before your class can be accessed in any way.

They are useful for performing initialization of complex static objects or to register a type with a static registry, as JDBC drivers do. Suppose you want to create a static, immutable Map containing some feature flags. Java doesn’t have a good one-liner for initializing maps, so you can use static initializers instead:

 

Q6. Can abstract class be final in Java?

No, abstract class cannot be final in Java. Making them final will stop abstract class from being extended, which is the only way to use abstract class. They are also opposite of each other, abstract keyword enforces to extend a class, for using it, on the other hand, final keyword prevents a class from being extended.

 

Q7. Can abstract class have static methods in Java?

Yes, abstract class can declare and define static methods, nothing prevents from doing that.

Q8. Can you create instance of abstract class?

No, you cannot create instance of abstract class in Java, as they are incomplete. Even though, if your abstract class don’t contain any abstract method, you cannot create instance of it. By making a class abstract, you told compiler that, it’s incomplete and should not be instantiated. Java compiler will throw error, when a code tries to instantiate abstract class.

 

Q9. Is it necessary for abstract class to have abstract method?

No, It’s not mandatory for an abstract class to have any abstract method. You can make a class abstract in Java, by just using abstract keyword in class declaration.

 

Q10. When do you favor abstract class over interface?

This is one of the favourite interview questions, if you know syntactical difference, you can answer this question quite easily.

Consider using interfaces if any of these statements apply to your situation:

  1. You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
  2. You want to specify the behaviour of a particular datatype, but not concerned about who implements its behaviour.
  3. You want to take advantage of multiple inheritances.

Consider using abstract classes if any of these statements apply to your situation:

  1. Use the abstract class if your sub-classes have is-a relationship with the abstract class.
  2. You want to share code among several closely related classes.
  3. If You expect that classes that extend your abstract class have many common methods or fields or require access modifiers other than public (such as protected and private).
  4. You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
  5. It’s better to use abstract class, when evolution is concern. Abstract class in Java evolves better than interface

 

Q11. Can abstract class contains main method in Java ?

Yes, abstract class can contain main method, it just another static method and you can execute Abstract class with main method, until you don’t create any instance.

 

Java Exception Interview Questions and Answers

Q12. What is Exception in Java?

An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions.

Error v/s Exception

Error: An Error indicates serious problem that a reasonable application should not try to catch. Error is not recoverable.
Exception: Exception indicates conditions that a reasonable application might try to catch. Exceptions can be handled in a program so that code runs gracefully.

 

Q13. What are the Exception Handling Keywords in Java?

There are four keywords used in java exception handling.

  1. throw: Sometimes we explicitly want to create exception object and then throw it to halt the normal processing of the program. throw keyword is used to throw exception to the runtime to handle it.
  2. throws: When we are throwing any checked exception in a method and not handling it, then we need to use throws keyword in method signature to let caller program know the exceptions that might be thrown by the method. The caller method might handle these exceptions or propagate it to its caller method using throws keyword. We can provide multiple exceptions in the throws clause.
  3. try-catch: We use try-catch block for exception handling in our code. try is the start of the block and catch is at the end of try block to handle the exceptions. We can have multiple catch blocks with a try and try-catch block can be nested also. catch block requires a parameter that should be of type Exception.
  4. finally: finally block is optional and can be used only with try-catch block. Since exception halts the process of execution, we might have some resources open that will not get closed, so we can use finally block. finally block gets executed always, whether exception occurs or not.

 

Q14. Explain Java Exception Hierarchy?

There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked exception. The sun microsystem says there are three types of exceptions.

  1. Errors: Errors are exceptional scenarios that are out of scope of application and it’s not possible to anticipate and recover from them, for example hardware failure, JVM crash or out of memory error.
  2. Checked Exceptions: Checked Exceptions are exceptional scenarios that we can anticipate in a program and try to recover from it, for example FileNotFoundException.
  3. Runtime Exceptions: Runtime Exceptions are caused by bad programming, for example trying to retrieve an element from the Array. We should check the length of array first before trying to retrieve the element otherwise it might throw ArrayIndexOutOfBoundException at runtime.

Q15. What is difference between Error, Checked and Unchecked Exception in Java?
  1. Checked Exception: The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.
  2. Unchecked Exception: The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
  3. Error: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

 

Q16. What is difference between throw and throws keyword in Java?

throw:
The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.

Syntax:

 

throws:
throws is a keyword in Java which is used in the signature of method to indicate that this method might throw one of the listed type exceptions. The caller to these methods must handle the exception using a try-catch block.

Syntax:

 

Important points to remember about throws keyword:

  • throws keyword is required only for checked exception and usage of throws keyword for unchecked exception is meaningless.
  • throws keyword is required only to convince compiler and usage of throws keyword does not prevent abnormal termination of program.
  • By the help of throws keyword we can provide information to the caller of the method about the exception.

 

Q17. How to write custom exception in Java?

We can extend Exception class or any of its sub-classes to create our custom exception class. The custom exception class can have its own variables and methods that we can use to pass error codes or other exception related information to the exception handler.

A simple example of custom exception is shown below.

 

Q18. What is OutOfMemoryError in Java?

OutOfMemoryError in Java is a subclass of java.lang.VirtualMachineError and its thrown by JVM when it rans out of heap memory. We can fix this error by providing more memory to run the java application through java JVM options.

 

Q19. What are different scenarios causing “Exception in thread main”?

Some of the common main thread exception scenarios are:

    • Exception in thread main java.lang.UnsupportedClassVersionError: This exception is thrown when your java class is compiled from another JDK version and you are trying to run it from another java version.
    • Exception in thread main java.lang.NoClassDefFoundError: There are two variants of this exception. The first one is where you provide the class full name with .class extension. The second scenario is when Class is not found.
    • Exception in thread main java.lang.NoSuchMethodError: main: This exception comes when you are trying to run a class that doesn’t have main method.
    • Exception in thread main java.lang.ArithmeticException: Whenever any exception is thrown from main method, it prints the exception is console. The first part explains that exception is thrown from main method, second part prints the exception class name and then after a colon, it prints the exception message.

 

Q20. What is difference between final, finally and finalize in Java?

final and finally are keywords in java whereas finalize is a method.

  1. final keyword can be used with class variables so that they can’t be reassigned, with class to avoid extending by classes and with methods to avoid overriding by subclasses.
  2. finally keyword is used with try-catch block to provide statements that will always gets executed even if some exception arises, usually finally is used to close resources.
  3. finalize() method is executed by Garbage Collector before the object is destroyed, it’s great way to make sure all the global resources are closed, but utmost care should be taken while using finalize() as it create severe performance penalty.

 

Out of the three, only finally is related to java exception handling.

 

Q21. What happens when exception is thrown by main method?

When exception is thrown by main() method, Java Runtime terminates the program and print the exception message and stack trace in system console.

Q22. Can we have an empty catch block?

We can have an empty catch block but it’s the example of worst programming. We should never have empty catch block because if the exception is caught by that block, we will have no information about the exception and it will be a nightmare to debug it. There should be at least a logging statement to log the exception details in console or log files.

 

Q23. Provide some Java Exception Handling Best Practices?

Some of the best practices related to Java Exception Handling are:

  1. Use Specific Exceptions for ease of debugging.
  2. Throw Exceptions Early (Fail-Fast) in the program.
  3. Catch Exceptions late in the program, let the caller handle the exception.
  4. Use Java 7 ARM feature to make sure resources are closed or use finally block to close them properly.
  5. Always log exception messages for debugging purposes.
  6. Use multi-catch block for cleaner close.
  7. Use custom exceptions to throw single type of exception from your application API.
  8. Follow naming convention, always end with Exception.
  9. Document the Exceptions Thrown by a method using @throws in javadoc.
  10. Exceptions are costly, so throw it only when it makes sense. Else you can catch them and provide null or empty response.

 

Q24. Why java uses concept of string literal?

To make Java more memory efficient (because no new objects are created if it already exists in string constant pool).

 

Multithreading, Concurrency, and Thread Basics

 

Q25. What is ThreadPool in Java?

A thread pool reuses previously created threads to execute current tasks and offers a solution to the problem of thread cycle overhead and resource thrashing. Since the thread is already existing when the request arrives, the delay introduced by thread creation is eliminated, making the application more responsive. Using worker threads minimizes the overhead due to thread creation. Thread objects use a significant amount of memory, and in a large-scale application, allocating and de-allocating many thread objects creates a significant memory management overhead.

Java provides the Executor framework which is centered around the Executor interface, its sub-interface –ExecutorService and the class-ThreadPoolExecutor, which implements both of these interfaces. By using the executor, one only has to implement the Runnable objects and send them to the executor to execute.

A simple way to create an executor that uses a fixed thread pool is to invoke the newFixedThreadPool factory method in java.util.concurrent.Executors This class also provides the following factory methods:

  • The newCachedThreadPool method creates an executor with an expandable thread pool. This executor is suitable for applications that launch many short-lived tasks.
  • The newSingleThreadExecutor method creates an executor that executes a single task at a time. Several factory methods are ScheduledExecutorService versions of the above executors.

 

Q26. What are Callable and Future in Java?

There are two ways of creating threads – one by extending the Thread class and other by creating a thread with a Runnable Interface. However, one feature lacking in Runnable is that we cannot make a thread return result when it terminates, i.e. when run() completes. For supporting this feature, the Callable interface comes in handy in Java.

Callable vs Runnable

  • For implementing Runnable, the run() method needs to be implemented which does not return anything, while for a Callable, the call() method needs to be implemented which returns a result on completion. Note that a thread can’t be created with a Callable, it can only be created with a Runnable.
  • Another difference is that the call() method can throw an exception whereas run() cannot.
  • Method signature that has to overridden for implementing Callable.

 

Future:
When the call() method completes, answer must be stored in an object known to the main thread, so that the main thread knows about the result that the thread returned.

How will the program store and obtain this result later? For this, a Future object can be used. Think of a Future as an object that holds the result – it may not hold it right now, but it will do so in the future (once the Callable returns). Thus, a Future is basically one way the main thread can keep track of the progress and result from other threads.

To read more on multithreading click here.

Q27. Is it possible to make array volatile in Java?

Yes, it is possible to make an array volatile in Java, but only the reference which is pointing to an array, not the whole array. Therefore, if one thread changes the reference variable points to another array, which will provide a volatile guarantee.

If the purpose is to provide memory visibility guarantee for individual indices of the array, volatile is of no practical use. Instead, you must rely on an alternative mechanism for thread-safety in that particular case, e.g. use of a synchronized keyword.

 

Q28. What is defined as false sharing in the context of multithreading?

False sharing is known to be one of the familiar performance issues on multi-core systems, whereby each process has a local cache. False sharing can be hard to identify since the thread may be retrieving completely different global variables that occur to be fairly close together in memory.

Similar to many other concurrency issues, the main way to avoid false sharing is to carefully review your code and supporting your data structure with the size of a cache line.

Read more about thread safety in java.

Q29. How do you take thread dump in Java?

By using kill -3 PID in Linux, where PID is the process id of Java process, you can take a thread dump of Java application.

In Windows, you can press Ctrl + Break. This will instruct JVM to print thread dump in standard out, and it may go to console or log file depending on your application configuration.

 

Q30. Describe what are thread-local variable is in Java?

Thread-local variables are variables restricted to a thread. It is like thread’s own copy which is not shared between a multitude of threads. Java offers a ThreadLocal class to upkeep thread-local variables. This is one of the many ways to guarantee thread-safety.

Any thread local variable which is not taken away once its work is done can hypothetically cause a memory leak in Java application.

 

Q31. What is the difference between sleep and wait in Java?

Both are used to pause thread that is currently running, however, sleep() is meant for short pause because it does not release lock, while wait() is meant for conditional wait.

Because of which it releases lock, which can then be developed by a different thread to alter the condition of which it is waiting.

 

Q32. What is immutable object? How would you create an immutable object in Java?

Immutable objects are defined as objects whose state cannot be changed once it has been made, any alteration will result in a new object, e.g. String, Integer, and other wrapper class.

To create immutable class in java, please follow below steps.

  • Declare the class as final so it can’t be extended.
  • Make all fields private so that direct access is not allowed.
  • Don’t provide setter methods for variables
  • Make all mutable fields final so that it’s value can be assigned only once.
  • Initialize all the fields via a constructor performing deep copy.
  • Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.
  • The “this” reference is not allowed to escape during construction from the immutable class and the immutable

 

Example of immutable object in java – String

Q33. What’s the difference between Callable and Runnable?

Both are interfaces used to carry out task to be executed by a thread. The main difference between the two interfaces is that Callable can return a value, while Runnable cannot. Another difference is that Callable can throw a checked exception, while Runnable cannot. Runnable has been around since Java 1.0, while Callable was introduced as part of Java 1.5.

 

Q34. What do the Thread.class methods run() and start() do?

Thread.run() will execute in the calling thread, i.e. a new thread is not created, and the code is executed synchronously.

Thread.start() will execute the same code, but in a new asynchronous thread.

 

Data Types and Data-structures questions

Q35. What are linear and non-linear data Structures?
  • Linear: A data structure is said to be linear if its elements form a sequence or a linear list. Examples: Array, LinkedList, Stacks and Queues
  • Non-Linear: A data structure is said to be non-linear if traversal of nodes is nonlinear in nature. Example: Graph and Trees.

 

Q36. How is an Array different from Linked List?
  • The size of the arrays is fixed, Linked Lists are Dynamic in size.
  • Inserting and deleting a new element in an array of elements is expensive, whereas both insertion and deletion can easily be done in Linked Lists.
  • Random access is not allowed in LinkedList, but is allowed in array.
  • Extra memory space for a pointer is required with each element of the Linked list.
  • Arrays have better cache locality that can make a pretty big difference in performance.

 

Q37. What is Stack and where it can be used?

A stack is a container of objects that are inserted and removed according to the last-in first-out (LIFO) principle. In the pushdown stacks only two operations are allowed: push the item into the stack, and pop the item out of the stack. A stack is a limited access data structure – elements can be added and removed from the stack only at the top. push adds an item to the top of the stack, pop removes the item from the top.

A helpful analogy is to think of a stack of books; you can remove only the top book, also you can add a new book on the top.

 

Q38. What is a Queue, how it is different from stack and how is it implemented?

A queue is a container of objects (a linear collection) that are inserted and removed according to the first-in first-out (FIFO) principle. An excellent example of a queue is a line of students in the food court of the School. New additions to a line made to the back of the queue, while removal (or serving) happens in the front.

In the queue only two operations are allowed enqueue and dequeue. Enqueue means to insert an item into the back of the queue, dequeue means removing the front item. The picture demonstrates the FIFO access.

The difference between stacks and queues is in removing. In a stack we remove the item the most recently added; in a queue, we remove the item the least recently added.

 

Q39. Which data structures are used for BFS and DFS of a graph?
  • Queue is used for BFS
  • Stack is used for DFS. DFS can also be implemented using recursion (Note that recursion also uses function call stack in stack memory).

 

Q40. How do you reference all the elements in a one-dimension array?

To reference all the elements in a one -dimension array, you need to use an indexed loop, So that, the counter runs from 0 to the array size minus one. In this manner, You can reference all the elements in sequence by using the loop counter as the array subscript.

 

Q41. Which data structures are applied when dealing with a recursive function?

Recursion, is a function that calls itself based on a terminating or base condition, it makes use of the stack. Using LIFO, a call to a recursive function saves the return address so that it knows how to return to the calling function after the call terminates.

 

Q42. Differentiate NULL and VOID?

Null is a value, whereas Void is a data type identifier. A variable that is given a Null value indicates an empty value. The void is used to identify pointers as having no initial size. Also void is used in method signature when method does not return anything.

 

Q43. What is the primary advantage of a linked list?

List of advantages of Linked List are:

  1. Linked List is Dynamic data Structure.
  2. Linked List can grow and shrink during run time.
  3. Insertion and Deletion Operations are Easier
  4. Efficient Memory Utilization, i.e no need to pre-allocate memory
  5. Faster Access time, can be expanded in constant time without memory overhead
  6. Linear Data Structures such as Stack, Queue can be easily implemented using LinkedList

 

Q44. How does variable declaration affect memory allocation?

Memory is allocated upon variable declaration, for primitive, pointers, structs, objects, reference types, etc. The amount of memory to be allocated or reserved depends on the data type of the variable being declared. For example, if a variable is declared to be of int type 4 bits and if long then 8 bytes of memory will be allocated.

 

Q45. What is the advantage of the heap over a stack?
  • The heap is more flexible than the stack. That’s because memory space for the heap can be dynamically allocated and de-allocated as needed. However, memory of the heap can at times be slower when compared to that stack.
  • Stack memory allocation is very fast, and guaranteed to be immediately available if the function is invoked successfully.
  • Heap allocation requires OS to allocate from a special memory place and the programmer needs to maintain the memory as well. Not fast, but durable across function calls
  • Book-keeping – stack memory doesn’t have to be “managed”, unlike dynamic memory which has to be manually allocated and deallocated.

 

Q46. Which one will take more memory: an int or Integer?

An Integer object will take more memory as it stores metadata overhead about the object. An int is primitive, therefore it takes less space.

 

Q47. How is the transient keyword used in Java?

The transient keyword is used to indicate that a field in class should not be serialized (used with the Serializable interface)

More about SerialVersion.

 

JVM Internals and Garbage Collection Interview Questions

Q48. What is the size of int in 64-bit JVM?

The size of an int variable is constant in Java, it is always 32-bit regardless of platform. This means the size of primitive int is identical in both 32-bit and 64-bit Java Virtual Machine.

 

Q49. How does WeakHashMap work?

WeakHashMap is an implementation of the Map interface. WeakHashMap is almost same as HashMap except in case of WeakHashMap, if object is specified as key doesn’t contain any references- it is eligible for garbage collection even though it is associated with WeakHashMap. i.e Garbage Collector dominates over WeakHashMap.

This class is intended primarily for use with key objects whose equals methods test for object identity using the == operator. Once such a key is discarded it can never be recreated, so it is impossible to do a lookup of that key in a WeakHashMap at some later time and be surprised that its entry has been removed.

 

Q50. What is the maximum heap size of 32-bit and 64-bit JVM?

In theory, the maximum heap memory you can assign to a 32-bit JVM is 2^32, which is 4GB, but practically the bounds are much smaller.

It also depends on operating systems, e.g. from 1.5GB in Windows to almost 3GB in Solaris. 64-bit JVM allows you to stipulate larger heap size, hypothetically 2^64, which is quite large but practically you can specify heap space up to 100GBs.

 

Q51. Can you guarantee the garbage collection process?

No, the garbage collection cannot be guaranteed, though you can make a request using System.gc() or Runtime.gc() method to request for Garbage collection but its not guaranteed.

 

Java Collections Framework Interview Questions

Q52. What is an Iterator?

Iterator interface provides methods to iterate over any Collection. We can get iterator instance from a Collection using iterator() method. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying collection during the iteration. Java Collection iterator provides a generic way for traversal through the elements of a collection and implements Iterator Design Pattern.

 

Q53. What is difference between Enumeration and Iterator interface?

Enumeration Vs Iterator in java:

Enumeration Iterator
Using Enumeration, you can only traverse the collection. You can’t do any modifications to collection while traversing it. Using Iterator, you can remove an element of the collection while traversing it.
Enumeration is introduced in JDK 1.0 Iterator is introduced from JDK 1.2
Enumeration is used to traverse the legacy classes like VectorStack and HashTable. Iterator is used to iterate most of the classes in the collection framework like ArrayListHashSetHashMapLinkedList etc.
Available Methods : hasMoreElements() and nextElement() Available Methods : hasNext()next() and remove()
Enumeration is fail-safe in nature. Iterator is fail-fast in nature.
Enumeration is not safe and secured due to it’s fail-safe nature. Iterator is safer and secured than Enumeration.

 

 

Q54. What do you understand by iterator fail-fast property?

Iterator fail-fast property checks for any modification in the structure of the underlying collection every time we try to get the next element. Iterators from java.util package throw ConcurrentModificationException if collection was modified by collection’s methods (add / remove) while iterating

Example:

 

 

Q55. What is difference between fail-fast and fail-safe?

Fail-safe:
These iterators make a copy of the internal collection (object array) and iterates over the copied collection. Any structural modification done to the iterator affects the copied collection, not original collection. So, original collection remains structurally unchanged.

  • Fail-safe iterators allow modifications of a collection while iterating over it.
  • These iterators don’t throw any Exception if a collection is modified while iterating over it.
  • They use copy of original collection to traverse over the elements of the collection.
  • These iterators require extra memory for cloning of collection. Ex : ConcurrentHashMap, CopyOnWriteArrayList

Fail-Fast:
Iterator fail-fast property checks for any modification in the structure of the underlying collection every time we try to get the next element. Iterators from java.util package throw ConcurrentModificationException if collection was modified by collection’s methods (add / remove) while iterating

  • These iterators throw ConcurrentModificationException if a collection is modified while iterating over it.
  • They use original collection to traverse over the elements of the collection.
  • These iterators don’t require extra memory.
  • Ex : Iterators returned by ArrayList, Vector, HashMap.

 

Q56. What is the importance of hashCode() and equals() methods?

HashMap uses Key object hashCode() and equals() method to determine the index to put the key-value pair. These methods are also used when we try to get value from HashMap. If these methods are not implemented correctly, two different Key’s might produce same hashCode() and equals() output and in that case rather than storing it at different location, HashMap will consider them same and overwrite them.

Similarly all the collection classes that doesn’t store duplicate data use hashCode() and equals() to find duplicates, so it’s very important to implement them correctly. The implementation of equals() and hashCode() should follow these rules.

  • If o1.equals(o2), then o1.hashCode() == o2.hashCode()should always be true.
  • If o1.hashCode() == o2.hashCode is true, it doesn’t mean that o1.equals(o2) will be true.

The general contract of hashCode is:

  • During the execution of the application, if hashCode() is invoked more than once on the same Object then it must consistently return the same Integer value, provided no information used in equals(Object) comparison on the Object is modified. It is not necessary that this Integer value to be remained same from one execution of the application to another execution of the same application.
  • If two Objects are equal, according to the the equals(Object) method, then hashCode() method must produce the same Integer on each of the two Objects.
  • If two Objects are unequal, according to the the equals(Object) method, It is not necessary the Integer value produced by hashCode() method on each of the two Objects will be distinct. It can be same but producing the distinct Integer on each of the two Objects is better for improving the performance of hashing based Collections like HashMap, HashTable…etc.

 

Q57. Can we use any class as Map key?

We can use any class as Map Key, however following points should be considered before using them.

  • If the class overrides equals() method, it should also override hashCode() method.
  • The class should follow the rules associated with equals() and hashCode() for all instances.
  • If 2 objects are equal, then their hashCode values must be equal as well.
  • If a field is not used in equals(), then it must not be used in hashCode().
  • If it is accessed often, hashCode() is a candidate for caching to enhance performance.
  • It is a best practice to implement the user defined key class as an immutable object.

 

Q58. What is BlockingQueue?

java.util.concurrent.BlockingQueue is a Queue that supports operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.

BlockingQueue interface is part of java collections framework. Java provides several BlockingQueue implementations such as ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue etc.

Read more about Priority Queue here.

Q59. How can we sort a list of Objects?

If we need to sort an array of Objects, we can use Arrays.sort(). If we need to sort a list of objects, we can use Collections.sort(). Both these classes have overloaded sort() methods for natural sorting (using Comparable) or sorting based on criteria (using Comparator).

Collections internally uses Arrays sorting method, so both of them have same performance except that Collections take some time to convert list to array. If you want your own sorting sequence then can override Comparable or Comparator interface methods.

 

Q60. What is the purpose of the initial capacity and load factor parameters of a HashMap? What are their default values?

The initial capacity argument of the HashMap constructor affects the size of the internal data structure of the HashMap. The HashMap‘s internal data structure is an array with the power-of-two size. So the initial capacity argument value is increased to the next power-of-two (for instance, if you set it to 10, the actual size of the internal array will be 16).

The load factor of a HashMap is the ratio of the element count divided by the bucket count (i.e. internal array size). For instance, if a 16-bucket HashMap contains 12 elements, its load factor is 12/16 = 0.75. A high load factor means a lot of collisions, which in turn means that the map should be resized to the next power of two. When the map achieves this load factor, it resizes its internal array to the next power-of-two value.

The initial capacity is 16 by default, and the loadFactor is 0.75 by default, so you could put 12 elements in a HashMap that was instantiated with the default constructor, and it would not resize.

Read Internal working and performance of HashMap.

Q61. What is the difference between poll() and remove() method of Queue interface?

Though both poll() and remove() method from Queue is used to remove the object and returns the head of the queue, there is a subtle difference between them. If Queue is empty() then a call to remove() method will throw Exception, while a call to poll() method returns null.

By the way, exactly which element is removed from the queue depends upon queue’s ordering policy and varies between different implementation, for example, PriorityQueue keeps the lowest element as per Comparator or Comparable at head position.

 

Q62. When does ConcurrentModificationException occur on iteration?

When you try to remove object using Collection’s or List’s remove method e.g. remove(Object element) or remove(int index), instead of Iterator’s remove() method than ConcurrentModificationException occurs. As per Iterator’s contract, if it detect any structural change in Collection e.g. adding or removing of the element, once Iterator begins, it can throw ConcurrentModificationException.

To Avoid ConcurrentModificationException in multi-threaded environment:

  • You can convert the list to an array and then iterate on the array. This approach works well for small or medium size list but if the list is large then it will affect the performance a lot.
  • You can lock the list while iterating by putting it in a synchronized block. This approach is not recommended because it will cease the benefits of multithreading.
  • If you are using JDK1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList classes. This is the recommended approach to avoid concurrent modification exception.

 

Java Best Practices Interview Questions

Q63. How do you avoid NullPointerException, while comparing two Strings in Java?

When compared to null, equals return false and doesn’t throw NullPointerException, you can use this property to avoid NPE while comparing String. Suppose you have a known String “abc” and you are comparing with an unknown String variable str, then you should call equals as “abc”.equals(str), this will not throw Exception in thread Main: java.lang.NullPointerException, even if str is null.

On the other hand if you call str.equals(“abc”), it will throw NPE. So be careful with this. By the way this is one of the Java coding best practices, which Java developer should follow, while using equals() method.

 

Q64. How would you defensively copy a Date field in your immutable class?

 

 

Q65. Prefer returning Empty Collections instead of Null?

If a program is returning a collection which does not have any value, make sure an Empty collection is returned rather than Null elements. This saves a lot of “if else” testing on Null Elements.

 

Q66. Use Strings carefully?

If two Strings are concatenated using “+” operator in a “for” loop, then it creates a new String Object, every time. This causes wastage of memory and increases performance time. If your string has lot of concatenation then its better to use StringBuilder if not multithreaded else use StringBuffer if multithreaded.

Also, while instantiating a String Object, constructors should be avoided and instantiation should happen directly. For example:

 

 

Q67. Avoid unnecessary Objects?

One of the most expensive operations (in terms of Memory Utilization) in Java is Object Creation. Thus it is recommended that Objects should only be created or initialized if necessary. Following code gives an example:

 

 

Q68. Dilemma between array and ArrayList?

Developers often find it difficult to decide if they should go for array type data structure of ArrayList type. They both have their strengths and weaknesses. The choice really depends on the requirements. If you know the size of the array upfront and performance is utmost importance then array is best choice. Since the size of Array is fixed, the memory gets allocated at the time of declaration of Array type variable.

Hence, Arrays are very fast. And if size is unknown then ArrayList is best choice as you don’t have to worry about managing the size of array. Also when lot of modifications are the requirement then ArrayList is better as It is much easier to Add or Remove elements from ArrayList than Array.

  • Array can contain both primitive data types as well as objects of a class depending on the definition of the array. However, ArrayList only supports object entries, not the primitive data types.
  • Since ArrayList can’t be created for primitive data types, members of ArrayList are always references to objects at different memory locations, Therefore in ArrayList, the actual objects are never stored at contiguous locations. References of the actual objects are stored at contiguous locations.

 

Q69. Avoiding Memory leaks by simple tricks?

Memory leaks often cause performance degradation of software. Since, Java manages memory automatically, the developers do not have much control. But there are still some standard practices which can be used to protect from memory leakages.

  • Always release database connections when querying is complete.
  • Use Finally block to release and close all connection and file operations etc.
  • Release instances stored in Static Tables.
  • Avoid unused variables in class.

 

Q70. What best practices should you follow while writing multithreaded code in Java?

When writing code for multithreaded environment in Java, the following are some best practices to be followed:

  • Always name your thread as this help in debugging.
  • Minimise the scope of your of synchronization. Rather than making the whole method synchronized, be mindful that only the critical section should be synchronized.
  • Opt for volatile over synchronisation if you have the option to.
  • Use a higher level of concurrency utilities instead of wait() and notify() for inter-thread communication, e.g. BlockingQueue, CountDownLatch and Semaphore.
  • Opt for concurrent collection over synchronized collection in Java as this will provide better scalability.

 

Q71. Explain some best practices you would apply while using Collection in Java?

When using Collection classes in Java, the following are some best practices to be mindful of:

  • Ensure you are using the right collection, e.g. if you need a non-synchronised list, then opt for ArrayList and not Vector.
  • Opt for concurrent collection over a synchronised collection because they are more scalable.
  • Ensure you are using interface to represent and access a collection e.g. use List to store ArrayList, Map to store HashMap. Example : Map<String, String> map = new HashMap<>();
  • Use iterator to loop over collection.
  • Always use generics with collection.
  • Always return empty collection from method rather than null. It helps in avoiding many null checks.

 

Unit Testing JUnit Interview Questions

Q72. Explain what is JUnit?

JUnit is a testing framework for unit testing of Java code.  It uses Java as a programming platform, and it is an Open Source Software managed by the JUnit.org community.

 

Q73. Explain what is Unit Test Case?

Unit Test Case is a part of the code that ensures that another part of code behaves as expected. For each requirement, there must be at least two test cases one negative test and one positive test. Test case should cover all lines of code in a method.

 

Q74. Mention different methods of exception handling in JUnit?

There are different methods of exception handling in JUnit

  • Try catch idiom
  • With JUnit rule
  • With @Test annotation
  • Using catch exception library
  • Using customs annotation

 

Q75. Explain what is ignore test in JUnit?

When your code is not ready, and it would fail if executed then you can use @Ignore annotation.

  • It will not execute a test method annotated with @Ignore
  • It will not execute any of the test methods of test class if it is annotated with @Ignore

 

Q76. Write a sample unit test case for a method that throws IndexOutOfBoundsException when working with ArrayList?

 

Q77. Write a sample unit testing method for testing timeout?

 

 

Q78. What are called as test smells in relation with unit testing?

Following could be termed as test smells: Multiple assertions within one unit test, long-running unit tests etc

 

Q79. What are the core features of JUnit?

JUnit test framework provides following important features −

  • Fixtures: Fixture is a fixed state of a set of objects used as a baseline for running tests. The purpose of a test fixture is to ensure that there is a well known and fixed environment in which tests are run so that results are repeatable. It includes following methods −
    1. setUp() method which runs before every test invocation.
    2. tearDown() method which runs after every test method.
  • Test suites : Test suite means bundle a few unit test cases and run it together. In JUnit, both @RunWith and @Suite annotation are used to run the suite test.
  • Test runners: Test runner is used for executing the test cases.
  • JUnit classes: JUnit classes are important classes which are used in writing and testing JUnits. Some of the important classes are −
    1. Assert − It contains a set of assert methods.
    2. TestCase − It contains a test case defines the fixture to run multiple tests.
    3. TestResult − It contains methods to collect the results of executing a test case.
    4. TestSuite − It is a Composite of Tests.

 

 

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.