1) Advantages of making a class final and how do you create immutable class

Final and Immutable in Java

2) synchronized(list) ?Is this same as synchronized keyword ?

3) ConcurrentHashMap vs synchronized(hashMap

4) What’s the difference between StringStringBuffer and StringBuilder?

String is an immutable class. In older JDK’s the recommendation when programmatically building a String was to use StringBuffer since this was optimized to concatenate multiple Strings together. However, the methods on StringBuffer were marked as sychronized, which meant that there was a performance penalty, hence StringBuilder was introduced to provide a non-synchronized way to efficiently concatenate and modify Strings.

5) How do you run a Java application on the command line and set the classpath with multiple jars?

java -cp /dev/myapp.jar:/dev/mydependency.jar com.codinko.MyApp

6. What is the difference between finalfinalize and finally?

final is a Java keyword used to indicate that either a method can not override in a subclass, or a class can not be extended or a field can not be modified. finalize is a method that gets called on an instance of an Object when it is garbage collected. finally is a Java keyword used in exception handling to indicate a block of code that should always be run whether an exception is thrown or not.

7. How does Garbage Collection prevent a Java application from going out of memory?

Tricky Question. There is no relation actually!
Garbage Collection simply cleans up unused memory when an object goes out of scope and is no longer needed. However an application could create a huge number of large objects that causes an OutOfMemoryError.

8. What’s the difference between a ClassNotFoundException and NoClassDefFoundError?

A ClassNotFoundException means the class file for a requested class is not on the classpath of the application. A NoClassDefFoundErrormeans that the class file existed at runtime, but for some reason the class could not be turned into a Class definition. A common cause is an exception being thrown in static initialization blocks.

9. Given two double values d1d2, why isn’t it reliable to test their equality using  ==

d1 == d2

Because of Double.NaN (literally: “Not a Number”).

This code:

final double d1 = Double.NaN;
final double d2 = Double.NaN;

System.out.println(d1 == d2);

will print false.

The most accurate way to tell whether two double values are equal to one another is to use Double.compare() and test against 0, as in:

System.out.println(Double.compare(d1, d2) == 0);

10. What is the problem with this code: final byte[] bytes = someString.getBytes();

  • Problem is that the code relies on the default Charset of the JVM;
    default Charset cannot handle all characters.

For instance, in most Windows installations, the default charset is CP1252; but on Linux installations, the default charset will be UTF-8.

As such, such a simple string as “é” will give a different result for this operation depending on whether this code is run on Windows or Linux.

The solution is to always specify a Charset, as in, for instance:

final byte[] bytes = someString.getBytes(StandardCharsets.UTF_8);

11. What is the JIT?

The JIT is the JVM’s mechanism by which it can optimize code at runtime.

JIT means Just In Time. It is a central feature of any JVM.

The JIT is just part of the JVM. Other parts include the bytecode interpreter, the class loading verification and linking mechanisms, and the native code support for stuff like reflection, I/O and so on.

Java source code is compiled into class files, which contains bytecode. These byte codes are then executed by JVM. Since the execution of bytecode is slower than the execution of machine language code, because JVM first needs to translate bytecode into machine language code.
JIT helps JVM here by compiling  byte code into machine language. JIT also offers caching of compiled code which result in improved performance of JVM while running your program.


This code:

final double d = 1 / 2;


prints 0. Why? How do you make this code print 0.5 instead?

The problem here is that this expression:

1 / 2

has integer literals on both sides of the operator: 1 and 2. As a consequence, an integer division will be performed, and the result of 1 divided by 2 in an integer division is 0.

In order for the result to be a double as expected, at least one operand of the operation needs to be a double. For instance:

final double d = 1 / 2.0;


final double d = 1.0 / 2;

13. In this code:

IntStream.range(0, 10).forEach(System.out::println);

what is the inferred type of the method reference System.out::println?

It is an IntConsumer.

IntStream.range(0, 10) returns an IntStream, and IntStream defines a .forEach() method accepting an IntConsumer as an argument, whose prototype is:

void accept(int value);

System.out is a PrintStream, and a PrintStream has a method named println which takes an int as an argument and returns void. This matches the signature of an IntConsumer.

14. What is the problem with this code?

final Path path = Paths.get(...);


The problem is that the Stream returned by Files.lines() is not closed.

The operating design principle here is “whoever acquires the resource should release the resource”. Files don’t auto-close when you read to EOF; It is expected that  files to be closed explicitly by whoever opened them.

This should be used instead as the language provides a mechanism for automating this for you: try-with-resources. Because Stream implements AutoCloseable, you can do:

try (Stream<String> s = Files.lines(...)) {
try (
    final Stream<String> stream = Files.lines(path);
) {

Stream extends BaseStream, and BaseStream extends AutoCloseable. While this has no influence on streams you obtain from collections for instance, the stream returned by Files.lines() is I/O bound. Neglecting to close it correctly may lead to a resource leak in the event of an error occurring while processing the stream.

15.  Consider the following piece of code:

final List<Integer> list = new ArrayList<>();



What will be the contents of the list after this operation and why?

The contents will be:

[ 1, 2 ]

The reason is that there are two removal operations on a List:

  • remove(int index)
  • remove(Object obj)

The JVM will always select the most specific overload of a method; and here we pass an int as an argument, the code therefore removes the element at index 2.

To remove the _element_ 2 from the list, the following needs to be written:


16. Write a function to detect if two strings are anagrams (for example, SAVE and VASE)

This gauge a candidate’s

  • ability to understand a problem and write an algorithm to solve it.
  • ability to break down the problem to see what you need to check, what the edge cases are, and whether the code meets those criteria.

The naive solution is often to loop through the letters of the first string and see if they’re all in the second string.

One way to implement a better solution is comparing sorted strings:

public static boolean checkStrings(String s1, String s2) {
    char[] s1Chars = s1.toCharArray();
    char[] s2Chars = s2.toCharArray();
    return Arrays.equals(s1Chars, s2Chars);


17. What is the contract between equals and hashCode of an object?

The only obligation is that for any objects o1 and o2 then if o1.equals(o2) is true then o1.hashCode() == o2.hashCode() is true.

Note that this relationship goes only one way

18. Can an enum be extended?

No. Enum types are final by design.

19. How threadsafe is enum in Java?

Creation of an enum is guaranteed to be threadsafe. However, the methods on an enum type are not necessarily threadsafe

20. How does the JVM handle storing local variables vs storing objects?

Objects are stored on the heap. Variables are a reference to the object.

Local variables are stored on the stack.

21. Identify the problem in the below code:

public class Foo {
    public Foo() {

    public void doSomething() {
        System.out.println("do something acceptable");

public class Bar extends Foo {
    public void doSomething() {
        Zoom zoom = new Zoom(this);

Classic example for escaping references.

When an object of Bar is created, the super constructor in Foo gets called first, which in turn calls the ‘overridden’ doSomething method.
The doSomething method passes the this instance to the class ZoomZoom now can use the ‘this‘ instance before it is created entirely. BAD!!!

Reference: https://stackoverflow.com/questions/20474521/allowing-the-this-reference-to-escape

22. When do you use volatile variables?

When a member variable is accessed by multiple threads and want the value of a volatile field to be visible to all readers (other threads in particular) after a write operation completes on it.

23. Why do you need to use synchronized methods or blocks?

If threads are being used and a number of threads have to go through a synchronized section of code, only one of them may be executed at a time. This is used to make sure shared variables are not updated by multiple threads.

24. What is the difference between HashMap and ConcurrentHashMap?

ConcurrentHashMap is thread-safe; that is the code can be accessed by single thread at a time while HashMap is not thread-safe. ConcurrentHashMap does not allow NULL keys while HashMap allows it.

25. what is  Thread pool executors?


26. What is a good usecase of calling System.gc()

One may call System.gc() when profiling an application to search for possible memory leaks. All the profilers call this method just before taking a memory snapshot.

27. What is the marker interface in Java?
How are Annotations better than a Marker Interfaces?

The marker interface in Java is an interfaces with no field or methods. In other words, it an empty interface in java is called a marker interface. An example of a marker interface is a Serializable, Clonable and Remote interface. These are used to indicate something to the compiler or JVM.

Annotations lets one achieve the same purpose of conveying metadata about the class to its consumers without creating a separate type for it. Annotations are more powerful, too, letting programmers pass more sophisticated information to classes that “consume” it.

Unlike annotations, interfaces allow us to take advantage of polymorphism

Read : https://codinko.wordpress.com/2019/10/11/marker-interfaces-in-java/

28. What are checked and unchecked exceptions? When do you use them?

checked exception is an exception that must be catch, they are checked by the compiler. An unchecked exception is mostly runtime exception, and is not required to be catch. In general, use checked exception when the situation is recoverable (retry, display reasonable error message).

29. int a = 1L; won’t compile and int b = 0; b += 1L; compiles fine. Why ?

When += is used, that’s a compound statement and the compiler internally casts it. Whereas in the first case, the compiler straightaway shouts at you since it is a direct statement.

30. Why aren’t you allowed to extend more than one class in Java but are allowed to implement multiple interfaces?

Extending classes may cause ambiguity problems. On the other hand, in terms of interfaces, the single method implementation in one class can serve more than one interfaces.

31. Why doesn’t the following code generate a NullPointerException even when the instance is null?

Test t = null;

 public static void someMethod() {

There is no need for an instance while invoking a static member or method, since static members belongs to a class rather than an instance.

A null reference may be used to access a class (static) variable without causing an exception.


public class Test
    public static void main(String[] args)
        Integer a = 1000, b = 1000;
        System.out.println(a == b);

        Integer c = 100, d = 100;
        System.out.println(c == d);



Why is the code printing true in the second and false in the first case?

This question tests concept of JVM’s cache behavior.

The second output is true as we are comparing the references, because the JVM tries to save memory when the Integer falls within a range (from -128 to 127). At point 2, no new reference of type Integer is created for ‘d’. Instead of creating a new object for the Integer type reference variable ‘d’, it is only assigned with a previously created object referenced by ‘c’. All of these are done by JVM.

33. How do you reverse String("Java fun") without using Iteration and Recursion?

new StringBuilder(givenString).reverse());

34. when to use an ArrayList and when to use LinkedList.

ArrayList is preferred when there are more get(int), or when search operations need to be performed as every search operation runtime is O(1).

If an application requires more insert(int) and delete(int) operations, then LinkedList is preferred, as LinkedList does not need to maintain back and forth to preserve continued indices as arraylist does.

35. What is the difference between an Iterator and a ListIterator ?

These are collection iterators.

One can only use ListIterator to traverse Lists, and cannot traverse a Set using ListIterator.

You can  traverse in a forward direction using Iterators.
Using ListIterator, one can traverse a List in both the directions (forward and backward).

One cannot obtain indexes while using Iterator. Indexes can be obtained at any point of time while traversing a list using ListIterator. The methods nextIndex() and previousIndex() are used for this purpose.

36. What is the advantage of generic collection?

They enable stronger type checks at compile time.

A Java compiler applies strong type checking to generic code, and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.

37. when-to-use-linkedlist-over-arraylist-in-java

38. why-is-it-bad-practice-to-call-system-gc


-XX:DisableExplicitGC VM option.

39. how to clear a large hashmap after use to mark it enable for GC?

40. does-a-finally-block-always-get-executed-in-java

Yes, finally will be called after the execution of the try or catch code blocks.

The only times finally won’t be called are:

  1. If you invoke System.exit();
  2. If the JVM crashes first;
  3. If the JVM reaches an infinite loop (or some other non-interruptable, non-terminating statement) in the try or catch block;
  4. If the OS forcibly terminates the JVM process; e.g. “kill -9 ” on UNIX.
  5. If the host system dies; e.g. power failure, hardware error, OS panic, etcetera.
  6. If finally block is going to be executed by daemon thread and all other non daemon threads exit before finally is called.
  1. Garbage collection in Java- GC is automatic, yes.
    – why should you know about GC ?- Because  some practices related to GC may be subtle and so should be known and understood to avoid memory leak or undesirable behavior.
    For example :finalize()

is called by the garbage collector on an object when garbage collection determines that there are no more references to the object

according to the javadoc but in reality it could never be called.

Other example : GC collects remove the objects that are no referenced any longer but you could have a “heavy” object that is not any longer required but still referenced by a referenced object. So the heavy would not be elligible to be collected.
Using monitoring tools as JVisualVM shows sometimes some surprises and I say : Ah, this big object is still referenced here.

41. How do you iterate over values in hashmap


If you’re only interested in the keys, you can iterate through the keySet() of the map:

Map<String, Object> map = ...;

for (String key : map.keySet()) {
    // ...

If you only need the values, use values():

for (Object value : map.values()) {
    // ...

Finally, if you want both the key and value, use entrySet():

for (Map.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    // ...

One caveat: if you want to remove items mid-iteration, you’ll need to do so via an Iterator

public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
.remove(); // avoids a ConcurrentModificationException

42. Is Java “pass-by-reference” or “pass-by-value” ?


43.  Create ArrayList from Array

new ArrayList<>(Arrays.asList(array))

44. How to retrieve a value that is stored in an ArrayList, stored in a Hashmap.

Here’s what I have:

  1. HashMap<String, ArrayList<Record>> records = new HashMap<>();

    The key in this hashmap is not what I am looking for. There is a method inside of the Record object called getRecordId() and I want to be able to evaluate whether or not this recordId, through an if statement, exists in the ArrayList

Answer: try this though!

//List of keys which contains your desired Record at it's value(ArrayList)
List<String> requiredListOfKeys = records.keySet().stream()
                                                  .filter(x -> records.get(x)


records.entrySet().forEach(e -> {
    if (e.getValue().contains(recordId)) {
        // do something with 'e.getKey()'