Disclosure: This post includes affiliate links; I may receive compensation if you purchase products or services from the different links provided in this article.
_
Hello devs, are you preparing for Java developer interviews? If Yes, here is a list of some useful Java interview questions for experienced Java programmers having experience in range of 2 to 5 years.
As an experienced developer you are expected to learn about OOP concepts, Java basics, Java Collection framework, Multi-threading and Concurrency utilities introduced in Java 5 and 6, Debugging Java application, Algorithm and Data structure, Some questions on design patterns, JVM and Garbage collection and couple of puzzles.
Actually its mix of everything you do in your day to day work.
If you are going for Java developer with some exposure on web development you will also be asked about popular Java frameworks like Spring, Hibernate, Struts 2.0 and others.
If you have more than 5 years of experience you can also expect questions about build tools like Maven, ANT and Gradle, Java best practices, Unit testing and JUnit and your experience about solving production issues.
One of the most common question I have faced is talking about the last production problem you have faced and how did you solved it.
If you are asked same question, give them step by step detail, right from analyzing problem to tactical fix to strategic solution.
In this article, I am going to share my list of Java Interview question for Java guys having 2 to 5 years of experience. Since I had similar experience couple of year ago, I know what questions are asked and keeping a list for your own always helps when you start looking for new challenge in your career.
I am not providing answers of these question in this post due to two reasons, questions are quite simple and you guys probably know the answer, second providing answer means I cannot use this post for my own preparation later, which is more important.
Though, I could write another article answering all these question if anyone request or I feel people need it.
By the way, if you are new to Java programming language or want to improve Java skills then you can also checkout sites like CodeGym, ZTM and karpado to learn Java by building Games and projects.
This list contains questions from different topics e.g. OOP concepts, multi-threading and concurrency, Java collections, Web services, Spring, Hibernate, Database and JDBC, it doesn't cover all topics you need to prepare.
I will add few more topics later when I have some time, for now, try to answer these questions without doing Google :)
Here are a couple of questions on OOP design, SOLID principle and baseic programming concepts
Loose coupling allows components to interact with each other with minimal dependencies, while tight coupling creates strong dependencies between components.
Cohesion refers to the degree to which elements within a module belong together, while coupling refers to the degree of interdependence between modules.
Liskov Substitution principle states that objects of a superclass should be replaceable with objects of its subclasses without affecting the correctness of the program.
For example, if you have a class hierarchy with a superclass "Shape" and subclasses "Circle" and "Square", any method that works with Shape should also work with Circle or Square without causing errors.
Abstract classes can have both abstract and concrete methods, while interfaces can only have abstract methods. Additionally, a class can implement multiple interfaces but can only extend one abstract class.
Composition implies a strong ownership relationship where the lifetime of the contained object is dependent on the container.
Aggregation implies a weaker relationship where the contained object can exist independently of the container. Association implies a relationship between two classes without any ownership or lifecycle dependency.
Now, let's see a few questions form Collections and Stream
Lists maintain elements in sequential order and allow duplicates (e.g., ArrayList, LinkedList). Sets do not allow duplicates and do not guarantee order (e.g., HashSet, TreeSet). Maps store key-value pairs and do not allow duplicate keys (e.g., HashMap, TreeMap).
Synchronized collections use explicit locking to achieve thread-safety, allowing only one thread to modify the collection at a time. Concurrent collections use non-blocking algorithms and are designed for high concurrency, allowing multiple threads to modify the collection concurrently without explicit locking.
The get method of HashMap calculates the hash code of the provided key, determines the index in the underlying array based on the hash code, and then searches for the key at that index. If found, it returns the corresponding value; otherwise, it returns null.
ConcurrentHashMap allows concurrent access to the map without blocking, while Hashtable uses synchronized methods to achieve thread-safety, resulting in potential performance bottlenecks. ConcurrentHashMap achieves thread-safety by dividing the map into segments, each with its lock, allowing multiple threads to modify different segments concurrently.
Use LinkedList when frequent insertion and deletion operations are required, as LinkedList provides constant-time insertion and deletion at any position. Use ArrayList when random access and iteration are frequent, as ArrayList provides constant-time access by index.
Now, its time to see questions from Java multithreading and concurrency concepts:
Both notify and notifyAll are methods in Java used to wake up threads waiting on a monitor (i.e., waiting to acquire an object's lock). notify wakes up one randomly selected thread, while notifyAll wakes up all waiting threads. notifyAll is preferred because it ensures that all waiting threads are notified, preventing potential indefinite waiting and improving system responsiveness.
A race condition occurs when the outcome of a program depends on the timing or interleaving of multiple threads. To avoid race conditions, you can use synchronization mechanisms like locks, semaphores, or atomic operations to ensure that critical sections of code are executed atomically or only by one thread at a time.
Deadlock occurs when two or more threads are stuck waiting for each other to release resources that they need to proceed. To avoid deadlock, you can use techniques such as resource ordering, avoiding nested locks, or using timeouts for acquiring locks. Additionally, designing code with a clear and consistent locking order can help prevent deadlocks.
Some high-level concurrency classes provided by java.util.concurrent include ExecutorService, ThreadPoolExecutor, CountDownLatch, Semaphore, CyclicBarrier, BlockingQueue, and ConcurrentHashMap. These classes provide thread-safe implementations of common concurrency patterns and mechanisms like thread pools, synchronization primitives, and concurrent data structures.
Yes, here is the code:
import java.util.concurrent.ArrayBlockingQueue; class Producer implements Runnable { private final ArrayBlockingQueuequeue; private int count = 0; Producer(ArrayBlockingQueue queue) { this.queue = queue; } public void run() { try { while (true) { queue.put(produce()); Thread.sleep(1000); // Simulate some work } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } private int produce() { System.out.println("Producing: " count); return count ; } } class Consumer implements Runnable { private final ArrayBlockingQueue queue; Consumer(ArrayBlockingQueue queue) { this.queue = queue; } public void run() { try { while (true) { consume(queue.take()); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } private void consume(int item) { System.out.println("Consuming: " item); } } public class Main { public static void main(String[] args) { ArrayBlockingQueue queue = new ArrayBlockingQueue(10); Producer producer = new Producer(queue); Consumer consumer = new Consumer(queue); Thread producerThread = new Thread(producer); Thread consumerThread = new Thread(consumer); producerThread.start(); consumerThread.start(); } }
JDBC is used for connecting database from Java program, let's ee a few questions on Database and JDBC
To prevent SQL injection attacks, use parameterized queries (prepared statements) with bound parameters, input validation, and escape characters. Avoid dynamic SQL queries constructed by concatenating user input.
The WHERE clause filters rows before the grouping and aggregation process, while the HAVING clause filters aggregated data after the grouping process based on specified conditions.
Transactions are a set of SQL statements that are executed as a single unit of work. ACID is an acronym for Atomicity, Consistency, Isolation, and Durability, which are properties that ensure the reliability of transactions in a database system.
Window functions perform calculations across a set of rows related to the current row within a query result set. They allow you to perform aggregate functions (such as SUM, AVG, COUNT) over a specified window or subset of rows, defined by the OVER clause. Window functions operate on a set of rows and return a single value for each row based on that set of rows. They are often used for tasks such as ranking, aggregation, and calculating running totals.
See, Grokking the SQL Interview book if you need more questions on Database and SQL
Now, its time to see questions from Hibernate, one of the popular Java framework:
It's better to use plain SQL when:
In Java, a sorted collection maintains elements in a specific order defined by a comparator or by the natural ordering of elements, while an ordered collection maintains elements in the order they were inserted.
Second level cache in Hibernate stores objects in a shared cache region, typically across multiple sessions. When an entity is queried for the first time, it is fetched from the database and stored in the second level cache. Subsequent queries for the same entity can then be satisfied from the cache instead of hitting the database, improving performance.
Both save() and persist() methods in Hibernate are used to save an entity to the database. However, save() returns the generated identifier immediately, while persist() doesn't guarantee immediate execution of the SQL INSERT statement; it may be executed later during flush time. Additionally, persist() is part of the JPA specification, while save() is specific to Hibernate.
Now, let's see questions form Microservice architecture and REST web services
SOAP is protocol-based with rigid structure, while REST is architectural style based on stateless communication with flexible endpoints.
It encapsulates the entire SOAP message and defines its structure.
Implement SSL/TLS for encryption and authentication.
It's the data transmitted in the body of the HTTP request or response.
It's an architectural style where applications are composed of small, independent services.
Microservices refer to architectural design, while REST is an architectural style for networked applications.
Monolithic has single codebase, while Microservices have multiple, independent components; Monolithic can have higher latency.
It manages distributed transactions in Microservices architecture.
It's the mechanism for locating services dynamically within a Microservices architecture.
Before any Java and Spring Developer interview, I always read the Grokking the Java Interview and Grokking the Spring boot Interviw
Here are few more questions from these books:
and,
And, if you are new to Java then you can also checkout sites like CodeGym, ZTM and karpado to learn Java by building Games and projects.
Thank you guys for now. You can find the answers in web easily but if there are enough interest, I can also update the post. Let me know if you have also asked these questions before. If anyone knows answer, can also post as comment.
Good luck for your Java Interview.
By the way, if you are new to Java programming language or want to improve Java skills then you can also checkout following best Java courses to get better:
免責事項: 提供されるすべてのリソースの一部はインターネットからのものです。お客様の著作権またはその他の権利および利益の侵害がある場合は、詳細な理由を説明し、著作権または権利および利益の証拠を提出して、電子メール [email protected] に送信してください。 できるだけ早く対応させていただきます。
Copyright© 2022 湘ICP备2022001581号-3