Java coding traps (output-based questions)
Here are Top Java Coding Traps (Output-Based Questions) β very common in interviews π₯Each includes code + output + explanation so you can answer confidently. Java Basic Trapsβ¦
Here are Top Java Coding Traps (Output-Based Questions) β very common in interviews π₯
Each includes code + output + explanation so you can answer confidently.
Java Basic Traps
1. String Pool Trap
String a = "Java";
String b = "Java";
System.out.println(a == b);
π Output: true
π Why?
- Both refer to same string pool object
String a = new String("Java");
String b = new String("Java");
System.out.println(a == b);
π Output: false
2. Integer Cache Trap
Integer a = 127;
Integer b = 127;
System.out.println(a == b);
π Output: true
Integer a = 128;
Integer b = 128;
System.out.println(a == b);
π Output: false
π Why?
- Cache range: -128 to 127
3. String Immutability
String str = "Java";
str.concat(" Rocks");
System.out.println(str);
π Output: Java
Why?
- String is immutable
4. finally Block Override
public class Test {
public static void main(String[] args) {
System.out.println(test());
} static int test() {
try {
return 1;
} finally {
return 2;
}
}
}
π Output: 2
Why?
finallyoverrides return
5. Array Reference Trap
int[] arr = {1, 2, 3};
int[] copy = arr;copy[0] = 100;System.out.println(arr[0]);
π Output: 100
Why?
- Both reference same array
6. Method Overloading Confusion
void test(int a) { System.out.println("int"); }
void test(Integer a) { System.out.println("Integer"); }test(10);
π Output: int
7. Null Method Call Trap
String str = null;
System.out.println(str instanceof String);
π Output: false
Why?
instanceofhandles null safely
8. Static vs Instance
class A {
static void show() { System.out.println("A"); }
}class B extends A {
static void show() { System.out.println("B"); }
}A obj = new B();
obj.show();
π Output: A
Why?
- Static methods β compile-time binding
9. List Modification Trap
List<Integer> list = Arrays.asList(1, 2, 3);
list.add(4);
π Output: UnsupportedOperationException
10. Post vs Pre Increment
int i = 5;
int result = i++ + ++i;
System.out.println(result);
π Output: 12
Step:
i++β 5 (i becomes 6)++iβ 7
π 5 + 7 = 12
How to Answer in Interview
π Donβt just give output β explain:
βThis happens due to string pool / immutability / caching / reference behavior.β
Must-Remember Traps
String pool
Integer cache
finally override
Arrays.asList() fixed size
i++ vs ++i
π§΅ MULTITHREADING TRAPS (1β10)
1. Thread start() vs run()
class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
}
}public class Test {
public static void main(String[] args) {
MyThread t = new MyThread();
t.run();
System.out.println("Main thread");
}
}
π Output (always same order):
Thread running
Main thread
β run() β normal method (no new thread)
2. Using start()
t.start();
System.out.println("Main thread");
π Output: (order NOT guaranteed β)
Main thread
Thread running
OR
Thread running
Main thread
3. Two Threads Execution
Thread t1 = new Thread(() -> System.out.println("A"));
Thread t2 = new Thread(() -> System.out.println("B"));t1.start();
t2.start();
π Output:
A B OR B A
β Order unpredictable
4. sleep() Behavior
Thread t = new Thread(() -> {
try {
Thread.sleep(1000);
System.out.println("Done");
} catch(Exception e){}
});
t.start();
System.out.println("Main");
π Output:
Main
Done
π₯ 5. join() Trap
Thread t = new Thread(() -> System.out.println("Thread"));
t.start();
t.join();
System.out.println("Main");
π Output:
Thread
Main
β join() waits for thread
6. Race Condition
int count = 0;Runnable r = () -> {
for(int i=0;i<1000;i++) count++;
};Thread t1 = new Thread(r);
Thread t2 = new Thread(r);t1.start(); t2.start();
t1.join(); t2.join();System.out.println(count);
π Output: unpredictable (< 2000 β)
7. synchronized Fix
synchronized(this) {
count++;
}
π Output: 2000 β
8. Daemon Thread
Thread t = new Thread(() -> {
while(true) {}
});
t.setDaemon(true);
t.start();System.out.println("Main ends");
π Program exits immediately
9. Deadlock (Concept)
// Thread1 locks A β waits B
// Thread2 locks B β waits A
π Output: program hangs β
10. Callable vs Runnable
Callable<Integer> task = () -> 10;
FutureTask<Integer> ft = new FutureTask<>(task);new Thread(ft).start();
System.out.println(ft.get());
π Output: 10
π STREAM TRAPS (11β20)
11. Stream Reuse
Stream<Integer> s = Stream.of(1,2,3);
s.forEach(System.out::println);
s.forEach(System.out::println);
π Output: Exception β
12. Lazy Execution
Stream.of(1,2,3)
.filter(x -> {
System.out.println(x);
return true;
});
π Output: nothing β
β No terminal operation
13. Order of Execution
Stream.of(1,2,3)
.filter(x -> {
System.out.println("Filter: " + x);
return true;
})
.map(x -> {
System.out.println("Map: " + x);
return x;
})
.forEach(System.out::println);
π Runs element by element (not full filter then map)
14. Parallel Stream Order
Stream.of(1,2,3,4)
.parallel()
.forEach(System.out::print);
π Output order unpredictable
15. forEachOrdered()
.parallel().forEachOrdered(System.out::print);
π Output: 1234 β
16. findFirst() vs findAny()
Stream.of(1,2,3).parallel().findAny();
π Output unpredictable
17. limit() with parallel
Stream.iterate(1, x->x+1)
.parallel()
.limit(5)
.forEach(System.out::print);
π Order not guaranteed
18. Side Effects
List<Integer> list = new ArrayList<>();Stream.of(1,2,3).forEach(list::add);
System.out.println(list);
π Works, but bad practice β
19. distinct() behavior
Stream.of(1,1,2,2,3)
.distinct()
.forEach(System.out::print);
π Output: 123
20. map() vs flatMap()
List<List<Integer>> list = Arrays.asList(
Arrays.asList(1,2),
Arrays.asList(3,4)
);list.stream()
.flatMap(List::stream)
.forEach(System.out::print);
π Output: 1234
Final Interview Strategy
Focus on explaining:
- Thread execution order
- Race conditions
- Stream laziness
- Parallel stream behavior
Pro Tip
If stuck, say:
βOutput may vary due to thread scheduling / parallel execution.β