Are you preparing for the Java interview? If Yes, then this blog is for you! We will fall short if we attempt to respond to a challenging topic using common sense because such questions need for specialised understanding. This blog helps you get to know the Top Tricky Java Interview Questions that are possibly asked for technical interviews. These interview questions are for freshers and experienced professionals.
Apps for the 15 billion Java-enabled devices are created by approximately 10 million developers worldwide using Java. Applications for common home items like mobile phones and DTH boxes are also developed using this technique. As a result, Java is widely used today!
With 6 FAQs, and 22 Tricky Java interview questions each for freshers and experienced, we’ve got a whole package to make you interview-ready! Keep reading to learn more!
Table of Contents:
Why is Java not capable of supporting multiple inheritances?
I found this fundamental Java question to be very challenging to respond to since, in most situations, the interviewer is seeking for particular points, and if you can provide them, they will be satisfied. The secret to answering a question of this difficulty in Java is to thoroughly prepare the subject to accommodate any follow-ups.
Gain comprehensive insights into Java Interview Questions and receive thorough clarification of your Core Java Training queries from our experienced trainers. |
Which two methods in the HashMap do you need to implement for the key Object?
Any object must implement the equals and hashcode methods in Java in order to be used as a Key in a HashMap.
The Hashing algorithm underlies HashMap. Understanding the terms Hash Function, Hash Value, and Bucket is the first step in understanding hashing.
Describe Immutable objects: What are they? Are immutable objects possible to write?
Java classes known as immutable classes prohibit object modification after creation. Any alteration to an immutable object produces a new object.
String, for instance, is immutable in Java. Most Java methods that are immutable are also final in order to prevent subclasses from overriding Java methods that would jeopardise immutability. Making members non-final but private and keeping them unchanged outside of constructors will give you the same functionality.
Why is a char array rather than a String chosen to store passwords in Java?
Here are a few plausible arguments for why character arrays are preferable to Strings for storing passwords in Java:
You should always use an encrypted password rather than a plain one since anyone with access to a memory dump can discover the password if it is in clear text. Due to Java Strings' immutability, it is impossible to change their contents because doing so would result in a new String. However, if you use char[], you can still set all of his elements to 0 or blank. Therefore, it is evident that storing the password as a character array reduces the security risk of password theft.
What distinguishes constructing a String as new() from doing it directly?
When we generate a string using the new() operator, it is created in the heap rather than the string pool, however when we build a string using a literal, it is created in the string pool, which is located in the PermGen part of the heap.
String s = new String("Test");
does not explicitly place the object in the String pool; instead, we must call the String.intern() method to do so. Only when a String object is created as a String literal.
For example: String s = "Test"
That was immediately added to the String pool by Java.
What distinguishes Java's StringBuilder and StringBuffer?
Classic Java issues that some people consider difficult and others quite simple. The main distinction between the two is that StringBuilder is not synchronised but StringBuffer methods are, and was first made available in Java version 5. For more distinctions, see StringBuilder vs. StringBuffer.
What distinguishes an ArrayList from a vector?
As resizable arrays used to implement the list interface, ArrayList and Vectors are both dynamic arrays.
The ArrayList class is part of the Java.util package and is a crucial component of the collection system. Because ArrayList can alter its size, it is often referred to as a dynamic array. An advantage for memory management is the ability to add and remove elements from an ArrayList depending on the need.
The vector in Java is comparable to a dynamic array that can change in size. The list interface is implemented using it. One of a vector's greatest advantages is that there is no size restriction, allowing us to store an unlimited number of elements. The ArrayList and Vectors are quite comparable, however the Vectors contain a number of old methods that are not included in the collection framework.
What is the difference between creating a String using the literal operator and the new() operator?
In contrast, strings created with literal are created in the String pool itself, which is located in the Perm section of the heap, strings created using new() are created in the heap rather than the string pool.
Describe Singleton. Is it better to synchronise the entire process or just the important parts?
A singleton class in Java is one that only has one instance throughout the whole Java application, such as java.lang. A Singleton class, runtime. Prior to Java 4, creating Singletons was difficult, but since Enum was introduced in Java 5, it became quite simple.
What distinguishes a factory pattern from an abstract factory pattern?
One further abstraction level is offered by Abstract Factory. Consider a number of factories that are all extensions of an Abstract Factor and in charge of producing various hierarchies of objects depending on the type of factory. For instance, UserFactory, AutomobileFactory, RoleFactory, etc. extended AbstractFactory. The production of items in that genre would be under the purview of each particular factory.
When writing stored procedures or using stored procedures from Java, how do you handle error conditions?
This is one of the difficult Java interview questions, and it's available to everyone. In my view, if an operation fails, a stored method should output an error code, but catching a SQLException is the sole option if the stored procedure itself fails.
What will occur if you call System or the return statement. egress on attempt or catch block? When block eventually executes?
This is a very common and challenging Java question since many programmers believe that finally blocks are always performed. By including a return statement in a try or catch block or by calling System, this inquiry challenges that idea. from the try or catch block, exit. The answer to this tough topic in Java is that finally blocks won't run if you call System, even if you include a return statement in a try or catch block. leave try or catch.
What distinguishes the Executor.submit() function from the method Executer.execute()?
When considering exception management, there is a distinction. If one of your tasks fails and it was submitted with the execute option, the exception will be handled by the uncaught exception handler (The default handler will just send the stack trace to System if you haven't specifically defined one. err). Any thrown exception, whether it was checked or not, becomes a part of the task's return status if you submitted the task with submit. For a job that was submitted with submit and ends with an exception, the Future.get will re-throw this exception, contained in an ExecutionException.
Can we replace a method that throws NullPointerException in a super class with a method that throws RuntimeException?
One more challenging overriding and overloading Java question. The answer is that you can throw RuntimeExceptions of the super class in overridden methods, but you cannot do the same if the exception is checked.
What exactly do you mean by thread safety? Why is it necessary? And finally, how can Java applications achieve thread safety?
The legal relationship between threads and memory in a real computer system is defined by the Java Memory Model. It sort of explains what actions are permitted in multi-threaded programmes. When a Thread can dependably view writes to variables executed by other Threads is determined by this. It establishes the volatile, final, and synchronised semantics that ensure that memory operations are visible to all threads.
Let's first talk about the Memory Barrier, which will serve as the foundation for the rest of our discussion. In JMM, there are two different types of memory barriers: write barriers and read barriers.
In order for the current thread to see changes made by other threads, a read barrier invalidates local memory (registers, cache, etc.) and then retrieves the contents from the main memory.
In order for the other threads to see changes made by the current Thread, the contents of the processor's local memory are flushed to the main memory by a write barrier.
Synchronous JMM semantics
A thread executes a read barrier when it gains control of an object by entering a synchronised section of code (ruins the local memory and instead reads from the heap).
Similar to when leaving a synchronised block, it performs a write barrier (flushes changes to main memory) as part of releasing the associated monitor. As a result, changes made to a shared state by one thread using a synchronised block are ensured to be visible to subsequent synchronised reads by other threads. When there is a synchronised code block present, JMM offers this guarantee.
Semantics of JMM for volatile fields
The acquisition and release of a monitor using a synchronised code block has the same memory semantics as reading and writing to volatile variables. Therefore, the JMM ensures that the volatile field is visible. Additionally, starting with Java 1.5, no other memory operations can be reordered with volatile reads and writes (volatile and non-volatile both). Therefore, any variable values that were visible to Thread A at the moment V was written are guaranteed to now be visible to Thread B when Thread B reads from volatile variable V after Thread A has finished writing to it.
How do you prevent deadlock when N threads access N resources?
This question will be quite difficult for you to answer if you are not experienced in building multi-threading code. Even senior and experienced programmers who are not typically exposed to deadlock and race circumstances may find this Java question challenging. Order is important; if resources are acquired in a specific order and released in the opposite order, stalemate can be avoided.
Does the lack of overriding the hashcode() method affect performance?
This is an excellent question that is open to everyone. To the best of my understanding, a bad hashcode function causes frequent collisions in a hash map, which gradually lengthens the time it takes to add an object.
Why shouldn't HashMap be used in a multithreaded environment? When does the get() method enter an infinite loop?
Another good question. Your answer should be during re-sizing and concurrent access.
In Java, is it possible to override static or private methods?
Another well-known Java problem, As I previously mentioned, a nice subject for Java trick questions is method overriding. In any case, if you create a similar method with the same return type and method arguments—a practise known as method hiding—you cannot override a static or private method in Java.
What will happen if we insert a key object into an existing HashMap?
This complex Java question is a part of the section on How HashMap works in Java, which is a subject on which complex Java questions are frequently created. Since HashMap doesn't allow duplicate keys, if you enter the same key again, it will replace the previous mapping.
What distinguishes CountDownLatch from CyclicBarrier in Java?
Java tough question is relatively new, having only been introduced in Java 5. The primary distinction between the two is that although CountDownLatch in Java cannot be reused, CyclicBarrier can be done so even if the Barrier is broken. For more distinctions, see CyclicBarrier vs. CountDownLatch in Java.
Can non-static variables be accessed in static contexts?
Another challenging Java quiz from Java basics. Java does not allow access to static variables in non-static contexts. To learn more about this challenging Java question, read the explanation of why you cannot access non-static variables from static methods.
1. Can you write Java 7 and Java 8 code to iterate over HashMap?
Yes it is possible
2. When are equals() and hashcode overridden?
Every time it's essential, particularly if you want to perform an equality check or use your object as the key in a hash map.
3. What issue will arise if the hashcode() procedure is left untouched?
You won't be able to retrieve your item from it if that is used as the hash map's key.
4. Is it preferable to synchronise just the important parts of the getInstance() method or the entire method?
Because if we lock the procedure as a whole, the answer is a vital part, everyone who calls it must wait even though no new objects are being created.
5. Can you write singleton crucial section code?
The candidate is expected to construct a Java singleton utilising double verified locking for this fundamental Java question, which is a follow-up to the prior question. Always use volatile variables to ensure that Singleton is thread-safe
6. What distinguishes the wait() method from the sleep() method?
While the wait method releases the lock, sleep() does not. There is a sleep() function in Java.lang. The while wait() method for the thread class is available in Java.lang. class of objects.
One of the straightforward high-level languages, Java offers the robust tools and outstanding standards needed for application development. It was also among the first programming languages to offer outstanding threading support for dealing with concurrency-based issues. The primary factors influencing Java's ever-increasing popularity in the software industry are its simple syntax, built-in capabilities, and the stability it offers to programmes.
Name | Dates | |
---|---|---|
Core Java Training | Nov 09 to Nov 24 | View Details |
Core Java Training | Nov 12 to Nov 27 | View Details |
Core Java Training | Nov 16 to Dec 01 | View Details |
Core Java Training | Nov 19 to Dec 04 | View Details |
Soujanya is a Senior Writer at Mindmajix with tons of content creation experience in the areas of cloud computing, BI, Perl Scripting. She also creates content on Salesforce, Microstrategy, and Cobit. Connect with her via LinkedIn and Twitter.