MUST Have Core Java Interview Questions – Part 3

We are continuing with Part-3 of MUST Have Core Java Interview Questions and Detailed answers tutorial. Major topics covered in this Java Tutorial are Garbage Collection in Java, File Handling and Java I/O, Generics in Java, Hashmap details and performance improvements in it.

Java Interview Questions and Answers

Complete Java Interview Questions List


Explain garbage collection with example? What are different parameters to tune GC?

Garbage collection is most important and most critical part of JVM. Whenever we create any object it is created on the heap area. When these objects keep on creating in the heap area, heap gets full and whenever on the full heap VM tries to put a new object, it does not allows and throw error.

This is same in C,C++ as well, where we need to remove the object or clear the space manually and need to create destructor to finalize object.

Java takes this part a step forward and provides garbage collector which automatically collects the unused objects and keeps heap space happy. So programmer while writing program needs not to worry about the object destruction part.

Java provides automatic garbage collection, and it just removes the objects that are not reachable anymore.

There are two kind of object state in Heap :

Reachable, these are the objects that are referenced.

Unreachable, there are the objects that are not referenced from anywhere.

Below is the diagram how the heap is divided:Garbage Collection Java Tutorial

This is how the head is divided into regions.  There are basically two regions in heap, these are Young Generation and Old Genearation.

Lets talk about both of them brief:

Young Generation : As the name suggests, young generation is the space where once the object is formed, it is placed in. Young generation is further divided into two regions that are Eden Space and Survivor Space. Eden space is the space where all the fresh or new objects are placed, once any new object is created with new, it will be placed into Eden space. We will talk about GC strategy afterwards but when GC cycle runs and any object that survives one cycle are moved to Survivor space and in Survivor space these objects are keep moving from one to other from each GC cycle. Some objects that became unreachable are garbage collected and some objects who are still reachable are exists in the survivor space.

Old Generation:  Old generation again as the name suggests where old objects are placed. So we have talked about the survivor space in young generation. Objects that are survived more than a threshold that is max tenuring threshold are moved to old generation.

Below is the GC parameter for this threshold:

Whenever any object crosses the number that is given in MaxTenuringThreshold, the same object is promoted to Old generation.

There are GC cycles as well, they kicks in when JVM sense low heap memory.

Minor GC Cycle is GC cycle that run periodically and collects the unreachable objects.  Whenever there is memory crunch and there is low memory then GC triggers major GC that runs on whole heap and collects the objects that are unreachable.

If your JVM continuously kicks major GC then there are possible chances of memory leak. In this case one needs to check application and find out the possible memory leak.

There are different kind of Garbage collectors available and we can use any of them with our application.

  • Serial Collector : Serial garbage collector is a garbage collector which runs with single thread and the same can be used for small applications.
  • CMS : CMS stands for concurrent mark sweep garbage collector. In this kind of garbage collector JVM continually does mark and sweep on the objects that are in the heap. This runs along with the application. One more thing about this garbage collector is that it doesnot stops the world, it just stops the world on mark/remark process. When we say stop the world it means that the application will be paused for a small amount of time.
  • Parallel: Parallel garbage collector is a garbage collector which uses multiple CPU’s to garbage collect from heap. Uses multiple CPU’s to mark and sweep. This garbage collector stops the world when it runs.
  • G1 : G1 stands for Garbage First, Introduced in java 7, this garbage collector divides the heap into small small regions. Regions with most garbage will be collected first.

There are different VM arguments to select the respective garbage collector:

For Serial GC:

For Parallel GC:


For G1 GC:

Back to top

Explain file handling in java, explain I/O in java, with example?

To deal with file system, java comes with I/o package, which provides a very rich library to interact with any of the file system. I/O basically stands for input/output. Java provides functions that deal with file system, whether creating a file, reading or deleting.

Lets talk about term Stream, that is very widely used term when we talk about i/o in java. So what is stream in java? Stream is basically a sequence of data that will be either reading by our program or our code will be writing, with is in a way input / output operation.

There are abstract classes present different kinds of stream that are ByteStream and CharacterStream. We will be using these classes when writing our code for input/output handling.

For ByteSteam java comes with InputStream and OutputStream, whereas for CharacterStream java comes with Reader and writer classes. For reading out of file system java comes with InputStream, whereas for writing OutputStream is used. For optimization BufferedInputStream and BufferedOutputStream are used.

Below is the hierarchy diagram of I/O classes:File Handling in Java

So this is how the file system hierarchy goes. Dotted one means there are multiple implementations but we have listed some of them. You can go through the java doc for all specification. But these are the implementations which are most widely used while dealing with file system.

Lets write code for creating file and write some data over it:

Lets understand the code first and then try to run and see what happens. What we have done is we first created File object and created a new file in our system. Once we are done with creating new file, we have to write some data in this. For this purpose we have used BufferedOutputStream, since as we have discussed earlier as well, BufferedOutputStream is optimized way while we deal with file system. After that we just write byte array to output stream which will actually write the data to our file system.

Lets run the code and try to find if it working fine:TempFile in System Path

So as we can see tempfile has been created in the given system path. Lets open and see if it containes the data that we have passed:Java TempFile

Allright, so we got the data what we wanted to write in the file. This was a very simple example of how to write data in a file using I/O library in java. In the same way using FileInputStream we can read the data from file system as well. Apart of these i/o library has a lot of methods to deal with file system. This is all about file handling in java using i/o library.

Back to top

Explain generics in java with example?

From java 1.5 a new concept is emerged that was generics and from then this was used very heavily in all types of applications. What was so special in generics and what does it solved. Lets understand in this section.

Basically generics provide some very useful features like type safety. Type safety is some thing which was not there in java before java1.5, type safety is a concept which says there is only and only one type of object is allowed in collection.

For example:

In the above example only String type of objects are allowed in this collection. If one tries to enter any object other than String complier will throw the error.

Here one more important thing of generics comes that is check at compile time and not run time. And this is another good thing which is these small types of thigs are detected at compile time and not at run time.

If one tries to add integer or some other object compiler will throw error and it is not allowed to do.

What if one tries to create a Generic class, let’s try to create on:

So we have created a simple generic class with set and get the object. To create one we need to modify the class signature what we usually writes, and append a generic object term to it, in the example above we used it as T. T is the type of object what we will try to set and get from our main class.

Lets create our main class and test if our Generic class working fine:

Executing the above code we got the output as:Generic Classes in Java

So we got what we set with the Generic class’s setObj method.

We can use generics on the method level as well like we used on class level.

Subtyping is not allowed in generics. Like we can not use subtype while declare with generics. Like we can not use Object and String as subtype in generics. For example:

Writing the above line, compiler will complain and the code will not compile. Lets try to run and see what the above code will throw exception.MainGenerics in Java

Running the code will throw the above exception. Irrespective of String is subtype of Object, but the compiler will not allow to use the sub types in generics.

Back to top

Explain HashMap in detail, what are performance enhancements in HashMap in Java8?

Hashmap is a special kind of collection in java and why we use special kind of collection with HashMap is because unlike other type of collection, HashMap provides key, value pair type of collection which other collection doesnot provides.

HashMap works on concept of hashing. One thumb rule is while working with hash based collection is that when writing custom classes and use them as a key in HashMap, we should always override HashCode and equals methods.

And why these are important is because, based on the hashcode, there is one more method in HashMap class which again calculates hash for the object, just to prevent against poor quality hash code methods.

Below is the implementation of hash method from HashMap class:

As we can see, object’s hash code is used again in the HashMap class.

Based on the hash, bucket is defined, on which the object will be placed. So there are buckets which are simply an array. Index of array is calculated based on the hash value and based on the index the values are placed in the bucket.

One more important thing to learn is Entry class, Entry class is an inner class in HashMap, code of Entry class is as follows:

So we have just added a glimpse of Entry class to understand what this class does. There is a lot of code in this class, that you can found in the HashMap class itself.

So basically bucket has Entry objects. Entry class is basically a LinkedList, if you see there is a next variable in the class which contains the next pointer. Apart of this there are key and values that HashMap stores.

So why this Entry class is designed as LinkedList?

What we understand earlier is that, based on the hashcode that we have defined in our object, the index is calculated and based on the index the object is placed in HashMap. Now suppose, for two object same index is calculated. If there is same index and if there is already an object is placed in the bucket then will it be overrided ? No, because the Entry class is designed in such a way that if there are more than one object on the same index then these will be added in the Iinked list.

This is because the Entry class is designed as LinkedList.

Now Lets see code for put and get methods in HashMap class.

So as we can see in put method, hash function is used to generate hashcode and the same hash is used to get the index for the bucket. One more thing, there is only one null key allowed in HashMap and the handling for the same can be seen in the method.

Lets see code for get as well:

So here we placed code for getEntry, which is been called from get method of HashMap. Here as well same as the put method, hash function is used to calculate the hash and based on hash the bucket is decided and based on bucket the Entry is fetched.

If you see the code of put and get closely then you will find the importance of equals and hashcode methods . And why it is very important to have them in the object that is being used as key in HashMap.

Now lets talk some about performance now, suppose there is very bad hash code designed and that returns the same value each and every time. In this case the bucket location of all objects will be same and the linked list will keep on growing. And once the the linked list grows then to retrieve the element is difficult because the complexity will be O(n) at that time. So what performance improvement being done as part of java8 is that whenever the linked list grows about a threshold the list is converted into a tree, and tree is red black tree, we will not go in the details of redblack tree but certainly the performance improvement will be there. Since the complexity of tree traversal is O(logn) . That is the performance improvement done as part of java8 in HashMap. This is all about HashMap in java.

Back to top

This Java Tutorial Series is continued and you can find more Java Interview Questions and answers in coming Web Development Java Tutorial here.

More Technical Interview Questions and Answers Series: