Top 100 Java Tricky Interview Questions and Answers (Part 2)

The post introduces you top 100 Java Tricky Interview Questions and Answers that help you get advantages in the interview or understand more deeply on java. Most of the Java tricky questions come from confusing concepts which is really tricky to master, like function overloading and overriding, character encoding, checked vs unchecked exceptions.

Java Tricky Interview Questions and Answers, java tricky interview questions
A Funny Question

Java Tricky Interview Questions and Answers(continued)

51. Is it ok to use random numbers in the implementation of hashcode() method in Java?
No. The hashcode of an object should be always same. If you use random number in hashcode() method, then you may get a different value of hashcode for same object. This will break the hashcode contract.
52. Between two types of dependency injections, constructor injection and setter dependency injection, which one is better?
Constructor injection guarantees that a class will be initialized with all its dependencies during creation. But setter injection provides flexibility to set an optional dependency.
If we are using an XML file to describe dependencies, the setter injection is more readable.
In general, it is a good practice to use constructor injection for mandatory dependencies and use setter injection for optional dependencies.
53. What is the difference between DOM and SAX parser in Java?

Java Tricky Interview Questions and Answers, SAX and DOM Parsing

In Java, Document Object Model (DOM) parser loads the whole XML into memory and creates a tree based on DOM model. This helps it in quickly locating the nodes, and making a change in the structure of XML.
On the other hand, Simple API for XML (SAX) parser is an event based parser. It doesn’t load the whole XML into memory. Due to this reason DOM is faster than SAX but require more memory and is not suitable to parse large XML files.
54. Between Enumeration and Iterator, which one has better performance in Java?
Enumeration interface is a read-only interface. It has better performance than Iterator. It is almost twice as fast as compared to an Iterator. It also uses very less memory. Also Enumeration does not have remove() method.
On the other hand, Iterator interface is safer than Enumeration, since it can check whether a collection is modified or not during iteration.
If a collection is altered while an Iterator is iterating, then it throws ConcurrentModificationException.
55. What is the difference between pass by reference and pass by value?

Java Tricky Interview Questions and Answers, pass value vs pass references

Whenever an object is passed by value, it means that a copy of the object is passed. Even if changes are made to that object, it doesn’t affect the original value.
Whenever an object is passed by reference, it means that the actual object is not passed, rather a reference of the object is passed.
Therefore, any changes made by an external method, are also reflected in the actual object and its reference.
56. What are the different ways to sort a collection in Java?
The most popular way to sort a collection in Java is by calling Collections.sort() method. You can provide your custom Comparator to sort() method for sorting the data in your custom way.
The other way is to use a Sorted collection like TreeSet or TreeMap that stores the information in a sorted order and then you can convert it to a List.
57. Why Collection interface doesn’t extend Cloneable and Serializable interfaces?
Collection interface just specifies groups of objects known as elements. Each concrete implementation of a Collection can choose its own way of how to maintain and order its elements.
Some collections may allow duplicate keys, while other collections may not.
A lot of collection implementations have clone method. But many do not. It is not worthwhile to include it in all, since Collection is an abstract representation. What matters is the concrete implementation.
Cloning and serialization come into picture while doing concrete implementation. Therefore, the concrete implementations of collections should decide how they can be cloned or serialized.
58. What is the difference between a process and a thread in Java?
A process is simply an execution of a program.
A Thread is a single execution sequence within a process.
A process may contain multiple threads. A Thread is also called as a lightweight process.
59. What are the benefits of using an unordered array over an ordered array?
In an ordered array the search time has time complexity of O(log n). Whereas, in an unordered array, search time complexity is O (n). In an ordered array, the insert operation has a time complexity of O(n). Whereas, the insertion operation for an unordered array takes constant time of O(1).
Therefore, when we have more writes than reads, it is preferable to use an unordered array.
60. Between HashSet and TreeSet collections in Java, which one is better?
A HashSet is Implemented using a HashTable. Therefore, its elements are stored in a random order. The add(), remove(), and contains() methods of a HashSet have constant time complexity O(1).
A TreeSet is implemented using a tree data structure. The elements in a TreeSet are sorted in a natural order. Therefore, add(), remove(), and contains() methods have time complexity of O(logn).
So from performance perspective, HashSet has better performance than TreeSet. But if you want to store elements in a natural sorting order, then TreeSet is a better collection.
61. When does JVM call the finalize() method?
JVM instructs the Garbage Collector to call the finalize method, just before releasing an object from the memory. A programmer can implement finalize() method to explicitly release the resources held by the object. This will help in better memory management and avoid any memory leaks.
62. When would you use Serial Garabage collector or Throughput Garbage collector in Java?
The Serial Garbage collector is used for small applications that require heap memory upto 100 MB.
The Throughput Garbage collector is used in medium to large size Java applications.
63. In Java, if you set an object reference to null, will the Garbage Collector immediately free the memory held by that object?
No. JVM decides to run the Garbage Collector whenever it is low on memory. When Garbage Collector runs, it looks for objects that are available for garbage collection and then frees the memory associated with this object.
So just setting an Object reference null makes it eligible for Garbage Collection, but it does not immediately free the memory.
64. How can you make an Object eligible for Garbage collection in Java?

Object eligible for Garbage collection

To make an Object eligible for Garbage collection, just make sure that it is unreachable to the program in which it is currently defined / created / used. You can set the object reference to null and make sure no other object refers it. Once the object cannot be reached, Garbage Collection can clean it during the next run.
65. When do you use Exception or Error in Java? What is the difference between these two?
Throwable class is the superclass of Exception and Error classes in Java.
When you want to catch the exceptional conditions that your program can create or encounter, then use the Exception class or subclass of Exception.
When you come across situations that are unexpected then use Error class in Java. Also recovering from Error is not possible in most of cases. So it is better to terminate the program.
66. What is the advantage of PreparedStatement over Statement class in Java?
PreparedStatements are precompiled statements for database queries. Due to this their performance is much better. Also, we can reuse PreparedStatement objects with different input values to the same query. Where as, Statement class does not provide these features.
67. In Java, what is the difference between throw and throws keywords?
When we want to raise an exception in our code, we use the throw keyword with the name of the exception to be raised. Where as, throws keyword is used in method declaration. Throws keyword tells us the Exception that can be thrown by this method.
Any caller of this method should be prepared to expect this Exception.
Another minor difference is that throw is used only with one exception, but throws can be used with comma-separated list of multiple exceptions.
68. What happens to the Exception object after the exception handling is done?
Once the exception handling is complete, the Exception object is not reachable. Then it is garbage collected in the next run of Garbage Collector.
69. How do you find which client machine is sending request to your servlet in Java?
We can use the ServletRequest class to find the IP address or host name of the client machine.
There are methods getRemoteAddr() to get the IP address of the client machine and getRemoteHost() to get the host name of the client machine.
70. What is the difference between a Cookie and a Session object in Java?
Both Cookie and Session are used during communication between Client and Server. The Client can disable a Cookie. Due to which the Web server cannot send a cookie. But a client cannot disable a session. So a Session always works irrespective of any setting at the client side.
Also a Session can store any Java object. But the Cookie can only store small information in a String object.
71. Which protocol does Browser and Servlet use to communicate with each other?
HTTP protocol. The Browser and Servlet communicate with each other by using the HTTP protocol.
72. What is HTTP Tunneling?
There are many network communication protocols on the Internet.
But HTTP is the most popular among them. HTTP Tunneling is a technique in which HTTP or HTTPS protocol encapsulated the communication done by any other type of protocol. The masking of other protocol requests as HTTP requests is known as HTTP Tunneling.
73. Why do we use JSP instead of Servlet in Java?
Since JSP pages are dynamically compiled into servlets, the programmers can easily make updates to the presentation layer code. For better performance, JSP pages can be pre-compiled. Also JSP pages provide flexibility to combine static templates like HTML or XML snippets.
In addition, programmers can make logic changes at the class level, without editing the JSP pages that use the class logic.
74. Is empty ‘.java’ file name a valid source file name in Java?
Yes. You can create a class and store it in a file with name .java.
You can try it yourself, by creating, compiling and running such a file. It will run correctly.
75. How do you implement Servlet Chaining in Java?
To implement, Servlet Chaining, there has to be more than one servlet. The output of one servlet has to be sent to a second servlet.
The output of the second servlet can be sent to a third servlet, and so on. In this way, a chain of servlets is formed to complete a task.
The last servlet in the chain will be responsible for sending final response to client.
76. Can you instantiate this class?

No, this class cannot be instantiated, since it will result in recursively calling its constructor.
77. Why Java does not support operator overloading?
Java supports Method overloading but does not support operator overloading. It would make the design more complex by adding operator loading. Also it will make more complex compiler.
One more reason is that, it will reduce the performance of JVM by operator overloading, since JCM has to do extra work to find the real meaning of overloaded operators at run time.
78. Why String class is Immutable or Final in Java?
Since String objects are cached in a String pool, it makes sense to make the String immutable. The cached String literals are shared between multiple clients. And there is a possibility that one client’s action may affect another client’s access to String pool.
String is also used as a parameter in many Java classes. Eg. You can pass hostname, port number as String while opening a network connection. If any one can modify your copy of the String, it can change the hostname. Due to this reason, it makes sense to make String final as soon as it is created.
79. What is the difference between sendRedirect and forward methods?
When you use sendRedirect method, it creates a new request. When you use the forward method, it just forwards a request to a new target.
In case of sendRedirect, the previous request scope objects are not available, because it creates a new request.
In case of forward method, the previous request scope objects are available after forwarding.
Also the sendRedirect method is considered slower than the forward method.
80. How do you fix your Serializable class, if it contains a member that is not serializable?
If you want to make a class Serializable, but find that this class contains members that are not Serializable, then you have to mark those members as transient. This will ensure that this member is not
persisted to a stream of bytes during Serialization. Therefore, Transient keyword of Java comes to help in this scenario.
81. What is the use of run time polymorphism in Java?
During the run time the behavior of an Object can change based on its run time state. Due to this run time polymorphism is introduced in Java. If you override a method in a child class, then you are providing run time polymorphism. Nothing will happen at the compile time. But at the run time, JVM decides which method will be called based on the class of the Object.
82. What are the rules of method overloading and method overriding in Java?
When we want to overload a method, we need to make sure that the method name remains same. But method signature can vary in the number or datatype of arguments or in the order of arguments.
When we want to override a method, we ensure that the method is not throwing checked exceptions that are new or higher than those declared by the overridden method. Also we make sure that the method name, arguments and return type remain the same. Also we cannot override Static and Final methods in Java.
83. What is the difference between a class and an object in Java?
A Class is a template or a blue print of an Object to be created. An Object is an instance of a Class. A Class defines the methods and member variables. But an Object populates the values of the member variables.
Therefore a class is a blueprint that you use to create objects. An object is an instance of a class – it is a concrete ‘thing’ that you made using a specific class. Most of the OOPS concepts are valid only when an Object is created.
In my opinion, this is the common question in the series of Java Tricky Interview Questions and Answers.
84. Can we create an abstract class that extends another abstract class?
Yes. An abstract class can extend another abstract class. It does not need to define the methods of parent abstract class. Only the last non-abstract class has to define the abstract methods of a parent abstract class.
85. Why do you use Upcasting or Downcasting in Java ?
When we want to cast a Sub class to Super class, we use Upcasting.
It is also known as widening. Upcasting is always allowed in Java.
When we want to cast a Super class to Sub class, we use Downcasting. It is also known as narrowing.
At times, Downcasting can throw the ClassCastException if it fails the type check.
86. What is the reason to organize classes and interfaces in a package in Java?
As the name suggests, a package contains a collection of classes. It helps in setting the category of a file. Like- whether it is a Data Access Object (DAO) or an API.
It helps in preventing the collision of Name space.
Also we can introduce access restriction by using package and the right modifiers on a class and its methods.
87. What is information hiding in Java?
Information hiding is OOPS concept. In Java you can use encapsulation to do Information hiding. An object can use the access modifiers like-public, private, protected to hide its internal details from another object. This helps in decoupling the internal logic of an object from outside world.
By using Information hiding, an object can change its internal implementation without impacting the outside calling client’s code.
88. Why does Java provide default constructor?
In Java all the interaction takes place between Object instances. To create an Object instance, JVM needs a constructor. Java does not enforce the rule on a programmer to define a default constructor for every class.
Whenever an object has to be created and programmer has not provided a constructor, Java uses default constructor to create the object. Default constructor also initializes member variables with their default values.
89. What is the difference between super and this keywords in Java?
We use super keyword to access the methods of the super class from child class.
We use this keyword to access methods of the same class.
90. What is the advantage of using Unicode characters in Java?
Unicode characters have much larger number of characters in the specification.
They also contain Asian and non-western European characters.
Most of the modern technologies, websites and browsers support these Unicode characters.
91. Can you override an overloaded method in Java?
Yes. Java allows to override an overloaded method, if that method is not a static or final method.
92. How can we change the heap size of a JVM?
Java provides the command line parameters to set the heap size for JVM.
You can specify the values in –Xms and –Xmx parameters. These parameters stand for initial and maximum heap size of JVM.
93. Why should you define a default constructor in Java?
In general, Java provides a default constructor with each class. But there are certain cases when we want to define our own version of default constructor.
When we want to construct an object with default values, we create our default constructor.
At times, we can mark the default constructor private. So that any other class cannot create an instance of our class. This technique is generally used in Singleton design pattern.
94. How will you make an Object Immutable in Java?
To make an object immutable follow these two rules. One, do not use any setter methods that can change the fields of your class. Two, make the fields final. By following these rules, the member variables cannot be changed after initialization. This will ensure that member variables of an Object do not change. And thus the Object will be considered Immutable.
95. How can you prevent SQL Injection in Java Code?
In Java, you can use PreparedStatement to prevent SQL injection. In a PreparedStatement you can pass the precompiled SQL queries with pre-defined parameters. This helps in checking the type of parameters to SQL queries. So it protects your code from SQL injection attacks.
96. Which two methods should be always implemented by HashMap key Object?
Any object that we want to use as key for HashMap or in any other hash based collection data structure e.g. Hashtable, or ConcurrentHashMap must implement equals() and hashCode() method.
97.Why an Object used as Key in HashMap should be Immutable?
The Key object should be immutable so that hashCode() method always return the same value for that object.
The Hashcode returned by hashCode() method depends on values of member variables of an object. If an object is mutable, then the member variables can change. Once the member variables change, the Hashcode changes. If the same object returns different hash code at different times, then it is not reliable to be used in the HashMap.
Let say, when you insert the object, the Hashcode is X, the HashMap will store it in bucket X. But when you search for it the Hashcode is Y, then HashMap will look for the object in bucket Y.
So you are not getting what you stored. To solve this, a key object should be immutable. Although, the compiler does not enforce this rule, a good programmer always remembers this rule.
98. How can we share an object between multiple threads?
There are many ways to share same object between multiple threads. You can use a BlockingQueue to pass an object from one thread to another thread.
You can also use Exchanger class for this purpose. An Exchanger is a bidirectional form of a SynchronousQueue in Java. You can use it to swap the objects as well.
99. How can you determine if your program has a deadlock?
If we suspect that our application is stuck due to a Deadlock, then we just take a thread dump by using the command specific to environment in which your application is running. Eg. In Linux you can use command kill -3.
In case of deadlock, you will see in thread dump the current status and stack trace of threads in the JVM, and one or more of them will be stuck with message deadlock.
Also you can do this programmatically by using the ThreadMXBean class that ships with the JDK.
If you don’t need programmatic detection you can do this via JConsole. On the thread tab there is a “detect deadlock” button.

That’s part 2 in series of Java Tricky Interview Questions and Answers. Continue to reading the 100 Java Tricky Interview Questions and Answers (Part 1)

Leave a Comment


Please share it if you found this useful
Hide Buttons