0% found this document useful (0 votes)
2 views40 pages

Java Advanced Questions

The document presents a series of Java programming questions and concepts related to multithreading, collections, database operations, and exception handling. Each question includes code snippets, expected outputs, and explanations of underlying concepts, highlighting potential pitfalls and best practices. Key topics include thread visibility, synchronization, atomic operations, and JDBC behavior, among others.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views40 pages

Java Advanced Questions

The document presents a series of Java programming questions and concepts related to multithreading, collections, database operations, and exception handling. Each question includes code snippets, expected outputs, and explanations of underlying concepts, highlighting potential pitfalls and best practices. Key topics include thread visibility, synchronization, atomic operations, and JDBC behavior, among others.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Question 1: The Volatile Visibility Twist

class Flag {

static boolean running = true; // Not volatile

public static void main(String[] args) throws InterruptedException {

new Thread(() -> {

while (running) { /* Spin */ }

[Link]("Stopped");

}).start();

[Link](100);

running = false;

[Link]("Main finished");

Output:

Main finished

(Program likely hangs/does not print "Stopped")

Concept:

Without volatile, the CPU cache may not flush the change of running to the reader thread. The
reader thread may see a stale cached value of true indefinitely.-----
Question 2: Synchronized Integer Lock

class Counter {

public static void main(String[] args) throws InterruptedException {

Integer lock = 1;

Thread t1 = new Thread(() -> {

synchronized(lock) {

[Link]("A");

try { [Link](100); } catch (Exception e) {}}

});

Thread t2 = new Thread(() -> {

synchronized(lock) {

[Link]("B");}

});

[Link]();

[Link](10);

// Note: Integer(1) is immutable/cached.

[Link]();}}

Output:

AB (Ordered) or A then B

Concept:

Locking on Integer or String literals is dangerous. If lock were reassigned (lock++), the
reference changes, and synchronization breaks. Here, since lock isn't reassigned, it works, but
it's a "bad practice" twist.-----
Question 3: Thread Start vs Run

class Task extends Thread {

public void run() {

[Link]("Run: " + [Link]().getName());

public static void main(String[] args) {

Task t = new Task();

[Link]();

[Link]();

Output:

Run: main

Run: Thread-0

Concept:

Calling run() executes the method on the current stack (main thread). Calling start()
launches a new call stack (new thread).-----​









Question 4: Daemon Thread Death

public class Main {

public static void main(String[] args) {

Thread t = new Thread(() -> {

try {

[Link](2000);

[Link]("Daemon Finished");

} catch (Exception e) {}

});

[Link](true);

[Link]();

[Link]("Main Exit");

Output:

Main Exit

Concept:

JVM terminates when all user threads finish. Daemon threads are killed instantly when the main
thread exits; "Daemon Finished" is never printed.-----
Question 5: Wait without Lock

public class Main {

public static void main(String[] args) throws InterruptedException {

Object lock = new Object();

try {

[Link]();

} catch (IllegalMonitorStateException e) {

[Link]("Exception");

Output:

Exception

Concept:

wait() (and notify()) must be called inside a synchronized block on that specific object, or
it throws IllegalMonitorStateException.-----
Question 6: ThreadJoin Order

public class Main {

public static void main(String[] args) throws InterruptedException {

Thread t1 = new Thread(() -> [Link]("1"));

Thread t2 = new Thread(() -> [Link]("2"));

[Link]();

[Link]();

[Link]();

[Link]();

[Link]("3");

Output:

123

Concept:

join() blocks the calling thread (main) until the joined thread (t1) dies. This forces a strict
serial execution order.-----
Question 7: Uncaught Exception Handler

public class Main {

public static void main(String[] args) {

Thread t = new Thread(() -> { throw new RuntimeException("Oops"); });

[Link]((th, e) -> [Link]("Caught: " + [Link]()));

[Link]();

Output:

Caught: Oops

Concept:

Exceptions in separate threads do not crash the main thread. They terminate the child thread
silently unless a handler is registered.-----
Question 8: AtomicInteger vs ++

import [Link];

class Counter {

static int count = 0;

static AtomicInteger atomic = new AtomicInteger(0);

public static void main(String[] args) throws InterruptedException {

Runnable r = () -> {

for(int i=0; i<1000; i++) { count++; [Link](); }

};

Thread t1 = new Thread(r); Thread t2 = new Thread(r);

[Link](); [Link]();

[Link](); [Link]();

[Link](count == 2000 ? "Count Correct" : "Count Wrong");

[Link]([Link]() == 2000 ? "Atomic Correct" : "Atomic Wrong");

Output:

Count Wrong (Likely)

Atomic Correct

Concept:

count++ is not atomic (read-modify-write). AtomicInteger uses hardware CAS


(Compare-And-Swap) for thread safety without synchronized.-----
Question 9: ThreadLocal Independence

public class Main {

static ThreadLocal<String> tl = [Link](() -> "Initial");

public static void main(String[] args) throws InterruptedException {

[Link]("Main");

Thread t = new Thread(() -> {

[Link]("Child");

[Link]([Link]());

});

[Link]();

[Link]();

[Link]([Link]());

Output:

Child

Main

Concept:

ThreadLocal stores data separately for each thread. Changes in the child thread do not affect
the main thread's copy.-----
Question 10: CompletableFuture Exception

import [Link];

public class Main {

public static void main(String[] args) {

[Link](() -> {

if (true) throw new RuntimeException("Fail");

return 1;

}).exceptionally(ex -> {

[Link]("Recovered");

return 0;

}).join();

Output:

Recovered

Concept:

CompletableFuture allows functional exception handling. The .exceptionally block


catches the runtime exception from the async task.-----
Question 11: IdentityHashMap Key Uniqueness

import [Link].*;

public class Main {

public static void main(String[] args) {

Map<String, String> map = new IdentityHashMap<>();

[Link](new String("A"), "1");

[Link](new String("A"), "2");

[Link]([Link]());

Output:

Concept:

Unlike HashMap (which uses .equals()), IdentityHashMap uses reference equality (==).
Since new String("A") creates two distinct heap objects, they are different keys.-----
Question 12: [Link] vs [Link]

import [Link].*;

public class Main {

public static void main(String[] args) {

try {

List<String> list = [Link]("A", "B");

[Link](0, "C"); // Works

List<String> list2 = [Link]("A", "B");

[Link](0, "C"); // Throws

} catch (UnsupportedOperationException e) {

[Link]("Immutable");

Output:

Immutable

Concept:

[Link] returns a fixed-size list backed by the array (mutable elements, fixed
structure). [Link] returns a truly immutable list (structural and element immutability).-----
Question 13: PriorityQueue Sorting Twist

import [Link].*;

public class Main {

public static void main(String[] args) {

PriorityQueue<Integer> pq = new PriorityQueue<>();

[Link](10); [Link](5); [Link](20);

[Link](pq); // toString() logic?

[Link]([Link]());

Output:

[5, 10, 20] (Order not guaranteed in toString)

Concept:

PriorityQueue implies a sorted heap structure, not a sorted list. toString() iterates the
array representation of the heap, which is not fully sorted. Only poll() guarantees retrieval in
sorted order.-----
Question 14: HashMap Mutable Keys

import [Link].*;

class Key { int id; Key(int id) { [Link] = id; }

public int hashCode() { return id; } }

public class Main {

public static void main(String[] args) {

Map<Key, String> map = new HashMap<>();

Key k = new Key(1);

[Link](k, "Data");

[Link] = 2; // Mutating key

[Link]([Link](k));

Output:

null

Concept:

Mutating a key after insertion changes its hash code. The map looks for the key in the bucket
corresponding to the new hash, but the entry is sitting in the old bucket.-----
Question 15: LinkedHashMap LRU Mode

import [Link].*;

public class Main {

public static void main(String[] args) {

// true = access order (LRU), false = insertion order

Map<String, String> map = new LinkedHashMap<>(16, 0.75f, true);

[Link]("A", "1"); [Link]("B", "2"); [Link]("C", "3");

[Link]("A"); // Access A

[Link]([Link]());

Output:

[B, C, A]

Concept:

In access-order mode (true), accessing an element moves it to the end of the iteration order.
"A" was accessed last, so it became the "youngest" element.-----
Question 16: TreeSet with Null

import [Link].*;

public class Main {

public static void main(String[] args) {

try {

TreeSet<String> set = new TreeSet<>();

[Link](null);

} catch (Exception e) {

[Link]([Link]().getSimpleName());

Output:

NullPointerException

Concept:

TreeSet relies on Comparable or Comparator. null cannot be compared to other strings


naturally, so modern Java TreeSet implementations ban nulls.-----
Question 17: [Link] vs [Link]

import [Link].*;

public class Main {

public static void main(String[] args) {

List<String> list = new ArrayList<>([Link]("A", "B"));

for (String s : list) {

if ("A".equals(s)) [Link](s);

Output:

ConcurrentModificationException

Concept:

You cannot modify a collection structurally (via [Link]) while iterating over it with a
for-each loop. This causes a ConcurrentModificationException. You must use
[Link]().-----
Question 18: [Link] Reference

import [Link].*;

public class Main {

public static void main(String[] args) {

List<StringBuilder> list = [Link](3, new StringBuilder("A"));

[Link](0).append("B");

[Link]([Link](2));

Output:

AB

Concept:

nCopies creates a list containing n references to the same object instance. Modifying one
element modifies them "all" because they are physically the same object.-----
Question 19: TreeMap SubMap View

import [Link].*;

public class Main {

public static void main(String[] args) {

TreeMap<Integer, String> map = new TreeMap<>();

[Link](1, "A"); [Link](2, "B"); [Link](3, "C");

SortedMap<Integer, String> sub = [Link](1, 3); // 1 inclusive, 3 exclusive

[Link](2, "Z");

try { [Link](4, "D"); } catch(Exception e) { [Link]("Error"); }

[Link]([Link](2));

Output:

Error

Concept:

subMap is a restricted view. You cannot insert keys outside the view's range (1 to <3), hence
IllegalArgumentException (printed as "Error"). Changes within range reflect in the original
map.-----
Question 20: EnumSet BitVector

import [Link].*;

enum Day { M, T, W }

public class Main {

public static void main(String[] args) {

EnumSet<Day> days = [Link](Day.M, Day.W);

EnumSet<Day> copy = [Link]();

[Link]([Link]().getSuperclass().getSimpleName());

Output:

EnumSet (Technically RegularEnumSet or JumboEnumSet internally)

Concept:

EnumSet is extremely efficient because it uses a bit vector (a single long if <= 64 constants)
instead of a hash table. It’s faster and uses less memory than HashSet.-----
Question 21: AutoCommit Trap

Connection conn = [Link](url, user, pass);

[Link](false);

Statement stmt = [Link]();

[Link]("INSERT INTO Users VALUES (1, 'John')");

// [Link](); // OMITTED

[Link]();

// Check Database

Output (in DB):

(Empty/Row missing)

Concept:

If AutoCommit is false and commit() is never explicitly called, the transaction is rolled back
when the connection closes (implementation dependent, but standard safety behavior).-----
Question 22: PreparedStatement Injection

String input = "' OR '1'='1";

String sql = "SELECT * FROM Users WHERE name = ?";

PreparedStatement ps = [Link](sql);

[Link](1, input);

[Link]([Link]()); // Pseudo-output

Output:

SELECT * FROM Users WHERE name = '' OR '1'='1' (Escaped)

Concept:

PreparedStatement treats the input purely as data (a literal string), escaping special
characters, thus neutralizing the SQL injection attack.-----
Question 23: ResultSet Scrollability

Statement stmt = [Link](ResultSet.TYPE_FORWARD_ONLY,


ResultSet.CONCUR_READ_ONLY);

ResultSet rs = [Link]("SELECT * FROM Data");

[Link]();

try {

[Link]();

} catch (SQLException e) {

[Link]("Exception");

Output:

Exception

Concept:

The default ResultSet type is FORWARD_ONLY. Calling previous(), first(), or


absolute() throws an exception. You need TYPE_SCROLL_INSENSITIVE or
SENSITIVE.-----
Question 24: Statement Batching Return

Statement stmt = [Link]();

[Link]("INSERT INTO A VALUES(1)");

[Link]("UPDATE B SET val=2");

int[] counts = [Link]();

[Link]([Link]);

Output:

Concept:

executeBatch() returns an array of integers, where each integer represents the update count
(rows affected) for the corresponding SQL command in the batch.-----
Question 25: Closing Statement vs ResultSet

Statement stmt = [Link]();

ResultSet rs = [Link]("SELECT * FROM A");

[Link](); // Closed explicitly

try {

[Link]();

} catch (SQLException e) {

[Link]("Closed");

Output:

Closed

Concept:

Closing a Statement automatically closes its open ResultSet. Trying to access the
ResultSet afterwards throws an exception.-----
Question 26: Execute vs ExecuteQuery

Statement stmt = [Link]();

boolean isResultSet = [Link]("UPDATE Users SET name='A'");

[Link](isResultSet);

Output:

false

Concept:

execute() returns true if the first result is a ResultSet (SELECT), and false if it is an
update count (INSERT/UPDATE/DELETE).-----
Question 27: Transaction Isolation - Dirty Read

Conceptual Setup: Level = READ_UNCOMMITTED

// Thread A:

[Link](Connection.TRANSACTION_READ_UNCOMMITTED);

[Link]("UPDATE T SET val=50"); // No commit yet

// Thread B:

ResultSet rs = [Link]("SELECT val FROM T");

// What does B see?

Output (Thread B):

50

Concept:

READ_UNCOMMITTED allows "Dirty Reads"—seeing uncommitted data from other transactions.


This is the lowest isolation level and most dangerous.-----
Question 28: Savepoint Rollback

[Link](false);

[Link]("INSERT INTO A VALUES (1)");

Savepoint sp = [Link]();

[Link]("INSERT INTO A VALUES (2)");

[Link](sp);

[Link]();

// How many rows in A?

Output:

1 (Row 1 exists, Row 2 rolled back)

Concept:

rollback(Savepoint) undoes changes only back to that specific savepoint, preserving the
work done before the savepoint within the transaction.-----
Question 29: JDBC 4.0 Autoloading

// Old style: [Link]("[Link]");

Connection conn = [Link]("jdbc:mysql://localhost/db");

[Link](conn != null);

Output:

true

Concept:

Since JDBC 4.0 (Java 6), drivers in the classpath with a


META-INF/services/[Link] file are automatically loaded. Explicit
[Link] is no longer strictly necessary.-----
Question 30: ResultSet Getter Type

// DB Column 'age' is VARCHAR "25"

ResultSet rs = [Link]("SELECT age FROM Users");

[Link]();

int age = [Link]("age");

[Link](age + 1);

Output:

26

Concept:

JDBC drivers attempt to convert types. If a VARCHAR contains a valid number ("25"), getInt()
parses it successfully. If it contained "Twenty", it would throw a SQLException.-----
Question 31: [Link] vs ofNullable

import [Link];

public class Main {

public static void main(String[] args) {

try {

[Link](null);

} catch (NullPointerException e) {

[Link]("NPE");

[Link]([Link](null).isPresent());

Output:

NPE

false

Concept:

[Link](obj) strictly requires a non-null value, throwing NullPointerException


otherwise. [Link](obj) safely wraps nulls into [Link]().-----
Question 32: Stream Reuse

import [Link].*;

public class Main {

public static void main(String[] args) {

Stream<String> s = [Link]("A", "B");

[Link]([Link]::print);

try {

[Link]();

} catch (Exception e) {

[Link]("Closed");

Output:

ABClosed

Concept:

Java Streams are "one-off". Once a terminal operation (forEach) is performed, the stream is
consumed and closed. Reuse throws IllegalStateException.-----
Question 33: Interface Static Method Override

interface A {

static void show() { [Link]("Interface"); }

class B implements A {

static void show() { [Link]("Class"); }

public class Main {

public static void main(String[] args) {

[Link]();

[Link]();

// A b = new B(); [Link](); // Compile Error

Output:

Interface

Class

Concept:

Static methods in interfaces are not inherited and cannot be overridden. [Link]() hides
[Link]() but is a completely separate method.-----
Question 34: Double Brace Initialization (Anti-Pattern)

import [Link].*;

public class Main {

public static void main(String[] args) {

List<String> list = new ArrayList<>() {{

add("A");

}};

[Link]([Link]().equals([Link]));

Output:

false

Concept:

Double brace initialization creates an anonymous inner class that extends ArrayList. It is
not strictly an ArrayList type, which can cause serialization or equality issues.-----
Question 35: String Split Limit

public class Main {

public static void main(String[] args) {

String s = "a,b,,,";

[Link]([Link](",").length);

[Link]([Link](",", -1).length);

Output:

Concept:

split(regex) discards trailing empty strings by default. split(regex, limit) with a


negative limit preserves trailing empty strings.-----
Question 36: Generic Type Erasure

import [Link].*;

public class Main {

public static void main(String[] args) {

List<Integer> ints = new ArrayList<>();

List<String> strs = new ArrayList<>();

[Link]([Link]() == [Link]());

Output:

true

Concept:

At runtime, Generics are erased. Both lists are just raw ArrayList instances (holding Objects).
The type information exists only at compile time.-----
Question 37: Switch on Null

public class Main {

public static void main(String[] args) {

String s = null;

try {

switch (s) {

case "A": [Link]("A");

} catch (NullPointerException e) {

[Link]("Null Switch");

Output:

Null Switch

Concept:

Switching on a String involves calling its hashCode() and equals() methods. If the
variable is null, it throws NullPointerException immediately.-----
Question 38: [Link] Double vs Float

public class Main {

public static void main(String[] args) {

[Link]([Link]([Link], 0.0f));

[Link]([Link](0.0f, [Link]));

Output:

NaN

NaN

Concept:

If either argument to [Link] (or max) is NaN, the result is NaN. This behavior follows the
IEEE 754 standard for floating-point arithmetic.-----
Question 39: Finally with [Link]

public class Main {

public static void main(String[] args) {

try {

[Link]("Try");

[Link](0);

} finally {

[Link]("Finally");

Output:

Try

Concept:

[Link](0) halts the JVM immediately. The finally block is not executed in this
specific scenario.-----
Question 40: Varargs Heap Pollution

public class Main {

static void print(List<String>... lists) {

Object[] objects = lists;

objects[0] = [Link](42); // Heap pollution

String s = lists[0].get(0); // ClassCastException

public static void main(String[] args) {

try {

print([Link]("A"));

} catch (ClassCastException e) {

[Link]("Pollution Detected");

Output:

Pollution Detected

Concept:

Varargs are implemented as arrays. Since arrays are covariant (String[] is an Object[])
but generics are invariant, mixing them can allow you to put the wrong type into the array,
causing a runtime cast error (ClassCastException) when accessing the generic type.

You might also like