Top 20 Tricky Java interview questions and Answers
1) What is the difference between CyclicBarrier and CountDownLatch in Java
Relatively newer Java tricky question, only been introduced from Java 5. The main difference between both of them is that you can reuse CyclicBarrier even if Barrier is broken, but you can not reuse CountDownLatch in Java.
Difference between CountDownLatch and CyclicBarrier in Java
Both CyclicBarrier and CountDownLatch are used to implement a scenario where one Thread waits for one or more Thread to complete their job before starts processing but there is one difference between CountDownLatch and CyclicBarrierin Java which separates them apart and that is, you can not reuse same CountDownLatch instance once count reaches to zero and latch is open, on the other hand, CyclicBarrier can be reused by resetting Barrier, Once the barrier is broken.
A useful property of a CountDownLatch is that it doesn't require that threads calling countDown wait for the count to reach zero before proceeding, it simply prevents any thread from proceeding past an await until all threads could pass.
A CyclicBarrier supports an optional Runnable command that is run once per barrier point, after the last thread in the party arrives, but before any threads are released. This barrier action is useful for updating shared-state before any of the parties continue.
The CyclicBarrier uses a fast-fail all-or-none breakage model for failed synchronization attempts: If a thread leaves a barrier point prematurely because of interruption, failure, or timeout, all other threads, even those that have not yet resumed from a previous await(), will also leave abnormally via BrokenBarrierException (or InterruptedException if they too were interrupted at about the same time).
Difference between CountDownLatch and CyclicBarrier in Java concurrency:
That's all about the difference between CountDownLatch and CyclicBarrier in Java. As I said, the key difference is that you can reuse CyclicBarrier but CountDownLatch cannot be reused once count down reaches zero. That's why CyclicBarrier is often used when a task is repeated while CountDownLatch is used for a one-time task like loading initial cache before start accepting client connections.
2). Can we use multiple main methods?
Yes. While starting the application we mention the class name to be run. The JVM will look for the main method only in the class whose name you have mentioned. Hence there is no conflict amongst the multiple classes having the main method.
We can overload the main method but we can not override it. So, we can have many main methods in a class.
3). Explain the difference between LinkedList and ArrayList.
ArrayList is an implementation of the List interface that is based on an array. ArrayList internally handles the resizing of this array when the elements are added or removed. You can access its elements in constant time by their index in the array. However, inserting or removing an element infers shifting all consequent elements which may be slow if the array is huge and the inserted or removed element is close to the beginning of the list.
LinkedList is a doubly-linked list: single elements are put into Node objects that have references to previous and next Node. This implementation may appear more efficient than ArrayList if you have lots of insertions or deletions in different parts of the list, especially if the list is large.
In most cases, however, ArrayList outperforms LinkedList. Even elements shifting in ArrayList, while being an O(n) operation, is implemented as a very fast System.arraycopy() call. It can even appear faster than LinkedList‘s O(1) insertion which requires instantiating a Node object and updating multiple references under the hood. LinkedList also can have a large memory overhead due to the creation of multiple small Node objects.
4). If a method throws NullPointerException in the superclass, can we override it with a method that throws RuntimeException?
One more tricky Java questions from the overloading and overriding concept. The answer is you can very well throw superclass of RuntimeException in overridden method, but you can not do the same if its checked Exception.
5). What does the expression 1.0 / 0.0 will return? will it throw Exception? any compile-time error?
This is another tricky question from Double class. Though Java developer knows about the double primitive type and Double class, while doing floating-point arithmetic they don't pay enough attention to Double.INFINITY, NaN, and -0.0 and other rules that govern the arithmetic calculations involving them. The simple answer to this question is that it will not throw ArithmeticExcpetion and return Double.INFINITY.
6). What will happen if we put a key object in a HashMap which is already there?
This tricky Java question is part of another frequently asked question, How HashMap works in Java. HashMap is also a popular topic to create a confusing and tricky question in Java. The answer to this question is if you put the same key again then it will replace the old mapping because HashMap doesn't allow duplicate keys. The Same key will result in the same hashcode and will end up in the same position in the bucket.
7). What will happen if you put a return statement or System.exit () on try or catch block? Will finally block execute?
This is a very popular tricky Java question and it's tricky because many programmers think that no matter what, but the finally block will always execute. This question challenge that concept by putting a return statement in the try or catch block or calling System.exit() from try or catch block.
The answer to this tricky question in Java is that finally block will execute even if you put a return statement in the try block or catch block but finally block won't run if you call System.exit() from try or catch block.
8). What does the expression 1.0 / 0.0 will return? will it throw Exception? any compile-time error?
This is another tricky question from Double class. Though Java developer knows about the double primitive type and Double class, while doing floating-point arithmetic they don't pay enough attention to Double.INFINITY, NaN, and -0.0 and other rules that govern the arithmetic calculations involving them. The simple answer to this question is that it will not throw ArithmeticExcpetion and return Double.INFINITY.
Also, note that the comparison x == Double. NaN always evaluates to false, even if x itself is a NaN. To test if x is a NaN, one should use the method call Double.isNaN(x) to check if the given number is NaN or not. If you know SQL, this is very close to NULL there.
9). Is it Possible to Create Object or Instance of an Abstract class in Java?
No, you cannot instantiate an abstract class in Java because it is abstract, it is not complete hence it cannot be used.
When you create an instance of a class, its's constructor is called, and even though abstract class can have a constructor, the compiler will not allow you to create an instance of the class. It's a compile-time error to create an instance of an abstract class in Java.
No, you cannot create an instance of an Abstract class in Java? Let's see some code examples to prove this point that it's illegal to create an instance of an object of an abstract class in Java. This example throws a compile-time error to indicate that it's not possible. The error message is not very clear, but it does say that "Cannot Instantiate The Type Hello. Nested", which effectively says that you cannot create an instance of an abstract class in Java.
/* * Java Program to prove that you cannnot * create instance of an abstract class * in Java. even though you can define * constructor. */
public class Hello {
public static void main(String[] args)
{
Nested n = new Nested();
}
abstract class Nested {
public Nested(){
System.out.println("No-argument default constructor");
}
}
When you compile this class using javac on the command line or just type the code in Eclipse IDE, you will see following compile-time error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: At tool.Hello.main(Hello.java:15)
You can see that even though you can declare constructor inside an abstract class, as soon as you try to instantiate an abstract class, the compiler is throwing "Cannot instantiate the type Hello. Nested" error.
This is true for both top-level and nested abstract class in Java, you cannot extend any of them.
10). Can you access a non-static variable in the static context?
Another tricky Java question from Java fundamentals. No, you can not access a non-static variable from the static context in Java. If you try, it will give a compile-time error. This is actually a common problem beginner in Java face when they try to access the instance variable inside the main method. Because the main is static in Java, and instance variables are non-static, you can not access the instance variable inside the main.
The static variable in Java belongs to Class and its value remains the same for all instances. static variable initialized when class is loaded into JVM on the other hand instance variable has a different value for each instance and they get created when an instance of an object is created either by using the new() operator or using reflection like Class.newInstance().
So if you try to access a non-static variable without any instance compiler will complain because those variables are not yet created and they don't have any existence until an instance is created and they are associated with any instance. So in my opinion, the only reason which makes sense to disallow non-static or instance variable inside static context is the non-existence of instance.
In summary since code in static context can be run even without creating an instance of a class, it does not make sense asking value for a specific instance that is not yet created.
You can still access any non-static variable inside any static method or block by creating an instance of the class in Java and using that instance to reference the instance variable. This is the only legitimate way to access non-static variables in the static context. here is a code example of accessing non-static variable inside a static context:
private int count=0; public static void main(String args[]) throws IOException { StaticTest test = new StaticTest(); //accessing static variable by creating an instance of class test.count++; } }
public class StaticTest {
So next time if you get compiler error “non-static variable cannot be referenced from a static context” access static member by creating an instance of Class. Let me know if you find any other reason on why non-static variable cannot be referenced from a static context.
11). What is the difference when String is gets created using a literal or new() operator?
When we create a string with new() its created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.
12). Does Java support multiple inheritances?
This is the trickiest question in Java if C++ can support direct multiple inheritances than why not Java is the argument Interviewer often give.
The answer of this question is much more subtle then it looks like, because Java does support multiple inheritances of Type by allowing an interface to extend other interfaces, what Java doesn't support is multiple inheritances of implementation. This distinction also gets blur because of the default method of Java 8, which now provides Java, multiple inheritances of behavior as well.
1) The first reason is ambiguity around Diamond problem, consider a class A has foo() method and then B and C derived from A and has there own foo() implementation and now class D derives from B and C using multiple inheritances and if we refer just foo() compiler will not be able to decide which foo() it should invoke.
This is also called Diamond problem because the structure on this inheritance scenario is similar to 4 edge diamond, see below
In my opinion even if we remove the top head of diamond class A and allow multiple inheritances we will see this problem of ambiguity.
Some times if you give this reason to the interviewer he asks if C++ can support multiple inheritances than why not Java. In that case I would try to explain to him the second reason which I have given below that it's not because of technical difficulty but more to maintainable and clearer design was driving factor though this can only be confirmed by any of java designer and we can just speculate. Wikipedia link has some good explanation on how different language address problem arises due to diamond problem while using multiple inheritances.
2) Second and more convincing reason to me is that multiple inheritances does complicate the design and creates problem during casting, constructor chaining, etc and given that there are not many scenarios on which you need multiple inheritances its wise decision to omit it for the sake of simplicity.
Also, java avoids this ambiguity by supporting single inheritance with interfaces. Since the interface only has a method declaration and doesn't provide any implementation there will only be just one implementation of a specific method hence there would not be any ambiguity.
13). Can you override a private or static method in Java?
Another popular Java tricky question, As I said method overriding is a good topic to ask trick questions in Java. Anyway, you can not override a private or static method in Java, if you create a similar method with the same return type and same method arguments in child class then it will hide the superclass method, this is known as method hiding. Similarly, you cannot override a private method in subclass because it's not accessible there, what you do is create another private method with the same name in the child class. See you cannot override static method in Java for more details.
14). What will happen if you put a return statement or System.exit () on try or catch block? Will finally block execute?
This is a very popular tricky Java question and it's tricky because many programmers think that no matter what, but the finally block will always execute. This question challenge that concept by putting a return statement in the try or catch block or calling System.exit() from try or catch block.
The answer to this tricky question in Java is that finally block will execute even if you put a return statement in the try block or catch block but finally block won't run if you call System.exit() from try or catch block.
15). How HashMap works internally in Java?
HashMap in Java works on hashing principle. It is a data structure which allows us to store object and retrieve it in constant time O(1) provided we know the key. In hashing, hash functions are used to link key and value in HashMap. Objects are stored by calling put(key, value) method of HashMap and retrieved by calling get(key) method. When we call put method, the hashcode() method of the key object is called so that the hash function of the map can find a bucket location to store value object, which is actually an index of the internal array, known as the table.
HashMap internally stores mapping in the form of Map.Entry object which contains both key and value object. When you want to retrieve the object, you call the get() method and again pass the key object. This time again key objects generate the same hash code (it's mandatory for it to do so to retrieve the object and that's why HashMap keys are immutable e.g. String) and we end up at the same bucket location.
If there is only one object then it is returned and that's your value object which you have stored earlier. Things get a little tricky when collisions occur. It's easy to answer this question if you have read a good book or course on data structure and algorithms like this one. If you know how the hash table data structure works then this is a piece of cake.
Since the internal array of HashMap is of fixed size, and if you keep storing objects, at some point of time hash function will return the same bucket location for two different keys, this is called collision in HashMap. In this case, a linked list is formed at that bucket location and a new entry is stored as next node.
If we try to retrieve an object from this linked list, we need an extra check to search correct value, this is done by equals() method. Since each node contains an entry, HashMap keeps comparing entry's key object with the passed key using equals() and when it returns true, Map returns the corresponding value.
Since searching inlined list is O(n) operation, in worst case hash collision reduce a map to linked list. This issue is recently addressed in Java 8 by replacing the linked list to the tree to search in O(logN) time. By the way, you can easily verify how HashMap works by looking at the code of HashMap.java in your Eclipse IDE if you know how to attach source code of JDK in Eclipse.
16). What is the difference between StringBuffer and StringBuilder in Java?
Classic Java questions some people think tricky and some consider it very easy. StringBuilder in Java was introduced in JDK 1.5 and the only difference between both of them is that StringBuffer methods e.g. length(), capacity(), or append() are synchronized while corresponding methods in StringBuilder are not synchronized href.
Because of this fundamental difference, the concatenation of String using StringBuilder is faster than StringBuffer. Actually, it's considered a bad practice to use StringBuffer anymore, because, in almost 99% of scenarios, you perform string concatenation on the same thread.
StringBuffer is very good with mutable String but it has one disadvantage all its public methods are synchronized which makes it thread-safe but at the same time slow. In JDK 5 they provided a similar class called StringBuilder in Java which is a copy of StringBuffer but without synchronization. Try to use StringBuilder whenever possible it performs better in most of cases than the StringBuffer class.
You can also use "+" for concatenating two strings because the "+" operation is internally implemented using either StringBuffer or StringBuilder in Java. If you see StringBuilder vs StringBuffer you will find that they are exactly similar and all API methods applicable to StringBuffer are also applicable to StringBuilder in Java.
- The first and most significant difference between String and StringBuffer in Java is that String is immutable in Java while StringBuffer is mutable. What this means is, performing any operation on String will create a new String object while modifying the StringBuffer object won't create a new object.
- If you are using + operator for concatenating multiple String then you should not be worried much because based upon Java implementation call to the + operator is replaced with either StringBuffer or StringBuilder based upon JVM implements Java 1.5 or lower version .
- StringBuffer.append()method is used to perform String concatenation in Java.
- Creating StringBuffer from String is easy, as StringBuffer accepts a String input. Similarly converting StringBuffer to String is also easy by using the toString() method in Java.
- Another significant difference between String and StringBuffer is that StringBuffer and String do not share the same type of hierarchy, which means you can not cast String to StringBuffer in Java. any such attempt will result in ClassCastException in Java.
Many types: 1. Stack 2. Heap 3. Native Method Stack 4. Program Counter Register 5. Class(Method) Area
18). What is the distinction between JDK, JRE, and JVM?
- JRE JRE stands for Java Runtime Environment and it is one of the procedures of JVM
- JVM JVM stands for Java Virtual Machine and the execution of Java byte code which is aided by the abstract machine by providing the runtime environment.
- JDK JDK stands for Java Development Kit and it exists physically and it consists of JRE + development tools.
19). What is the reflection and why is it useful?
The name reflection is used to describe code that can inspect other code in the same system (or itself).
For example, say you have an object of an unknown type in Java, and you would like to call a 'doSomething' method on it if one exists. Java's static typing system isn't really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called 'do something' and then calls it if you want to.
So, to give you a code example of this in Java (imagine the object in question is foo) :
Method method = foo.getClass().getMethod("doSomething", null); method.invoke(foo, null); One very common use case in Java is the usage with annotations. JUnit 4, for example, will use reflection to look through your classes for methods tagged with the @Test annotation, and will then call them when running the unit test.
Uses of Reflection
Reflection is commonly used by programs that require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. With that caveat in mind, reflection is a powerful technique and can enable applications to perform operations that would otherwise be impossible.
Extensibility Features
An application may make use of external, user-defined classes by creating instances of extensible objects using their fully-qualified names. Class Browsers and Visual Development Environments A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code. Debuggers and Test Tools Debuggers need to be able to examine private members in classes. Test harnesses can make use of reflection to systematically call a discoverable set of APIs defined on a class, to ensure a high level of code coverage in a test suite.
Drawbacks of Reflection
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.
- Performance Overhead: Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts and should be avoided in sections of code which are called frequently in performance-sensitive applications.
- Security Restrictions: Reflection requires runtime permission which may not be present when running under a security manager. This is an important consideration for code that has to run in a restricted security context, such as in an Applet.
- Exposure of Internals: Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.
20). What is difference between Executor.submit() and Executer.execute() method ?
There is a difference when looking at exception handling. If your task throws an exception and if it was submitted with execute 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 any thrown exception, checked exception or not, is then part of the task's return status. For a task that was submitted with submit and that terminates with an exception, the Future.get will re-throw this exception, wrapped in an ExecutionException.
In this article we have seen Java interview questions and Answers
0 Comments
Post a Comment