20+ Core Java Interview Questions for experienced Professionals from Investment Banks
Tags: java, career, beginners, programming
Published: 2019-06-13 15:38:18

---
title: 20+ Core Java Interview Questions for experienced Professionals from Investment Banks
published: true
description: Some of the most frequently asked core Java interview questions from investment banks like Barclays, Credit Suisse, Citibank, Nomura, etc
tags: java,career,beginners,programming
---
*Disclosure: This post includes affiliate links; I may receive compensation if you purchase products or services from the different links provided in this article.*

There are a lot of [Java developers](https://javarevisited.blogspot.com/2018/05/10-tips-to-become-better-java-developer.html) trying for Java development role on Investment banks like Barclays, Credit Suisse, Citibank, etc, but many of them don't have any idea of what kind of interview questions they can expect there.

In this article, I'll share some of the most frequently asked [core Java questions](https://javarevisited.blogspot.com/2015/10/133-java-interview-questions-answers-from-last-5-years.html) from investment banks to Java programmers with more than 3 years of experience.

Disclosure: This post includes affiliate links; I may receive compensation if you purchase products or services from the different links provided in this article.

Yes, these questions are not for [beginners](http://www.java67.com/2018/03/20-Java-Interview-Questions-Answers-freshers-1-2-3-YearsExperienced-Programmers.html) or [1 to 2 years of Java](https://javarevisited.blogspot.com/2018/07/top-30-java-phone-interview-questions.html#axzz5N70xIF15) experienced professional as often banks don't hire them via open interviews, they mostly join as graduate trainees, but they can also learn a lot by just going through questions and understanding answers and concepts behind them. 

**It's not guaranteed that you will get these questions**, in fact, most likely you won't, but this will give you some idea of what kind of questions you can expect. The more you prepare the better your interview will be.

If you think these 21 core java questions are not enough and you need more than check out these additional [**40 Java questions**](http://www.java67.com/2015/03/top-40-core-java-interview-questions-answers-telephonic-round.html) for the telephonic interview and these [**200+ Java questions**](http://bit.ly/2CupaSL)from last 5 years as well.

Once you have done those, you would be more confident to given any Java interview, be it a phone interview or face-to-face.



## Frequently asked Core Java Interview Questions from Investment Banks
Anyway, without wasting any more of your time, let's dive into some of the common Java interview questions from banks, which I have collected from some of my friends and colleagues who appeared in interviews of these banks.

**Question 1. Does not overriding hashCode() method has any performance implication?** ([answer](http://java67.blogspot.com/2013/04/example-of-overriding-equals-hashcode-compareTo-java-method.html "Click to open in a new window"))\
This is a good question and opens to all, as per my knowledge, a poor hash code function will result in the [frequent collision in HashMap](http://javarevisited.blogspot.sg/2016/01/how-does-java-hashmap-or-linkedhahsmap-handles.html) which eventually increases the time for adding an object into Hash Map.

From [Java 8](https://javarevisited.blogspot.com/2018/08/top-5-java-8-courses-to-learn-online.html) onwards through collision will not impact performance as much as it does in earlier versions because after a threshold the [linked list](http://javarevisited.blogspot.sg/2017/07/top-10-linked-list-coding-questions-and.html#axzz4xXS86IVo) will be replaced by a [binary tree](http://www.java67.com/2016/08/binary-tree-inorder-traversal-in-java.html), which will give you **O(logN)** performance in the worst case as compared to O(n) of a linked list.

**Question 2: How does substring () inside String works?** ([answer](http://javarevisited.blogspot.sg/2011/10/how-substring-in-java-works.html "Click to open in a new window"))

Another good Java interview question, I think the answer is not sufficient, but here it is "*Substring creates a new object out of source string by taking a portion of original string"*.

This question was mainly asked to see if the developer is familiar with the risk of [memory leak](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Fjava-understanding-solving-memory-problems), which sub-string can create.

Until Java 1.7, the substring holds the reference of the original character array, which means even a sub-string of 5 characters long, *can prevent 1GB character array from garbage collection*, by holding a strong reference.

This issue was fixed in Java 1.7, where the original character array is not referenced anymore, but that change also made the creation of a substring a bit costly in terms of time. Earlier it was on the range of O(1), which could be O(n) in the worst case of Java 7 onwards.

Btw, if you want to learn more about memory management in Java, I recommend checking out [Understanding the Java Virtual Machine: Memory Management](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Funderstanding-java-vm-memory-management) course By Kevin Jones on Pluralsight.

[![](https://3.bp.blogspot.com/-N209tnOe6R0/Vod9K_ZfNeI/AAAAAAAAEdw/iRdD6OcOaHQ/s400/JVM%2Barchitecture.jpg)](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Funderstanding-java-vm-memory-management)


**Question 3: Does all property of Immutable Object needs to be final in Java?** ([answer](http://javarevisited.blogspot.com/2013/03/how-to-create-immutable-class-object-java-example-tutorial.html))

Not necessary, as stated in the linked answer article, you can achieve the same functionality by *making a member as non-final but private and not modifying them except in constructor.*

Don't provide a setter method for them and if it is a mutable object, then don't ever leak any reference for that member.

Remember [making a reference variable final](https://javarevisited.blogspot.com/2016/09/21-java-final-modifier-keyword-interview-questions-answers.html), only ensures that it will not be reassigned a different value, but you can still change individual properties of an object, pointed by that reference variable.

This is one of the key points, Interviewer likes to hear from candidates. If you want to know more about final variables in Java, I recommend joining [The Complete Java MasterClass](https://click.linksynergy.com/fs-bin/click?id=JVFxdTr9V80&subid=0&offerid=323058.1&type=10&tmpid=14538&RD_PARM1=https%3A%2F%2Fwww.udemy.com%2Fjava-the-complete-java-developer-course%2F) on Udemy, one of the best, hands-on course.

**Question 4: Can you use HashMap in the multi-threaded environment? What can be the problem? When does get() method go to the infinite loop?** ([answer](http://java67.blogspot.com/2013/06/how-get-method-of-hashmap-or-hashtable-works-internally.html "Click to open in a new window"))\
Answer: Well, nothing is wrong, it depends upon how you use it. For example, if you [initialize a HashMap](http://www.java67.com/2016/01/how-to-initialize-hashmap-with-values-in-java.html) by just one thread and then all threads are only reading from it, then it's perfectly fine.

One example of this is a **Map which contains configuration properties**.

The real problem starts when at least one of that thread is updating HashMap i.e. adding, changing, or removing any key-value pair.

Since put() operation can cause re-sizing and which can further lead to an infinite loop, that's why either you should use [Hashtable](http://javarevisited.blogspot.com/2012/01/java-hashtable-example-tutorial-code.html) or [ConcurrentHashMap](http://javarevisited.blogspot.com/2013/02/concurrenthashmap-in-java-example-tutorial-working.html), later is even better.


**Question 5: Can you write a critical section code for the singleton?** ([answer](http://javarevisited.blogspot.sg/2014/05/double-checked-locking-on-singleton-in-java.html "Click to open in a new window"))\
This core Java question is another common question and expecting the candidate to write Java singleton using [double-checked locking](http://www.java67.com/2015/09/thread-safe-singleton-in-java-using-double-checked-locking-pattern.html).

Remember to use a [volatile variable](http://javarevisited.blogspot.sg/2011/06/volatile-keyword-java-example-tutorial.html) to make Singleton [thread-safe](http://www.java67.com/2016/04/why-double-checked-locking-was-broken-before-java5.html).

Here is the code for a critical section of a thread-safe Singleton pattern using [double-checked locking idiom](https://javarevisited.blogspot.com/2014/05/double-checked-locking-on-singleton-in-java.html):

```java
public class Singleton {

private static volatile Singleton _instance;

/** * Double checked locking code on Singleton\
    * @return Singelton instance\
*/

public static Singleton getInstance() {

if (_instance == null) {

synchronized (Singleton.class) {

if (_instance == null) {

_instance = new Singleton();

}

}

}

return _instance; }

}
```

On the same note, it's good to know about classical design patterns likes Singleton, Factory, Decorator, etc. If you are interested in this then this [**Design Pattern in Java**](https://click.linksynergy.com/deeplink?id=JVFxdTr9V80&mid=39197&murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fdesign-patterns-java%2F) is a good collection of that.

[![](https://cdn-images-1.medium.com/max/1000/1*MTeZ0WlAo-_9AAQrGS-CCw.jpeg)](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Fpatterns-library)

**Question 6: How do you handle error condition while writing a stored procedure or accessing stored procedure from java?** ([answer](http://javarevisited.blogspot.com/2013/04/spring-framework-tutorial-call-stored-procedures-from-java.html))

This is one of the *tough Java interview questions* and again it's open for you all, my friend didn't know the answer so he didn't mind telling me.

My take is that a stored procedure should return an error code if some operation fails but if the stored procedure itself fails then catching [SQLException](http://www.java67.com/2016/06/javasqlsqlexception-no-suitable-driver-found-jdbc-mysql-localhost-3306.html) is the only choice.

The [**Effective Java 3rd Edition**](https://www.amazon.com/Effective-Java-3rd-Joshua-Bloch/dp/0134685997/?tag=javamysqlanta-20) also has some good advice on dealing with error and exceptions in Java, which is worth reading.

[![](https://cdn-images-1.medium.com/max/1000/1*p_TBjBE24E87PMZuv_koUA.png)](https://www.amazon.com/Effective-Java-3rd-Joshua-Bloch/dp/0134685997/?tag=javamysqlanta-20)

**Question 7 : What is difference between Executor.submit() and Executer.execute() method ?** ([answer](http://java67.blogspot.com/2012/08/5-thread-interview-questions-answers-in.html "Click to open in a new window"))

This Java interview question is from my list of [Top 50 Java multi-threading question answers](http://javarevisited.blogspot.sg/2014/07/top-50-java-multithreading-interview-questions-answers.html#axzz4jaJmaqbE), It's getting popular day by day because of the huge demand for a Java developer with good concurrency skill.

The answer to this Java interview question is that former returns an object of [Future](http://javarevisited.blogspot.sg/2015/06/how-to-use-callable-and-future-in-java.html#axzz4tUeeQOAU) which can be used to find the result from a worker thread)

There is a difference when looking at exception handling. If your tasks throw an exception and if it was submitted with executing 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()` method any thrown exception, [checked exception](http://javarevisited.blogspot.sg/2011/12/checked-vs-unchecked-exception-in-java.html "Click to open in a new window") or not, is the part of the task's return status.

For a task that was submitted with submitting and that terminates with an exception, the Future.get() will re-throw this exception, wrapped in an ExecutionException.

If you want to learn more about Future, Callable, and Asynchronous computing and take your Java Concurrency skills to next level, I suggest you check out [**Java Concurrency Practice in Bundle**](https://learning.javaspecialists.eu/courses/concurrency-in-practice-bundle?affcode=92815_johrd7r8) course by Java Champion Heinz Kabutz.

[![](https://cdn-images-1.medium.com/max/1000/1*9d4d_Pne_2jSwdCi9aG9NQ.png)](https://learning.javaspecialists.eu/courses/concurrency-in-practice-bundle?affcode=92815_johrd7r8)

It's an advanced course, which is based upon the classic [**Java Concurrency Practice**](http://www.amazon.com/dp/0321349601/?tag=javamysqlanta-20) book by none other than [Brian Goetz](https://medium.com/@briangoetz), which is considered as a bible for Java Developers. The course is definitely worth your time and money. Since Concurrency is a tough and tricky topic, a combination of this book and course is the best way to learn it.

**Question 8: What is the difference between factory and abstract factory pattern?** ([answer](http://javarevisited.blogspot.sg/2013/01/difference-between-factory-and-abstract-factory-design-pattern-java.html "Click to open in a new window"))\
Answer: Abstract Factory provides one more level of abstraction. Consider different factories each extended from an Abstract Factory and responsible for the 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 the creation of objects in that genre.

If you want to learn more about Abstract Factory design patterns then I suggest you check out [Design Pattern in Java](https://click.linksynergy.com/fs-bin/click?id=JVFxdTr9V80&subid=0&offerid=323058.1&type=10&tmpid=14538&RD_PARM1=https%3A%2F%2Fwww.udemy.com%2Fdesign-patterns-java%2F) course, which provides a nice, real-world example to understand patterns better.

Here is UML diagram of factory and abstract factory pattern:

[![](https://cdn-images-1.medium.com/max/1000/1*zoSC-TjwFjirb_ShdCnfYQ.jpeg)](https://click.linksynergy.com/fs-bin/click?id=JVFxdTr9V80&subid=0&offerid=323058.1&type=10&tmpid=14538&RD_PARM1=https%3A%2F%2Fwww.udemy.com%2Fdesign-patterns-java%2F)

If you need more choices, then you can also check out my list of [Top 5 Java Design Pattern](https://javarevisited.blogspot.com/2018/02/top-5-java-design-pattern-courses-for-developers.html) courses.

**Question 9: What is Singleton? is it better to make the whole method synchronized or only the critical section synchronized?** ([answer](http://javarevisited.blogspot.com/2012/12/how-to-create-thread-safe-singleton-in-java-example.html))\
Singleton in Java is a class with just one instance in the whole Java application, for example, `java.lang.Runtime` is a Singleton class.

Creating Singleton was tricky prior to Java 4 but once Java 5 introduced [Enum](https://javarevisited.blogspot.com/2011/08/enum-in-java-example-tutorial.html) it's very easy.

You can see my article [How to create thread-safe Singleton in Java](http://javarevisited.blogspot.sg/2012/12/how-to-create-thread-safe-singleton-in-java-example.html) for more details on writing Singleton using the enum and double checked locking which is the purpose of this Java interview question.

**Question 10: Can you write code for iterating over HashMap in Java 4 and Java 5?** ([answer](http://java67.blogspot.com/2014/05/3-examples-to-loop-map-in-java-foreach.html "Click to open in a new window"))\
Tricky one, but he managed to write using while and a for a loop. Actually, there are four ways to iterate over any Map in Java, one involves using [keySet()](http://www.java67.com/2016/05/keyset-vs-entryset-vs-values-in-java-map-example.html) and iterating over a key and then using [get()](http://www.java67.com/2013/06/how-get-method-of-hashmap-or-hashtable-works-internally.html) method to retrieve values, which is a bit expensive.

The second method involves using [entrySet()](http://www.java67.com/2013/08/best-way-to-iterate-over-each-entry-in.html) and iterating over them either by using [for each loop](https://javarevisited.blogspot.com/2015/09/java-8-foreach-loop-example.html#axzz5HKqzQNyN) or while with Iterator.hasNext() method.

This one is a better approach because both key and value object is available to you during Iteration and you don't need to call [get()](http://javarevisited.blogspot.sg/2011/02/how-hashmap-works-in-java.html) method for retrieving the value, which could give the O(n) performance in case of a huge [linked list](http://www.java67.com/2017/06/5-difference-between-array-and-linked.html) at one bucket.

You can further, see my post [4 ways to iterate over Map in Java](http://javarevisited.blogspot.com/2011/12/how-to-traverse-or-loop-hashmap-in-java.html) for detailed explanation and code examples.

**Question 11 : When do you override hashCode() and equals()?** ([answer](http://javarevisited.blogspot.com/2013/08/10-equals-and-hashcode-interview.html))\
Whenever necessary especially if you want to do an equality check based upon business logic rather than object equality e.g. two employee objects are equal if they have the same `emp_id`, despite the fact that they are two different objects, created by different parts of the code.

Also, [overriding](http://www.java67.com/2013/04/example-of-overriding-equals-hashcode-compareTo-java-method.html) both these methods are must if you want to use them as key in [HashMap](http://www.java67.com/2017/08/top-10-java-hashmap-interview-questions.html).

Now as part of the equals-hashcode contract in Java, when you override equals, you must override hashcode as well, otherwise, your object will not break invariant of classes e.g. Set, Map which relies on [equals()](http://javarevisited.blogspot.sg/2013/08/10-equals-and-hashcode-interview.html) method for functioning properly.

You can also check my post [5 tips on equals in Java](http://javarevisited.blogspot.com/2011/02/how-to-write-equals-method-in-java.html) to understand the subtle issue which can arise while dealing with these two methods.

**Question 12: What will be the problem if you don't override hashCode() method?** ([answer](http://java67.blogspot.sg/2013/04/example-of-overriding-equals-hashcode-compareTo-java-method.html "Click to open in a new window"))\
If you don't override the equals method, then the contract between equals and hashcode will not work, according to which, two objects which are equal by equals() must have the **same hashcode**.

In this case, another object may return different hashCode and will be stored on that location, which breaks invariant of [HashMap class](http://www.java67.com/2013/02/10-examples-of-hashmap-in-java-programming-tutorial.html) because they are not supposed to allow duplicate keys.

When you add the object using the put() method, it iterates through all Map.Entry objects present in that bucket location, and update value of the previous mapping, if Map already contains that key. This will not work if the hashcode is not overridden.

If you want to learn more about the role of equals() and hashCode() in Java Collections like Map and Set, I suggest you go through [Java Fundamentals: Collections](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Fjava-fundamentals-collections) course on Pluralsight by Richard Warburton

[![](https://cdn-images-1.medium.com/max/1000/1*HVbOHlpmI5PGNgWUpgpI5A.jpeg)](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Fjava-fundamentals-collections)

**Question 13 : Is it better to synchronize critical section of getInstance() method or whole getInstance() method?** ([answer](http://javarevisited.blogspot.com/2014/05/double-checked-locking-on-singleton-in-java.html))\
The answer is only a critical section because if we lock the whole method that every time someone calls this method, it will have to wait even though we are not creating an object.

In other words, [synchronization](http://javarevisited.blogspot.sg/2011/04/synchronization-in-java-synchronized.html#axzz4sZOoYUxv) is only needed, when you create an object, which happens only once.

Once an object has created, there is no need for any synchronization. In fact, that's very poor coding in terms of performance, as the synchronized method reduces performance up to 10 to 20 times.

Here is UML diagram of [Singleton design pattern](https://javarevisited.blogspot.com/2011/03/10-interview-questions-on-singleton.html):

[![](https://cdn-images-1.medium.com/max/1000/1*ySVB-r0Nj4m9P9i8Lz_dgw.png)](http://bit.ly/2xZnIDC)

By the way, there are several ways to create a thread-safe singleton in Java, including [Enum](http://javarevisited.blogspot.sg/2012/07/why-enum-singleton-are-better-in-java.html#axzz4tzMEHSJw), which you can also mention as part of this question or any follow-up.

If you want to learn more, you can also check to [**Learn Creational Design Patterns in Java** ](http://bit.ly/2xZnIDC)--- A #FREE Course from Udemy.

**Question 14: Where does equals() and hashCode() method comes in the picture during the get() operation on HashMap?** ([answer](https://javarevisited.blogspot.com/2017/08/top-10-java-concurrenthashmap-interview.html#axzz5ITbIGRsU))\
This core Java interview question is a follow-up of previous Java questions and the candidate should know that once you mention hashCode, people are most likely to ask, how they are used in HashMap.

When you provide a key object, first its hashcode method is called to calculate bucket location. Since a bucket may contain more than one entry as a linked list, each of those Map.Entry object is evaluated by using equals() method to see if they contain the actual key object or not.

I strongly suggest you read my post, [**How HashMap works in Java**](http://javarevisited.blogspot.sg/2011/02/how-hashmap-works-in-java.html), another tale of an interview to learn more about this topic.

[![](https://cdn-images-1.medium.com/max/1000/1*P5LcQWTCtU8VMPkpaA77eQ.jpeg)](http://bit.ly/2AHuthF)

**Questions 15: How do you avoid deadlock in Java?** ([answer](http://javarevisited.blogspot.sg/2015/10/133-java-interview-questions-answers-from-last-5-years.html))\
If you know, a deadlock occurs when two threads try to access two resources that are held by each other, but to that happen the following four conditions need to match:

1.  Mutual exclusion\
    At least one process must be held in a non-sharable mode.
2.  Hold and Wait\
    There must be a process holding one resource and waiting for another.
3.  No preemption\
    resources cannot be preempted.
4.  Circular Wait\
    There must exist a set of processes

You can avoid deadlock by breaking the *circular wait condition*. In order to do that, you can make arrangements in the code to impose the **ordering** on acquisition and release of locks.

If the lock will be acquired in a consistent order and released in just the opposite order, there would not be a situation where one thread is holding a lock that is acquired by another and vice-versa.

You can further see my post, [**how to avoid deadlock in Java**](https://javarevisited.blogspot.com/2018/08/how-to-avoid-deadlock-in-java-threads.html) for the code example and a more detailed explanation.

I also recommend, [Java Multithreading, Concurrency & Performance Optimization](https://click.linksynergy.com/deeplink?id=JVFxdTr9V80&mid=39197&murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fjava-multithreading-concurrency-performance-optimization%2F) By Michael Pogrebinsky on Udemy for a better understanding of concurrency patterns for Java developers.

[![](https://cdn-images-1.medium.com/max/1000/1*WauLWDjUsj1CyO6dLmRDAA.gif)](https://click.linksynergy.com/deeplink?id=JVFxdTr9V80&mid=39197&murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fjava-multithreading-concurrency-performance-optimization%2F)

**Question 16: What is the difference between creating String as new() and literal?** ([answer](http://javarevisited.blogspot.com/2012/10/10-java-string-interview-question-answers-top.html))\
When we create a String object in Java with a new() Operator, it's created in [heap](https://javarevisited.blogspot.com/2011/05/java-heap-space-memory-size-jvm.html#axzz5SDsAfcC8) and not added into string pool while String created using [literal](http://www.java67.com/2014/08/difference-between-string-literal-and-new-String-object-Java.html) are created in String pool itself which exists in PermGen area of heap.

`String str = new String("Test")`

does not put the object str in String pool, we need to call [String.intern()](https://javarevisited.blogspot.com/2015/12/when-to-use-intern-method-of-string-in-java.html) method which is used to put them into String pool explicitly.

It's only when you create a String object as String literal e.g. `String s = "Test"` Java automatically puts that into String pool.

By the way, there is a catch here Since we are passing arguments as "Test", which is a String literal, it will also create another object as "Test" on [string pool](http://javarevisited.blogspot.sg/2016/07/difference-in-string-pool-between-java6-java7.html).

This is the one point, which has gone unnoticed until knowledgeable readers of [Javarevisited](http://javarevisited.blogspot.com/) blog suggested it. To learn more about the difference between a String literal and String object, see [this](http://java67.blogspot.sg/2014/08/difference-between-string-literal-and-new-String-object-Java.html "Click to open in a new window") article.

Here is a nice image that shows this difference quite well:

[![](https://cdn-images-1.medium.com/max/1000/1*4s5ZMfvuiIxI-4rBM_oubg.png)](http://javarevisited.blogspot.sg/2013/07/java-string-tutorial-and-examples-beginners-programming.html)

**Question 17: What is an Immutable Object? Can you write Immutable Class?** ([answer](http://javarevisited.blogspot.in/2013/03/how-to-create-immutable-class-object-java-example-tutorial.html "Click to open in a new window"))\
Immutable classes are Java classes whose objects cannot be modified once created. Any modification in Immutable object results in the new object, for example, [String is immutable in Java](http://javarevisited.blogspot.sg/2010/10/why-string-is-immutable-in-java.html "Click to open in a new window").

Mostly Immutable classes are also [final](https://javarevisited.blogspot.com/2011/12/final-variable-method-class-java.html) in Java, in order to prevent subclasses from overriding methods, which can compromise Immutability.

You can achieve the same functionality by making member non-final but [private](http://javarevisited.blogspot.sg/2012/10/difference-between-private-protected-public-package-access-java.html) and not modifying them except in the constructor.

Apart from the obvious, you also need to make sure that, you should not expose the internals of an Immutable object, especially if it contains a mutable member.

Similarly, when you accept the value for the mutable member from client like `java.util.Date`, use [clone() method](http://javarevisited.blogspot.sg/2013/09/how-clone-method-works-in-java.html "Click to open in a new window") keep a separate copy for yourself, to prevent the risk of malicious client modifying mutable reference after setting it.

The Same precaution needs to be taken while returning value for a mutable member, return another separate copy to the client, never return original reference held by Immutable class. You can also see my post [How to create an Immutable class in Java](http://javarevisited.blogspot.sg/2013/03/how-to-create-immutable-class-object-java-example-tutorial.html) for step by step guide and code examples.

**Question 18: Give the simplest way to find out the time a method takes for execution without using any profiling tool?** ([answer](http://javarevisited.blogspot.com/2012/10/10-java-string-interview-question-answers-top.html))\
Read the system time just before the method is invoked and immediately after the method returns. Take the time difference, which will give you the time taken by a method for execution.

Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for execution. Try it on a method which is big enough, in the sense the one which is doing a considerable amount of processing

**Question 19: Which two method you need to implement to use any Object as a key in HashMap?** ([answer](http://javarevisited.blogspot.com/2013/01/difference-between-identityhashmap-and-hashmap-java.html))\
In order to use any object as Key in HashMap or Hashtable, it must implement [equals](http://www.java67.com/2012/11/difference-between-operator-and-equals-method-in.html) and [hashcode](http://javarevisited.blogspot.sg/2015/01/why-override-equals-hashcode-or-tostring-java.html#axzz55oDxm8vv) method in Java.

You can also read [How HashMap works in Java](http://javarevisited.blogspot.sg/2011/02/how-hashmap-works-in-java.html) for a detailed explanation on how equals and hashcode method is used to put and get an object from HashMap.

**Question 20: How would you prevent a client from directly instantiating your concrete classes? For example, you have a Cache interface and two implementation classes MemoryCache and DiskCache, How do you ensure there is no object of these two classes is created by the client using a new() keyword.**\
I leave this question for you to practice and think about before I give the answer. I am sure you can figure out the right way to do this, as this is one of the important decisions to keep control of classes in your hand, great from a maintenance perspective.

**Further Learning**

1.  [The Complete Java Masterclass](https://click.linksynergy.com/fs-bin/click?id=JVFxdTr9V80&subid=0&offerid=323058.1&type=10&tmpid=14538&RD_PARM1=https%3A%2F%2Fwww.udemy.com%2Fjava-the-complete-java-developer-course%2F)
2.  [Java Fundamentals: The Java Language](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Fjava-fundamentals-language)
3.  [Core Java SE 9 for the Impatient](https://www.amazon.com/Core-Java-SE-Impatient-2nd/dp/0134694724?tag=javamysqlanta-20)
4.  [**200+ Java Interview questions**](http://bit.ly/2CupaSL)
5.  [Ace the Java Coding Interview](https://www.educative.io/track/ace-java-coding-interview?affiliate_id=5073518643380224)

### Closing Notes

Great!!, you made it to the end of the article... Good luck with your Java Programming Interview! It's certainly not going to be easy, but by following these questions, you are one step closer to accomplishing your goal.

Please consider following me ([**javinpaul**](https://twitter.com/javinpaul)) on Medium if you'd like to be notified on my new post, and don't forget to follow me on [**Twitter**](https://twitter.com/javinpaul)**!**