Reader Sreenath Ravva shared these questions from an Oracle Enterprise Manager interview. This is a historical account, not an official Oracle question bank or a prediction of a current interview. The answers below make the original questions useful for revising Java, concurrency, JDBC and project discussions.
I have tried to put links to web pages where you can refer for answers to below interview questions. They may not be enough to cover the topic, but they will give you a start.
1. What came up in the telephone round?
1.1. How would you introduce yourself and your project?
Introduce your current role, the application’s purpose and the part you owned. Describe one technical decision, why you chose it and an outcome you can support. Keep confidential project details out of the answer.
https://www.youtube.com/watch?v=CumOvDWnUDY
role -> product purpose -> work you owned -> decision -> supported result
Use your own facts for each box. The diagram is an answer structure, not a script to recite.
1.2. How do abstraction and encapsulation differ in Java?
Abstraction exposes the behavior callers need; encapsulation controls access to an object’s state and implementation. An interface can describe an abstract contract, while private fields and methods help enforce an implementation’s invariants.
- howtodoinjava.com/object-oriented/understanding-abstraction-in-java/
- howtodoinjava.com/object-oriented/encapsulation-in-java-and-its-relation-with-abstraction/
interface PaymentMethod { void pay(long cents); } // abstraction
final class Wallet implements PaymentMethod {
private long balance; // encapsulated state
Wallet(long balance) { this.balance = balance; }
public void pay(long cents) {
if (cents > balance) throw new IllegalArgumentException();
balance -= cents;
}
}
The interface exposes what callers can request. The private field and validation protect the balance invariant.
1.3. Can a subclass overload a method inherited from its superclass?
Overloading uses the same method name with different parameter lists. A subclass can add an overload of an inherited accessible method. Return type alone cannot distinguish overloads, and selection uses compile-time argument types.
- howtodoinjava.com/2013/07/15/what-is-polymorphism-in-java
- https://stackoverflow.com/questions/10901259/java-overloading-rules
class Base { void send(String message) {} }
class Child extends Base { void send(int code) {} } // overload
Child inherits send(String) and adds a different parameter list.
1.4. What are the rules for overriding a method?
Overriding replaces inherited instance-method behavior with a compatible signature and return type. It cannot reduce access or broaden checked exceptions. Static methods are hidden, and final methods cannot be overridden.
class Base { Number value() { return 1; } }
class Child extends Base {
@Override Integer value() { return 2; }
}
The covariant return type is allowed. An override must keep a compatible signature and cannot reduce visibility.
1.5. How do widening and narrowing conversions differ?
Widening conversions generally move to a broader primitive type without an explicit cast, though some numeric conversions can lose precision. Narrowing usually requires a cast and can lose range or precision. Reference casts are checked against the object’s runtime type.
int count = 16;
long wide = count; // widening
int narrow = (int) wide; // explicit narrowing
A cast is required for the narrowing assignment even when this particular value fits.
1.6. Can a try block appear without catch or finally?
An ordinary try statement needs a catch or finally block. A try-with-resources statement can omit both because its resource specification provides the cleanup behavior.
Try-with-resources closes eligible resources automatically. Prefer it for JDBC and other AutoCloseable resources rather than relying on a finalizer.
try (java.io.ByteArrayInputStream input =
new java.io.ByteArrayInputStream(new byte[] {42})) {
System.out.println(input.read()); // 42
}
The resource closes at the end of the block even though the statement has no catch or finally clause.
1.7. How would you solve the producer-consumer problem?
Use a bounded BlockingQueue: producers put work into it and consumers take work out. Blocking coordinates empty/full conditions and provides backpressure. Define how producers finish and consumers shut down instead of relying on an endless loop.
- http://en.wikipedia.org/wiki/Producer-consumer_problem
- //howtodoinjava.com/java-5/how-to-use-blockingqueue-and-threadpoolexecutor-in-java/
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(2);
queue.put(42); // producer; waits when full
int value = queue.take(); // consumer; waits when empty
These calls need separate producer and consumer threads in a real application. Choose a shutdown signal or cancellation policy as well.
1.8. Why do wait(), notify() and notifyAll() belong to Object?
Every object can act as a monitor with an associated wait set, so monitor coordination methods belong to Object. A thread must own that object’s monitor before calling wait, notify or notifyAll. Waiting releases that monitor; it does not release every lock the thread holds.
- //howtodoinjava.com/2013/03/04/core-java-interview-questions-series-part-2/
- http://stackoverflow.com/questions/17840397/concept-behind-putting-wait-notify-methods-in-object-class
Object monitor = new Object();
synchronized (monitor) {
monitor.wait(100); // releases this monitor while waiting
}
The call is valid only while the current thread owns monitor.
1.9. Can you override wait() or notify()?
In Object.java, methods getClass(), notify(), notifyAll() and three wait() methods are final, so you can’t override them.
Object: final wait(), notify(), notifyAll()
|
+-- subclass inherits these methods unchanged
notify() and the wait() overloads are final members of Object, so a subclass cannot replace their behavior.
1.10. How do wait(), sleep() and yield() differ?
wait releases the owned object monitor and waits for notification, interruption or timeout. sleep pauses the current thread without releasing monitors. yield is a scheduler hint that may be ignored. None guarantees that a particular other thread will run next.
wait() -> releases the object's monitor while waiting
sleep() -> pauses the current thread; retains held monitors
yield() -> hints to the scheduler; may do nothing
1.11. What does Thread.join() do?
join waits for the target thread to terminate, with optional timeout variants. When an untimed join returns normally, the joining thread can observe the completed thread’s actions through the happens-before guarantee. Handle interruption rather than ignoring it.
http://stackoverflow.com/questions/18479771/java-multithreading-concept-and-join-method
Thread worker = new Thread(() -> System.out.println("done"));
worker.start();
worker.join(); // returns after worker terminates
The calling thread waits for worker; it does not stop worker.
2. What came up in the face-to-face round?
2.1. How would you describe your project in more detail?
Use the same concise introduction as in the first round, then be ready to explain the project architecture, your responsibilities and a decision the interviewer asks about. Keep the account consistent across rounds.
Refer to first question in above list.
request -> component you owned -> dependency -> failure or trade-off -> result
Replace each part with a real project fact and be ready to explain the trade-off.
2.2. How would you diagnose an OutOfMemoryError?
Explain a real incident if you have one; otherwise describe your diagnostic approach honestly. Read the OutOfMemoryError message to identify heap, Metaspace, direct memory or thread-creation pressure. Use suitable dumps, GC logs and resource metrics before assuming the solution is a larger heap.
error message -> memory area -> logs/metrics -> heap dump or native evidence -> cause -> verified fix
For example, a Java heap-space error and a native-memory exhaustion require different evidence. Do not claim a past incident you did not experience.
2.3. How do JDBC connection leaks occur?
A connection leak occurs when borrowed connections are not returned to the pool. Close Connection, Statement and ResultSet resources reliably, inspect pool active/idle counts and use leak diagnostics to identify the borrowing code.
try (Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT id FROM users WHERE id = ?")) {
statement.setLong(1, userId);
try (ResultSet rows = statement.executeQuery()) {
while (rows.next()) System.out.println(rows.getLong("id"));
}
}
Closing the connection returns it to a pool when the data source is pooled.
2.4. How can you swap two integers without a third variable?
For two distinct local integer variables, XOR can swap the values without overflow. This is an interview puzzle; ordinary production code is clearer with a temporary variable.
public class SwapExample {
public static void main(String[] args) {
int a = 3, b = 7;
a ^= b;
b ^= a;
a ^= b;
System.out.println(a + ", " + b); // 7, 3
}
}
This works for two variables. Applying the XOR trick twice to the same array element would zero it, so do not use it for aliased locations.
2.5. How would you sort an array and remove duplicates?
Sort the array, then scan once and retain only values that differ from the previous retained value. Discuss whether the input may be modified and how an empty array is handled. Sorting dominates the usual comparison-based time cost.
http://stackoverflow.com/questions/17967114/how-to-remove-duplicates-from-an-array-in-java
int[] uniqueSorted = Arrays.stream(values).sorted().distinct().toArray();
This returns a new array. State whether changing the input array is allowed before choosing an in-place alternative.
2.6. How would you implement a singleton?
An enum constant or initialization-on-demand holder can provide a JVM-managed singleton. Explain lazy initialization, constructor access and the intended scope. A Spring singleton is one bean instance per container and bean definition, not necessarily one instance across a whole distributed application.
//howtodoinjava.com/design-patterns/singleton-design-pattern-in-java/
enum Registry { INSTANCE; }
Registry registry = Registry.INSTANCE;
An enum constant is a concise singleton when one instance per class loader is the intended scope.
2.7. How would you merge two integer arrays and remove duplicates?
For sorted unique output, combine both arrays and insert values into a TreeSet, or sort and deduplicate a combined array. For encounter order, use a LinkedHashSet. Choose the data structure after clarifying the required output order.
http://stackoverflow.com/questions/5057156/merging-lists-into-a-single-array-with-unique-elements
int[] uniqueSorted = IntStream.concat(Arrays.stream(left), Arrays.stream(right))
.distinct().sorted().toArray();
This allocates a new array and sorts the unique values.
2.8. How do you fetch rows using JDBC and ResultSet?
Obtain a connection, create a PreparedStatement, bind parameters and execute the query. Traverse the ResultSet with next() and read named columns. Use try-with-resources for all three resources and handle SQL errors without returning a connection leak.
//howtodoinjava.com/2013/11/24/jdbc-select-query-example/
try (Connection c = dataSource.getConnection();
PreparedStatement q = c.prepareStatement("SELECT name FROM users WHERE id = ?")) {
q.setLong(1, userId);
try (ResultSet rows = q.executeQuery()) {
while (rows.next()) System.out.println(rows.getString("name"));
}
}
The parameter marker keeps the value separate from SQL text; close all three resources.
2.9. How do you retrieve a value from a HashMap?
Use get(key) with a key whose equals and hashCode contract matches the inserted key. A null result may mean either no mapping or a mapped null in HashMap; containsKey distinguishes them when that distinction matters.
//howtodoinjava.com/java/interviews-questions/how-hashmap-works-in-java/
Map<String, Integer> scores = new HashMap<>();
scores.put("Ada", 0);
Integer value = scores.get("Ada"); // 0
boolean present = scores.containsKey("Ada"); // true
containsKey() distinguishes an absent mapping from a stored null.
2.10. How do Vector and ArrayList differ?
Vector synchronizes individual methods; ArrayList does not. Both are resizable indexed lists. Individual synchronization does not make a sequence of operations or an iteration atomic, so shared usage still needs an appropriate coordination strategy.
//howtodoinjava.com/java/collections/useful-java-collection-interview-questions/
List<String> names = new ArrayList<>();
List<String> legacy = new Vector<>();
Choose ArrayList for ordinary use. If multiple threads share a list, choose a concurrency design that protects whole operations, not just individual calls.
2.11. How do sleep() and wait() differ?
sleep affects the current thread and retains held monitors. wait operates on an owned monitor, releases that monitor while waiting and requires reacquisition before returning. Use wait in a condition loop because wakeups do not prove the condition is true.
//howtodoinjava.com/2013/03/08/difference-between-sleep-and-wait/
synchronized (lock) {
lock.wait(100); // releases lock while waiting
Thread.sleep(100); // retains lock while sleeping
}
Both calls can throw InterruptedException; this fragment belongs in a method that handles it.
2.12. How would you approach the SQL queries mentioned in the interview?
Practice joins, aggregation, NULL handling, indexes and transaction isolation using a small schema. For each query, explain why it returns the intended rows and which database-specific assumptions it makes.
-- Practice example, not a claim about the original interview question:
SELECT department_id, COUNT(*) AS staff_count
FROM employees
GROUP BY department_id;
Explain the expected row per department and how NULL department IDs are grouped.
2.13. How would you print the Fibonacci series?
Choose a starting convention before coding. This example starts with zero and prints eight terms. A zero term count prints nothing; a longer series eventually exceeds long range.
public class FibonacciSampleCode {
public static void main(String[] args) {
int terms = 8;
long previous = 0, current = 1;
for (int i = 0; i < terms; i++) {
System.out.print(previous + (i + 1 == terms ? "\n" : " "));
long next = previous + current;
previous = current;
current = next;
}
}
}
The output is 0 1 1 2 3 5 8 13. Each iteration prints the earlier value, then advances the pair.
2.14. Is the shown try-catch syntax valid?
No. The original interview snippet used an inner try without its own catch or finally, and an empty catch() parameter. Both violate Java syntax.
try { try { } } catch() { } // invalid
A valid form names an exception type and variable, and gives each ordinary try a catch or finally:
try {
System.out.println("work");
} catch (RuntimeException error) {
System.out.println(error.getMessage());
}
2.15. When does a finally block run?
finally normally runs when control leaves the associated try/catch, including by return or exception. It is not guaranteed after JVM termination or a process crash. Avoid returning from finally because it can replace an earlier return value or suppress an exception.
try { System.out.println("work"); }
finally { System.out.println("cleanup"); }
The cleanup line normally runs even if the try throws. Use try-with-resources for AutoCloseable resources.
2.16. What does final mean for variables, methods and classes?
A final variable cannot be reassigned after initialization; the referenced object may still be mutable. A final method cannot be overridden, and a final class cannot be subclassed. These are separate restrictions, not a general guarantee of immutability.
http://en.wikipedia.org/wiki/Final_%28Java%29
final List<String> names = new ArrayList<>();
names.add("Ada"); // allowed: the object remains mutable
// names = new ArrayList<>(); // invalid reassignment
A final method cannot be overridden, and a final class cannot be subclassed.
2.17. Can a class be declared static?
A member class can be static, which means it has no implicit enclosing instance. A top-level class cannot be static. A static nested class can still create ordinary instances and have instance fields.
http://stackoverflow.com/questions/2376938/why-cant-a-java-class-be-declared-as-static
class Outer {
static class Nested {}
}
// static class TopLevel {} // invalid
Only a nested member class can use this modifier.
2.18. What are static fields and methods?
A static field belongs to its declaring class, and a static method is invoked without an instance receiver. It cannot directly access instance fields without an object reference. Static mutable state still needs synchronization when shared between threads.
http://stackoverflow.com/questions/7815664/static-method-and-static-variable-java
class Counter {
static int created;
Counter() { created++; }
static int count() { return created; }
}
All Counter instances share the field; Counter.count() needs no instance.
2.19. Can a class be declared private?
A nested member class can be private. A top-level class cannot: top-level access is public or package access. Choose visibility based on where the type is meant to be used.
http://docs.oracle.com/javase/tutorial/java/javaOO/classdecl.html
class Outer {
private static class Helper {}
}
// private class TopLevel {} // invalid
A top-level class can use package access by omitting public; it cannot be private.
2.20. Does finally run after return or System.exit()?
A return from try normally runs finally before the method returns. A return inside finally can replace the earlier result. System.exit initiates JVM shutdown, so ordinary stack-unwinding finally blocks are not guaranteed to execute.
http://stackoverflow.com/questions/65035/does-finally-always-execute-in-java
static int result() {
try { return 1; }
finally { System.out.println("cleanup"); }
}
The method prints cleanup before returning 1. System.exit() may terminate the VM without running the block, so do not use finally as a guaranteed shutdown hook.
2.21. How would you answer why you want to change companies?
Give an honest, professional reason for considering the role, such as the responsibilities, technical work or growth you are seeking. Do not invent experience or criticize a previous employer.
what you value -> relevant opportunity -> skill you can contribute
Use truthful, specific reasons. The original account does not provide a model personal response.
Use this account as a practice set. Explain the behavior, discuss an edge case and connect it to work you actually performed; memorizing the original interviewer’s wording is less useful than being able to handle a follow-up.
Happy Learning!
Thanks a lot sir, i love reading your blog and You have explained every topic in a detail way.
Sir, can you please post spring interview questions?
I am asked to write a generics code to add two number.using generics,when i tried,it can’t be perform any arithmetic operation on two generics type passed arguments in a method.
For a possible solution if i will check instance of on passed arguments,then perform arithmetic operation,then what will be the generic output type in that case.
Any guidance.
something like below:
class AddOp<T extends Number>{ public <T> T add(T e1,T e2){ if(e1 instanceof Integer){ return e1.intValue()+e2.intValue(); } } }Very good side i have ever seen
Thanks sunil
Your site has very good information and very well presented. But when we are trying to read the page, every few seconds the page just scrolls to an advertisement and we lose track of the part we are reading. It is EXTREMELY annoying and to be honest outright insulting. I know you would like some ad revenue, but why can’t you display the ads on the side?
Hi Venu, Thanks for the feedback. I am using adsense and developermedia for ads. Both are reputed and trustworthy. It is perhaps any rouge ad from any advertiser. Please send me screenshot whenever you face such behavior, i will block that ad. Thanks again for your patience.
superb boss keep happy learning and happy teaching…………………..
Can I have only try block in code?
No. You need either catch block or finally block along with try block, at least.
It’s false. Because there is try-with-resources in java 7.
try(FileInputStream f = new FileInputStream("ttt")){ System.out.println("t"); }it works ok
Thanks for your valuable comment. I will update the post.
Thanks a lot.
As usual one more great article from you.
I love yours blog, I guess i could find here almost everything :)
hi Lokesh..for an 7+ yrs. Exp. Java resource..what would be the topics that needs to be concentrated on while preparing for an interview…
thnx sir for this lovely article keep posting more
Please share testing and Spring Interview questions.
Testing is not my forte. Spring interview questions are in my TODO list already.
Its very usefull … Please share spring questions also..
I will soon ask my readers for their experience in spring interview questions, and consolidate them.
thnk u for given these questions and can u post questions on spring also………..
Excellent. Thanks for putting together and sharing.
thanks