100+ Java interview questions and answers for freshers & experienced professionals and users. Top Java interview questions with their answers for fresher and experienced professionals and users. Most common and tricky Java interview questions with their answers for fresher and experienced professionals and users.
This is a two part article where I will share 100+ Java Interview Questions and Answers for Freshers & Experienced professionals and users. I have already written first list of 50 java interview questions and answers, here I will continue the article with the remaining questions and answers.
Java Interview Questions and Answers
Let us start with the java interview questions and answers
51. What is a static import in Java?
Static import is similar to normal import declaration. Normal import allows us to import classes from packages without using package qualifier. Static import allows us to import static members from a class without using class qualifier.
52. What is the difference between import static com.test.Fooclass and import com.test.Fooclass?
First import is a static import and the second import is normal import of a class. First import allows us to import static members of class.
53. What is Locale in Java?
- A Locale object represents a specific geographical, political, or cultural region. It is used to locale-sensitive operations in Java.
- It helps is following the local conventions of a country, native or region. These conventions can be for formatting the dates, money, numbers etc.
54. What is the serialization?
Serialization is a process converting an object into a byte array. This byte array represents the class, version and internal state of the object. JVM can use this byte array to transmit/read the object over a network.
55. What is the purpose of serialization?
Some of the uses of serialization are:
- Communication: It is used for transmitting an object over network between two machines.
- Persistence: We can store the object’s state in a database and retrieve it from database later on.
- Caching: Serialization can be used for caching to improve performance. We may need 10 minutes to build an object, but it may take just 10 seconds to de-serialize the object.
- Cross JVM Synchronization: It can be used in same way across multiple JVM that follow different architecture.
56. Why do we mark a data member transient?
Member variables of an object are marked transient to indicate that they should not be serialized. During serialization process the transient variables are not considered part of the persistent state of an object.
57. How does marking a field as transient makes it possible to serialize an object?
- Let say we have a class ABC that implements Serializable interface, but it contains a member variable object of class XYZ that does not implement Serializable interface. Due to this it is not possible to Serialize the class ABC.
- To solve this issue, we can mark the member variable XYZ as Transient in class ABC. This will allow us to serialize the class ABC.
58. What is Externalizable interface in Java?
- Externalizable interface extends Serializable interface in Java. It is used for giving the Class control over saving and restoring the contents of its instances.
- A class implements methods writeExternal() and readExternal() to store and restore the object.
59. What is the difference between Serializable and Externalizable interface?
- Serializable is a marker interface but Externalizable is not a marker interface.
- When we implement Serializable interface, the class is serialized automatically by default. We can override writeObject() and readObject()methods to control more complex object Serialization process.
- In case of Externalizable, we use readExternal() and writeExternal() methods to give control to class for class's serialization process.
- Serializable interface is based on recursive algorithm.
- Serializable gives you two options. One option is to provide custom way of serialization, the other default way. In Externalizable, you have to always implement readExternal() and writeExternal() methods.
- A public no-arg constructor is needed while using Externalizable interface.
- In Serialization, we need to define serialVersionUID. If it is not explicitly defined it will be generated automatically based on all the fields, methods of the class.
60. What is Reflection in Java?
Reflection is Java language's ability to inspect and dynamically call classes, methods, attributes etc. at Runtime. It helps in examining or modifying the Runtime behavior of a class at Runtime.
61. What are the uses of Reflection in Java?
- Reflection is often used in Testing, Debugging and in Integrated Development Environment (IDE).
- Reflection allows you to write programs that do not have to "know" everything at compile time. It makes programs more dynamic, since they can be tied together at runtime.
- Many modern frameworks like Spring etc. use Reflection. Some modern languages like Python etc. also use Reflection.
- JAVA API for XMLParsing (JAXP) also uses Reflection.
62. How can we access private method of a class from outside the class?
We can use Reflection to access private method of a class from outside the class. IN Java, we use getDeclaredMethod() to get instance of a private method. Then we mark this method accessible and finally invoke it.
In following sample code, we are accessing private method message() of class Foo by Reflection.
FileName: Foo.java public class Foo { private void message(){System.out.println("hello java"); } } FileName: FooMethodCall.java import java.lang.reflect.Method; public class FooMethodCall{ public static void main(String[] args)throws Exception{ Class c = Class.forName("Foo"); Object o= c.newInstance(); Method m =c.getDeclaredMethod("message", null); m.setAccessible(true); m.invoke(o, null); } }
63. What is Garbage Collection in Java?
Java has an internal mechanism called Garbage collection to reclaim the memory of unused projects at run time. Garbage collection is also known as automatic memory management.
64. Why Java provides Garbage Collector?
In Java, there are no pointers. Memory management and allocation is done by JVM. Since memory allocation is automated, after some time JVM may go low on memory. At that time, JVM has to free memory from unused objects. To help with the process of reclaiming memory, Java provides an automated process called Garbage Collector.
65. What is the purpose of gc() in Java?
Java provides two methods System.gc() and Runtime.gc() to request the JVM to run the garbage collection. By using these methods, programmers can explicitly send request for Garbage Collection. But JVM process can reject this request and wait for some time before running the GC.
66. When does an object become eligible for Garbage Collection in Java?
An object can be Garbage Collected by JVM, if it is not reachable. There are two cases for deciding eligibility of objects for Garbage
Collection:
- An Object/instance that cannot be reached by a live thread.
- A set of circularly referenced instances that cannot be reached by any other instance outside that set.
67. Why do we use finalize() method in Java?
- Java provides finalize() method to perform any cleanup before Garbage Collection. This method is in Object class, and it is invoked by JVM internally. Developers are free to implement this method for any custom cleanup in case of Garbage Collection.
- If an Object is not Garbage Collected, then this method may not be called.
- This method is never invoked more than once by JVM.
68. What are the different types of References in Java?
In Java, there are four types of references:
- Strong Reference
- Soft Reference
- Weak Reference
- Phantom Reference
69. What is the purpose of the Runtime class?
The purpose of the Runtime class is to provide access to the Java Runtime system. This class provides certain important methods like:
- Runtime.freeMemory() – This method returns the value of free memory in JVM
- Runtime.maxMemory() - This method returns the value of maximum memory that JVM can use.
- Runtime.gc() – This method can invoke garbage collection.
70. What are the uses of Runtime class?
Runtime class in Java provides following benefits:
- It allows to read data via key board
- It can use system properties and environment variables
- It helps in running non-java programs from within a java application.
71. How many types of Nested classes are in Java?
Java provides four types of Nested classes:
- Member inner class
- Local inner class
- Anonymous inner class
- Static nested class
72. Why do we use Nested Classes?
There are following reasons for using nested classes:
- Logical Grouping: We can logically group classes in one place. If one class is useful to only one other class, then we put smaller class within the larger class and keep them
in one file. This kind of nesting "helper classes" in a toplevel class makes the package more streamlined. - Encapsulation: Nested classes increase encapsulation. Let say there are two top-level classes, Foo and Bar. Bar needs access to private members of Foo. We can hide class Bar within class Foo. In this way, private members of Foo can be accessed by class Bar. So class Foo remains encapsulated. Also, class Bar remains hidden from the outside world.
- Code Clarity: Nested classed make the code more readable and well organized. Only Top-level classes are exposed. The helper classes are kept hidden and closer the code where it is used by a Top-level class.
73. What is the difference between a Nested class and an Inner class in Java?
- An Inner class in Java is non-static class. It is a type of Nested class that is defined in another class but not qualified with a Static modifier. A Nested class is also a class can be Static Nested class or a non-Static Inner class.
- An Inner class has access to other members of the enclosing class, even if they are declared private. A Static Nested class can not access the other members of the enclosing class.
74. Why do we use Static Nested interface in Java?
Only the enclosing class can access a Static Nested interface. Consider following code in which interface Xyz is enclosed in class Abc.
public class Abc { public interface Xyz { void callback(); } public static void registerCallback(Xyz xyz) {...} } // Client Code Abc.registerCallback(new Abc.Xyz() { public void callback() {...} });
Any code that cannot access Abc can not access interface Xyz also.
So the purpose of declaring an Inner interface is to restrict its access from outside world.
75. What is the meaning of Immutable in the context of String class in Java?
- An Immutable object cannot be modified or changed in Java. String is an Immutable class in Java.
- Once a String object is created, it cannot be changed. When we assign the String to a new value, a new object is created
76. Why a String object is considered immutable in java?
- Java language uses String for a variety of purposes. For this it has marked String Immutable.
- There is a concept of String literal in Java.
- Let say there are 2 String variables A and B that reference to a String object “TestData”. All these variables refer to same String literal. If one reference variable A changes the value of the String literal from “TestData” to “RealData”, then it will affect the other variable as well. Due to which String is considered Immutable. In this case, if one variable A changes the value to “RealData”, then a new String literal with “RealData” is created and A will point to new String literal. While B will keep pointing to “TestData”
77. How many objects does following code create?
Code:
String s1="HelloWorld"; String s2=" HelloWorld "; String s3=" HelloWorld ";
The above code creates only one object. Since there is only one String Literal “HelloWorld” created, all the references point to same object.
78. How many objects does following code create?
Code:
String s = new String("HelloWorld");
The above code creates two objects. One object is created in String constant pool and the other is created on the heap in non-pool area.
79. What is String interning?
- String interning refers to the concept of using only one copy of a distinct String value that is Immutable.
- It provides the advantage of making String processing efficient in Time as well as Space complexity. But it introduces extra time in creation of String.
80. What is the basic difference between a String and StringBuffer object?
String is an immutable object. Its value cannot change after creation. StringBuffer is a mutable object. We can keep appending or modifying the contents of a StringBuffer in Java.
81. How will you create an immutable class in Java?
In Java, we can declare a class final to make it immutable. There are following detailed steps to make it Immutable:
- Add final modifier to class to prevent it from getting extended
- Add private modifier to all the fields to prevent direct access
- Do not provide any setter methods for member variables
- Add final modifier to all the mutable fields to assign value only once
- Use Deep Copy to initialize all the fields by a constructor
- In clone method, return a copy of object instead of the actual object reference
82. What is the use of toString() method in java ?
- In Java, Object class has toString() method. This method can be used to return the String representation of an Object. When we print an object, Java implicitly calls toString() method.
- Java provides a default implementation for toString() method. But we can override this method to return the format that we want to print.
83. Arrange the three classes String, StringBuffer and StringBuilder in the order of efficiency for String processing operations?
- StringBuilder is the most efficient class. It does not have the overhead of Synchronization. StringBuffer is a Synchronized class. It has better performance than String but it is slower than StringBuilder. String is the slowest for any String processing operations, since it is leads to creation of new String literal with each modification.
- So the decreasing order of efficiency is: StringBuilder, StringBuffer, String
84. What is Exception Handling in Java?
Java provides Exception Handling mechanism to handle Runtime errors that occur in JVM. There are checked exceptions in a program that we expect to occur in certain situations.
Exception handling mechanism catches these checked exceptions and takes relevant actions.
85. In Java, what are the differences between a Checked and Unchecked?
- Checked Exceptions extend Throwable class, but they do not extend RuntimeException or Error classes. UncheckedException extend RuntimeException class.
- Checked Exceptions are checked at compile time in Java. Unchecked Exceptions happen at Runtime, so they are not checked at compile time.
- IOException, SQLException etc. are examples of Checked Exceptions. NullPointerException, ArithmeticException etc. are examples of Unchecked Exceptions.
86. What is the difference between throw and throws in Java?
- Java provides throw keyword to throw an exception from a method or a static block. Java provides throws keyword to mention the probable exception thrown by a method in its declaration.
- We use throw to explicitly throw an exception. We used throws to declare an exception in method definition.
- We cannot propagate checked exceptions with throw only. But checked exceptions can be propagated with throws keyword.
- A throw call is followed by an instance. Class or Exception follows a throws keyword.
- Call to throw occurs within a method. throws is just used with method signature.
- We can throw only one exception at a time. But we can mention as many exceptions in throws clause.
87. What is the difference between Collection and Collections Framework in Java?
- In Java, a Collection is an object that contains multiple elements of same type in a single unit. These multiple elements can be accessed through one Collection object.
- In Java Collections Framework is a library that provides common architecture for creating, updating and accessing different types of collections. In Collections framework there are common methods that are frequently used by developers for working on a Collection object.
88. What are the main benefits of Collections Framework in Java?
Main benefits of Collections Framework in Java are as follows:
- Reusability: Java Collections Framework provides common classes and utility methods than can be used with different types of collections. This promotes the reusability
of the code. A developer does not have to re-invent the wheel by writing the same method again. - Quality: Using Java Collection Framework improves the program quality, since the code is already tested and used by thousands of developers.
- Speed: Most of programmers report that their development speed increased since they can focus on core logic and use the generic collections provided by Java framework.
- Maintenance: Since most of the Java Collections framework code is open source and API documents is widely available, it is easy to maintain the code written with the help of Java Collections framework. One developer can easily pick the code of previous developer.
89. What is the root interface of Collection hierarchy in Java?
- The root interface of Collection hierarchy in Java is Collection interface.
- But the Collection interface extends Iterable interface. Due to this some people consider Iterable interface as the root interface.
- Iterable interface is present in java.lang package but Collection interface is present in java.util package. Oracle Java API docs mention that Collection interface is a member of the Java Collections framework.
- Whereas, Iterable interface is not stated as a part of Java Collections framework in Java docs.
- Due to this Collection interface is the root of Collections Framework.
90. What are the main differences between Collection and Collections?
Main differences between Collection and Collections are as follows:
- Collection is an interface in Java. But Collections is a class in Java.
- Collection is a base interface. Collections is a utility class in Java.
- Collection defines methods that are used for data structures that contain the objects.
- Collections defines the methods that are used for operations like access, find etc. on a Collection.
91. What are the Thread-safe classes in Java Collections framework?
The Thread-safe classes in Java Collections framework are:
- Stack
- Properties
- Vector
- Hashtable
- BlockingQueue
- ConcurrentMap
- ConcurrentNavigableMap
92. How will you convert a List into an array of integers like- int[]?
We can use ArrayUtils class in Apache Commons Lang library.
Sample code is:
int[]intArray = ArrayUtils.toPrimitive(myList.toArray(newInteger[0]));
If we use List.toArray(), it will convert List to Integer[].
Another option is:
int[] intArray = new int[myList.size()]; for (int i=0; i < myList.size(); i++) { intArray [i] = myList.get(i); }
93. How will you convert an array of primitive integers int[] to a List collection?
We can use ArrayUtils in Apache Commons Lang library for this purpose.
Sample code is:
List intList = Arrays.asList(ArrayUtils.toObject(intArray));
The other option would be to use a for loop and explicitly adding integers to a List.
Sample code is:
int[]intArray = {10,20,30}; List intList = new ArrayList(); for (int i: intArray) { intList.add(i); }
94. How will you convert a List to a Set?
There are two ways to convert a List to a Set in Java.
Option 1: Use HashSet
Set mySet = new HashSet(myList);
In this case we put a list into a HashSet. Internally hashCode() method is used to identify duplicate elements.
Option 2: Use TreeSet
In this case we use our own comparator to find duplicate objects.
Set mySet = new TreeSet(myComparator); mySet.addAll(myList);
95. How will you remove duplicate elements from an ArrayList?
The trick in this question is to use a collection that does not allow duplicate elements. So we use a Set for this purpose.
Option 1: Use Set
If ordering of elements is not important then we just put the elements of ArrayList in a HashSet and then add them back to the ArrayList.
Sample Code is:
ArrayList myList = // ArrayList with duplicate elements Set mySet = new HashSet(myList); myList.clear(); myList.addAll(mySet);
Option 2: Use LinkedHashSet
If ordering of elements is important then we put the elements of ArrayList in a LinkedHashSet and then add them back to the ArrayList.
Sample Code is:
ArrayList myList = // ArrayList with duplicate elements Set mySet = new LinkedHashSet(myList); myList.clear(); myList.addAll(mySet);
96. What are the differences between the two data structures: a Vector and an ArrayList?
An ArrayList is a newer class than a Vector. A Vector is considered a legacy class in Java. The differences are:
- Synchronization: Vector is synchronized, but the ArrayList is not synchronized. So an ArrayList has faster operations than a Vector.
- Data Growth: Internally both an ArrayList and Vector use an array to store data. When an ArrayList is almost full it increases its size by 50% of the array size. Whereas a Vector increases it by doubling the underlying array size
97. What are the differences between Collection and Collections in Java?
Main differences between Collection and Collections are:
- Type: Collection is an interface in Java. Collections is a class.
- Features: Collection interface provides basic features of data structure to List, Set and Queue interfaces. Collections is a utility class to sort and synchronize collection elements. It has polymorphic algorithms to operate on collections.
- Method Type: Most of the methods in Collection are at instance level. Collections class has mainly static methods that can work on an instance of Collection.
98. What are the differences between a List and Set collection in Java?
Main differences between a List and a Set are:
- Order: List collection is an ordered sequence of elements. A Set is just a distinct collection of elements that is unordered.
- Positional Access: When we use a List, we can specify where exactly we want to insert an element. In a Set there is no order, so we can insert element anywhere without worrying about order.
- Duplicate: In a List we can store duplicate elements. A Set can hold only unique elements.
99. What are the differences between a HashSet and TreeSet collection in Java?
Main differences between a HashSet and TreeSet are:
- Ordering: In a HashSet elements are stored in a random order. In a TreeSet, elements are stored according to natural ordering.
- Null Value Element: We can store null value object in a HashSet. A TreeSet does not allow to add a null value object.
- Performance: HashSet performs basic operations like add(), remove(), contains(), size() etc in a constant size time. A TreeSet performs these operations at the order of log(n) time.
- Speed: A HashSet is better than a TreeSet in performance for most of operations like add(), remove(), contains(), size() etc .
- Internal Structure: a HashMap in Java internally backs a HashSet. A NavigableMap backs a TreeSet internally.
- Features: A TreeSet has more features compared to a HashSet. It has methods like pollFirst(), pollLast(), first(), last(), ceiling(), lower() etc.
- Element Comparison: A HashSet uses equals() method for comparison. A TreeSet uses compareTo() method for comparison to maintain ordering of elements.
100. In Java, how will you decide when to use a List, Set or a Map collection?
- If we want a Collection that does not store duplicate values, then we use a Set based collection.
- If we want to frequently access elements operations based on an index value then we use a List based collection. E.g. ArrayList
- If we want to maintain the insertion order of elements in a collection then we use a List based collection.
- For fast search operation based on a key, value pair, we use a HashMap based collection.
- If we want to maintain the elements in a sorted order, then we use a TreeSet based collection.
101. What are the differences between Comparable and Comparator?
Main differences between Comparable and Comparator are:
- Type: Comparable is an interface in Java where T is the type of objects that this object may be compared to.
- Comparator is also an interface where T is the type of objects that may be compared by this comparator.
- Sorting: In Comparable, we can only create one sort sequence. In Comparator we can create multiple sort sequences.
- Method Used: Comparator interface in Java has method public int compare (Object o1, Object o2) that returns a negative integer, zero, or a positive integer when the object o1 is less than, equal to, or greater than the object o2. A Comparable interface has method public int compareTo(Object o) that returns a negative integer, zero, or a positive integer when this object is less than, equal to, or greater than the object o.
- Objects for Comparison: The Comparator compares two objects given to it as input. Comparable interface compares "this" reference with the object given as input.
- Package location: Comparable interface in Java is defined in java.lang package. Comparator interface in Java is defined in java.util package.
102. What are the Java Collection classes that implement List interface?
Java classes that implement List interface are:
- AbstractList
- AbstractSequentialList
- ArrayList
- AttributeList
- CopyOnWriteArrayList
- LinkedList
- RoleList
- RoleUnresolvedList
- Stack
- Vector
103. What are the Java Collection classes that implement Set interface?
Java classes that implement Set interface are:
- AbstractSet
- ConcurrentSkipListSet
- CopyOnWriteArraySet
- EnumSet
- HashSet
- JobStateReasons
- LinkedHashSet
- TreeSet
104. What is the difference between Iterator and Enumeration?
Both Iterator and Enumeration are interfaces in Java to access Data Structures. The main differences between these are:
- Enumeration is an older interface. Iterator is a newer interface.
- Enumeration can only traverse legacy collections. Iterator can traverse both legacy as well as newer collections.
- Enumeration does not provide remove() method. So we cannot remove any element during traversal. Iterator provides remove() method.
- Iterator is a fail-fast interface, it gives ConcurrentModificationException if any thread tries to modify an element in the collection being iterated. Enumeration is not fail-fast.
- Method names in Iterator are shorter than in an Enumeration.
105. How Multi-threading works in Java?
- Java provides support for Multithreading. In a Multithreading environment, one process can execute multiple threads in parallel at the same time.
- In Java, you can create process and then create multiple threads from that process. Each process can execute in parallel to perform independent tasks.
- Java provides methods like- start(), notify(), wait(), sleep() etc. to maintain a multi-threading environment.
Lastly I hope this article on Java Interview Questions and answers for fresher and experienced professionals was helpful. So, let me know your suggestions and feedback using the comment section.