1. Is there any difference between a = a + b and a += b expressions?
When we add two integral variables e.g. variables of type byte, short, or int in Java, then they are first promoted to int type, and then addition happens.
The += operator implicitly casts the result of addition into the type of variable used to hold the result.
What happens when you put return statement or System.exit () on try or catch block? Will finally block execute?
It is a popular tricky Java interview question. Most of the programmers think that no matter what the finally block will always execute. This question challenges that concept by putting a return statement in the try or catch block or calling System.exit() from try or catch block.
You can answer by saying that finally block executes even if we put a return statement in the try block or catch block. But finally block does not execute if you call System.exit() from try or catch block.
2. What does the expression 1.0 / 0.0 return? Will there be any compilation error?
Double class is the source of many tricky interview questions. You may know about the double primitive type and Double class. But while doing floating point arithmetic some people don’t pay enough attention to Double.INFINITY, NaN, and -0.0. There are rules that govern the floating point arithmetic calculations involving Double.
The answer to this question is that 1.0 / 0.0 will compile successfully. And it will not throw ArithmeticException. It will just return Double.INFINITY.
3. Can we use multiple main methods in multiple classes?
Yes. When we start an application in Java, we just mention the class name to be run to java command. The JVM looks for the main method only in the class whose name is passed to java command.
Therefore, there is no conflict amongst the multiple classes having main method.
4. Does Java allow you to override a private or static method?
The question is tricky but the answer is very simple. You cannot override a private or static method in Java. If we create a similar method with same return type and same method arguments in child class, then it will hide the superclass method. This is known as method hiding.
Also, you cannot override a private method in sub class because Private method is not visible even in a subclass. Therefore, what you can do is to create another private method with the same name in the child class.
So in both the cases, it is not method overriding. It is either method hiding or a new method.
5. What happens when you put a key object in a HashMap that is already present?
In a HashMap there are buckets in which objects are stored. Key objects with same HashCode go to same bucket.
If you put the same key again in a HashMap, then it will replace the old mapping because HashMap doesn’t allow duplicate keys. The same key will have same HashCode as previous key object. Due to same HashCode, it will be stored at the same position in the bucket.
6. How can you make sure that N threads can access N resources without deadlock?
This question checks your knowledge of writing multi-threading code. If you have experience with deadlock and race conditions, you can easily answer this.
The answer is that by resource ordering you can prevent deadlock.
If in our program we always acquire resources in a particular order and release resources in the reverse order, then we can prevent the deadlock.
So a thread waiting for same resource can not get into deadlock while the other thread is trying to get it and holding the resource required by first thread. If both of them release the resources in right
order, one of them can acquire it to finish the work.
7.How can you determine if JVM is 32-bit or 64-bit from Java Program?
We can find JVM bit size 32 bit or 64 bit by running java command from the command prompt. Or we can get it from Java program.
Sun has a Java System property to determine the bit size of the JVM: 32 or 64:
sun.arch.data.model=32 // 32 bit JVM
sun.arch.data.model=64 // 64 bit JVM
We can use System.getProperty(“sun.arch.data.model”) to determine if it is 32/64 bit from Java program.
8. What is the right data type to represent Money (like Dollar/Pound) in Java?
To represent money you need decimal points in the numbers like $1.99.
BigDecimal class provides good methods to represent Money.
Using BigDecimal, we can do the calculation with decimal points and correct rounding. But using BigDecimal is a little bit high on memory usage.
We can also use double with predefined precision. But calculation on double can give erroneous results.
9. How can you do multiple inheritances in Java?
This is a question to trick people coming from C++ and Scala background to Java. There are many Object Oriented languages that support multiple inheritances. But Java is not one of them.
Answer of this question can be that, Java does support multiple inheritances of by allowing an interface to extend other interfaces.
You can implement more than one interface. But you cannot extend multiple classes. So Java doesn’t support multiple inheritances of implementation.
But in Java 8, the default method breaks the rule of multiple inheritances behavior.
10. Is ++ operation thread-safe in Java?
No, ++ operator is not a thread safe operation. It involves multiple instructions like- reading a value, incrementing it and storing it back into memory. These instructions can overlap between multiple
threads. So it can cause issues in multi-threading.
11. How can you access a nonstatic variable from the static context?
We cannot access a non-static variable from the static context in Java. If you write a code like that, then you will get compile time error. It is one of the most common problems for beginner Java programmers, when they try to access instance variable inside the main method in a class.
Since main method is static in Java, and instance variables are nonstatic, we cannot access instance variable inside main. The solution is to create an instance of the object and then access the instance
12. Let say there is a method that throws NullPointerException in the superclass. Can we override it with a method that throws RuntimeException?
This question is checking your understanding of the concepts of method overloading and overriding in Java.
We can throw superclass of RuntimeException in an overridden method, but we cannot do the same if it is a checked Exception.
13. How can you mark an array volatile in Java?
If you know multi-threading well then you can easily answer it.
We can mark an array volatile in Java. But it makes only the reference to array volatile, not the whole array.
If one thread changes the reference variable to point to another array, then it will provide a volatile guarantee. But if multiple threads are changing individual array elements, they won’t be having same reference due to the reference itself being volatile.
14. What is a thread local variable in Java?
Thread-local variable is a variable restricted to a specific thread. It is like thread’s own copy of variable that is not shared among multiple threads.
Java provides ThreadLocal class to support thread-local variables.
To achieve thread-safety, you can use it. To avoid any memory leak, it is always good to remove a thread-local variable, once its work is done.
15. What is the difference between sleep() and wait() methods in Java?
In Java, we use these methods to pause currently running thread.
There is a simple difference between these.
sleep() is actually meant for short pause because it doesn’t release lock.
wait() is meant for conditional wait and it can release a lock that can be acquired by another thread to change the condition on which it is waiting.
16. Can you create an Immutable object that contains a mutable object?
In Java, it is possible to create an Immutable object that contains a mutable object.
We should not share the reference of the mutable object, since it is inside an immutable object. Instead, we can return a copy of it to other methods.
17. How can you convert an Array of bytes to String?
You can convert an Array of bytes to String object by using the String constructor that accepts byte. We need to make sure that right character encoding is used. Else we may get different results after conversion.
18. What is difference between CyclicBarrier and CountDownLatch class?
CyclicBarrier and CountDownLatch classes were introduced from Java 5.
We can reuse CyclicBarrier even if it is broken, but we cannot reuse CountDownLatch in Java.
19. What is the difference between StringBuffer and StringBuilder?
StringBuilder was introduced in Java 5. The main difference between both of them is that StringBuffer methods e.g. length(), capacity(), append() are synchronized. But corresponding methods in StringBuilder are not synchronized.
Due to this difference, concatenation of String using StringBuilder is faster than StringBuffer. Now it is considered bad practice to use StringBuffer, because, in most of the scenarios, we perform string
concatenation in the same thread.
20. Which class contains clone method? Cloneable or Object class?
It is a very basic trick question. clone() method is defined in Object class. Cloneable is a marker interface that doesn’t contain any method.
21. How will you take thread dump in Java?
There are platform specific commands to take thread dump in Java.
In Linux/Unix, just use kill -3 PID, where PID is the process id of Java process. It will give the thread dump of Java process.
In Windows, press Ctrl + Break. This will instruct JVM to print thread dump in standard out or err. It can also go to console or log file depending upon your application configuration.
22. Can you cast an int variable into a byte variable? What happens if the value of int is larger than byte?
An int is 32 bit in Java. But a byte is just 8 bit in Java. We can cast an int to byte. But we will lose higher 24 bits of int while casting. Because a byte can hold only first 8 bits of int. Remaining 24 bits
(32-8 = 24) will be lost.
23. In Java, can we store a double value in a long variable without explicit casting?
No, we cannot store a double value into a long variable without casting it to long. The range of double is more than that of long. So we need to type cast.
To answer this question, just remember which one is bigger between double and long in Java.
24. What will this return 5*0.1 == 0.5? true or false?
The answer is false because floating point numbers can not be represented exactly in Java, so 5*0.1 is not same as 0.5.
25. Out of an int and Integer, which one takes more memory?
An Integer object takes more memory than an int in Java. An Integer is an object and it stores meta-data overhead about the object. An int is a primitive type so its takes less memory and there is no metadata overhead.
26. Can we use String in the switch case statement in Java?
Yes. From Java 7 onwards, String can be used in switch case statement. This gives convenience to programmer. But internally hash code of String is used for the switch statement.
27. Can we use multiple main methods in same class?
Yes. You can have multiple methods with name main in the same class. But there should be only one main method with the signature public static void main(String args). JVM looks for main with this
signature only. Other methods with name main in same class are just ignored.
28. When creating an abstract class, is it a good idea to call abstract methods inside its constructor?
No, we should avoid calling abstract methods in the constructor of an abstract class. Because, it can restrict how these abstract methods can be implemented by child classes.
Many IDE give “Overridable method call in constructor” warning for such implementation.
This is a problem of object initialization order. The superclass constructor will run before the child class constructor. It means child class is not yet initialized. But due to presence of overridden method in superclass, the overridden method of subclass is called when the subclass is not fully initialized.
29. How can you do constructor chaining in Java?
When we call one constructor from another constructor of the same class, then it is known as constructor chaining in Java. When you have multiple overloaded constructors in a class, you can do constructor chaining.
30. How can we find the memory usage of JVM from Java code?
We can use memory management related methods provided in java.lang.Runtime class to get the free memory, total memory and maximum heap memory in Java.
By using these methods, you can find out how much of the heap is used and how much heap space still remains.
Runtime.freeMemory() returns amount of free memory in bytes.
Runtime.totalMemory() returns total memory in bytes.
Runtime.maxMemory() returns maximum memory in bytes.
31. What is the difference between x == y and x.equals(y) expressions in Java?
The x == y expression does object reference matching if both a and b are an object and only returns true if both are pointing to the same object in the heap space.
The x.equals(y) expression is used for logical mapping and it is expected from an object to override this method to provide logical equality.
Eg. A Book object may be logically equal to another copy of same
Book, but it is a different object which will be false while doing x == y.
32. How can you guarantee that the garbage collection takes place?
No. We cannot guarantee the garbage collection in Java. Java documentation explicitly says that GarbageCollection is not guaranteed.
You can call System.gc() to request garbage collection, however, that’s what it is – a request. It is upto GC’s discretion to run.
33. What is the relation between x.hashCode() method and x.equals(y) method of Object class?
x.hashCode() method returns an int hash value corresponding to an object instance.
It is used in hashCode based collection classes like Hashtable, HashMap, LinkedHashMap etc.hashCode() method is also related to equals() method.
As per Java specification, two objects which are equal to each other using equals() method must have same hash code.
Therefore, two objects with same hashCode may or may not be equal to each other. But two equal objects should have same hash code.
34. What is a compile time constant in Java?
A compile time constant is public static final variable. The public modifier is optional here. At compile time, they are replaced with actual values because compiler knows their value up-front and it also knows that it cannot be changed during run-time. So they are constants.
35. Explain the difference between fail-fast and fail-safe iterators?
The main difference between fail-fast and fail-safe iterators is whether or not the collection can be modified while it is being iterated.
Fail-safe iterators allow modification of collection in an iteration task. But fail-fast iterators do not allow any modification to collection during iteration.
During iteration, fail-fast iterators fail as soon as they realize that the collection has been modified. Modification can be addition, removal or update of a member. And it will throw a ConcurrentModificationException.
Eg. ArrayList, HashSet, and HashMap are fail-fast.
Fail-safe iterators operate on a copy of the collection. Therefore they do not throw an exception if the collection is modified during iteration.
Eg. ConcurrentHashMap, CopyOnWriteArrayList are fail-safe.
36. You have a character array and a String. Which one is more secure to store sensitive data (like
password, date of birth, etc.)?
Short answer is, it is safe to store sensitive information in character array.
In Java, String is immutable and it is stored in the String pool. Once a String is created, it stays in the pool in memory until it is garbage collected. You have no control on garbage collection. Therefore, anyone having access to a memory dump can potentially extract the sensitive data and use it.
Whereas, if you use a mutable object like a character array, to store the value, you can set it to blank once you are done with it. Once it is made blank it cannot be used by anyone else.
37. Why do you use volatile keyword in Java?
The volatile keyword guarantees global ordering on reads and writes to a variable. This implies that every thread accessing a volatile field will read the variable’s current value instead of using a cached value.
By marking the variable volatile, the value of a variable is never cached thread-locally. All reads and writes will go straight to main memory of Java.
38. What is the difference between poll() and remove() methods of Queue in Java?
It is a basic question to know the understanding of Queue data structure. Both poll() and remove() methods remove and return the head of the Queue.
When Queue is empty, poll() method fails and it returns null, but remove() method fails and throws Exception.
39. Can you catch an exception thrown by another thread in Java?
Yes, it can be done by using Thread.UncaughtExceptionHandler.
Java Documentation says “When a thread is about to terminate due to an uncaught exception the Java Virtual Machine will query the thread for its UncaughtExceptionHandler usingThread.getUncaughtExceptionHandler()
will invoke the handler’s uncaughtException method, passing the thread and the exception as arguments.”
40. How do you decide which type of Inner Class – Static or Non-Static to use in Java?
An inner class has full access to the fields and methods of the enclosing class. This is convenient for event handlers, but comes at a cost. Every instance of an inner class retains and requires a reference to its enclosing class.
Due to this cost, there are many situations where static nested classes are preferred over inner classes. When instances of the nested class outlive instances of the enclosing class, the nested class should be static to prevent memory leaks. At times, due to their “hidden” reference to enclosing class, Inner classes are harder to construct via reflection.
41. What are the different types of Classloaders in Java?
Java Classloader is the part of the Java Runtime Environment (JRE) that loads classes on demand into Java Virtual Machine (JVM).
When the JVM is started, three types of class loaders are used:
Classes may be loaded from the local file system, a remote file system, or even the web.
42. What are the situations in which you choose HashSet or TreeSet?
HashSet is better than TressSet in almost every way. It gives O(1) for add(), remove() and contains() operations. Whereas, TressSet gives O(log(N)) for these operations.
Still, TreeSet is useful when you wish to maintain order over the inserted elements or query for a range of elements within the set.
We should use TreeSet when we want to maintain order. Or when there are enough read operations to offset the increased cost of write operations.
43. What is the use of method references in Java?
Java 8 has introduced Method references. It allows constructors and methods to be used as lambdas.
The main uses of Method reference are to improve code organization, clarity and terseness.
44. Do you think Java Enums are more powerful than integer constants?
Yes. Java Enums provide many features that integer constants cannot. Enums can be considered as final classes with a fixed number of instances. Enums can implement interfaces but cannot extend another class.
While implementing the strategy pattern, we can use this feature of Enums. Especially, when the number of strategies is fixed.
You can also attach meta-data to enum values in Java. Also enum values are typesafe, where as integer constants are not.
You can also define custom behavior in enum values.
45. Why do we use static initializers in Java?
In Java, a static initializer can run code during the initial loading of a class and it guarantees that this code will only run once. Also the static code will finish running before a class can be accessed in any way.
Initializing static members from constructors is more work. You have to make sure that every constructor does this. You need to maintain a flag to mark the static work when it is done. You may have to think about synchronization or races conditions for work in static block not initialized from static context.
46. Your client is complaining that your code is throwing NoClassDefFoundError or NoSuchMethodError, even though you are able to compile your code without error and method exists in your code. What could be the reason behind this?
Sometimes we upgrade our libraries even with same method name. But we forget to let the client know about the new version. Due this different in version, we get NoClassDefFoundError or NoSuchMethodError at runtime when one library was not compatible with such an upgrade.
Java build tools and IDEs can also produce dependency reports that tell you which libraries depend on that JAR. Mostly, identifying and upgrading the library that depends on the older JAR resolve the issue.
47. How can you check if a String is a number by using regular expression?
Regex is a powerful tool for matching patterns and searching patterns.
A numeric String can only contain digits i.e. 0 to 9. It can also contain + and – sign at start of the String. We can create a regular expression for these two rules. One simple example is as follows:
Pattern pattern = Pattern.compile(".*\\D.*");
48. What is the difference between the expressions String s = “Temporary” and String s = new
String(“Temporary “)? Which one is better and more efficient?
In general, String s = ” Temporary “ is more efficient to use than String s = new String(“Temporary “).
In case of String s = ” Temporary “, a String with the value “Temporary” is created in String pool. If another String with the same value is created (e.g., String s2 = ” Temporary “), it will reference the same object in the String pool.
But, when you use String s = new String(“Temporary “), Java creates a String with the value “Temporary” in the String pool.
Also, that String object is then passed to the constructor of the String Object i.e. new String(“Temporary “). And this call creates another String object (not in the String pool) with that value.
Therefore, each such call creates an additional String object. E.g. String s2 = new String(“Temporary “) creates an extra String object, rather than just reusing the same String object from the String pool. So String s = “Temporary” is always an efficient way.
49. In Java, can two equal objects have the different hash code?
No. It is not possible for two equal objects to have different hashcode. But two objects with same hashcode may or may not be equal.
50. How can we print an Array in Java?
We can print an array by using methods of Arrays class. We can either use Arrays.toString() method or we can use Arrays.deepToString() method.
Since array doesn’t implement toString() method by itself, just passing an array to System.out.println() will not print its contents. But we can use Arrays.toString() to print each element of an array.
Continue to reading the 100 Java Tricky Interview Questions and Answers (Part 2)