These Java interview questions cover core language fundamentals, object-oriented programming, constructors, packages, exceptions, strings, collections, and multithreading. The answers are written for freshers and experienced developers, with notes where older interview material no longer reflects modern Java.

How to Prepare for Java Interview Questions by Experience Level

  • Freshers: Focus on syntax, JVM, JDK, JRE, classes and objects, inheritance, interfaces, exceptions, strings, arrays, and basic collections.
  • 3 to 5 years of experience: Be ready to explain collections internals, immutability, concurrency, thread safety, exception design, generics, streams, and practical debugging decisions.
  • Senior Java developers: Expect design trade-offs, JVM behavior, memory management, concurrency utilities, performance analysis, API design, testing, and production troubleshooting.

Java Basic Interview Questions

How is Java different from C++?

Java and C++ are designed for different goals, so one is not universally better than the other. Java emphasizes portability, managed memory, a large runtime ecosystem, and a simpler object model. C++ provides lower-level memory control, deterministic destruction, operator overloading, templates, multiple inheritance of classes, and closer access to hardware.

Java does not expose pointer arithmetic, does not support user-defined operator overloading, and does not support multiple inheritance of classes. It uses garbage collection instead of C++-style destructors. Java does support multiple inheritance of type through interfaces and generic programming through generics.

How do you declare a constant variable in Java?

The final keyword prevents a variable from being reassigned after initialization. A class-level constant is commonly declared with both static and final, and its name is usually written in uppercase.

The following original example intends to declare PI, but its type should be double, not int, because 3.14 is a floating-point value.

final int PI=3.14;
</>
Copy
private static final double PI = 3.14;

How does Java release resources without destructors?

The garbage collector reclaims heap memory occupied by objects that are no longer reachable. Garbage collection is automatic, but its exact timing is not guaranteed. Calling System.gc() only requests a collection; the JVM may ignore the request.

Garbage collection is not a replacement for explicitly closing external resources such as files, sockets, and database connections. Use try-with-resources for objects that implement AutoCloseable.

</>
Copy
try (BufferedReader reader = Files.newBufferedReader(path)) {
    System.out.println(reader.readLine());
}

What does the static keyword mean in Java?

A static member belongs to the class rather than to a particular object. Java supports static fields, static methods, static initialization blocks, and static nested classes.

  • A static field is shared by all instances of a class.
  • A static method can be called without creating an object, but it cannot directly access instance members.
  • A static initialization block runs when the class is initialized.

Can static methods be overridden in Java?

No. Static methods are resolved using the reference type and can only be hidden, not overridden. If a subclass declares a static method with the same signature, method selection is based on the compile-time type of the reference.

Is String a primitive data type in Java?

No. String is a final class in the java.lang package. A string literal creates or reuses a String object, and methods such as length(), substring(), and equals() operate on that object.

Can Java execute code before main()?

A static initialization block can run when the class containing it is initialized, before the JVM invokes that class’s main() method. However, a normal standalone Java application still needs a valid entry point to be launched in the usual way.

Why is Java called platform independent?

The Java compiler normally translates source code into JVM bytecode. A compatible Java Virtual Machine can execute that bytecode on different operating systems and processor architectures. Platform independence therefore comes from standardized bytecode and platform-specific JVM implementations.

How is Java source code executed?

The compiler javac converts .java source files into .class bytecode files. The JVM loads and verifies the bytecode, then interprets it or compiles frequently executed code into native machine instructions using a Just-In-Time compiler.

</>
Copy
Java source (.java) → javac → bytecode (.class) → JVM → native execution

What is a Just-In-Time compiler in Java?

A JIT compiler is part of the JVM execution engine. It identifies frequently executed bytecode and compiles it into native machine code while the application is running. This allows the JVM to optimize code using runtime information such as actual call patterns and frequently used branches.

What are Java varargs and what rules apply?

Varargs allow a method to accept zero or more arguments of the same declared type. The syntax uses an ellipsis, and the compiler packages the supplied values into an array.

  • A method can have only one varargs parameter.
  • The varargs parameter must be the final parameter.
  • Varargs methods can be overloaded, but ambiguous overloads should be avoided.
</>
Copy
static int sum(int... values) {
    int total = 0;
    for (int value : values) {
        total += value;
    }
    return total;
}

What gives Java its write once, run anywhere behavior?

Java bytecode is designed to run on any compatible JVM. The same compiled application can often run unchanged across systems, although native libraries, operating-system integration, file paths, encodings, and environment-specific behavior can still affect portability.

Can main() be declared as static public void?

Yes. Java permits modifiers in either order, so both public static void main(String[] args) and static public void main(String[] args) compile. The conventional order is public static.

Java Constructor and Object-Oriented Interview Questions

What is the purpose of a default constructor?

If a class declares no constructor, the compiler supplies a no-argument constructor. That generated constructor invokes the superclass constructor and leaves instance fields with their default values, such as 0, false, or null. If any constructor is declared explicitly, Java does not generate the default constructor.

Why are constructors not inherited?

A constructor initializes an instance of the class in which it is declared and has the same name as that class. A subclass has its own constructors, but each subclass constructor must invoke a superclass constructor either explicitly with super(...) or implicitly through super().

What does a constructor return in Java?

A constructor has no return type, not even void, and it cannot return a value. The new expression allocates an object and evaluates to a reference after construction completes.

Why can constructors not be final, static, or abstract?

  • final: Constructors are not inherited or overridden, so preventing overriding has no meaning.
  • static: A constructor initializes a new object, while a static member belongs to the class.
  • abstract: A constructor must contain executable initialization logic and cannot be implemented later by a subclass.

Why is the main method static?

The JVM can invoke a static entry-point method without first constructing an instance of the application class. The required launcher signature is conventionally public static void main(String[] args).

Can a normal Java application run without main()?

A class launched directly by the standard Java launcher needs a valid main() method. Static blocks may execute during class initialization, but modern JVMs still report that the main method is missing if no supported entry point exists. Framework-managed applications may use another bootstrap mechanism supplied by the framework.

Why is Object the root class of Java classes?

Every Java class directly or indirectly extends java.lang.Object. It supplies common methods such as equals(), hashCode(), toString(), getClass(), wait(), notify(), and notifyAll().

Why does Java not support multiple inheritance of classes?

Java avoids multiple inheritance of implementation because inheriting conflicting state or method implementations from several classes can create ambiguity and complicate object construction. A class may extend one class and implement multiple interfaces. Interfaces can provide default methods, and Java defines rules for resolving conflicts between them.

Can public class Myclass be stored in Yourclass.java?

No. A top-level public class must be declared in a source file with the same case-sensitive name, so public class Myclass must be stored in Myclass.java.

Do you need to import java.lang?

No. Types in java.lang, including String, Object, System, and wrapper classes, are imported automatically.

What is the result of Java remainder expressions with negative values?

</>
Copy
-14%3
14%3

The results are:

-2
2

For integer operands, Java’s remainder has the same sign as the dividend, which is the left operand.

Can an interface contain a concrete method?

Yes. Modern Java interfaces may contain default methods, static methods, and private helper methods. An instance method with a body must be declared using an allowed modifier such as default or private. The following original example does not compile because the method body is provided without such a modifier.

Example

</>
Copy
package sample;
public interface Interview{
	void display(){
	}
}
</>
Copy
public interface Interview {
    default void display() {
        System.out.println("default implementation");
    }
}

Can you create an object directly from an interface?

No. An interface cannot be instantiated directly. You can declare a variable of an interface type and assign it an instance of a class, anonymous class, lambda expression for a functional interface, or other implementation.

Java Packages Interview Questions

Can the same class or package be imported twice?

Duplicate import declarations are redundant but generally do not create duplicate class loading. Imports are compile-time name-resolution declarations; they do not instruct the JVM to load every imported class.

What is a Java package and why is it used?

A package is a namespace used to organize related classes, interfaces, records, enums, and annotations. Packages help prevent naming conflicts, support access control, improve modular organization, and make APIs easier to maintain and reuse.

Does importing a package import its subpackages?

No. Importing tutorial.* imports accessible types directly inside tutorial, not types in tutorial.employ. A subpackage must be imported separately or its classes must be referenced using fully qualified names.

import tutorial.employ.*;

Java Exception Handling Interview Questions

What is an exception in Java?

An exception is an object that represents an abnormal condition encountered while a program is running. When an exception is thrown, normal control flow stops and the JVM searches the current method and its callers for a compatible handler. If no handler is found, the thread terminates and the JVM normally prints a stack trace.

Can Java have a standalone try block?

No. A try statement must be followed by at least one catch block, a finally block, or be part of a valid try-with-resources statement.

</>
Copy
public class Tutorial{
	public static void main(String arg[]) {
		try{
		}
	}
}

The preceding code does not compile because the try block is not followed by catch or finally.

Why does this try-catch example fail to compile?

</>
Copy
class Example {
	public static void main(String arg[]) {
		try{
		}
		System.out.println(“tutorial”);
		catch(){
		}
	}
}

The code has several compile-time errors. A catch block must immediately follow its associated try block, a catch parameter type and variable are required, and the example uses typographic quotation marks instead of normal Java string quotes.

Can one catch block handle multiple exception types?

Yes. A multi-catch clause separates alternatives with |. The alternatives cannot be related by subclassing because catching the parent type would already cover its child type.

catch(ArithmeticException | ArrayStoreException e) {
	System.out.println(e);
}

Can a class contain more than one finally block?

Yes. A class may contain many separate try statements, and each may have its own finally block. A single try statement can have only one associated finally block.

What is the difference between checked and unchecked exceptions?

Checked exceptions are subclasses of Exception other than RuntimeException. The compiler requires them to be caught or declared. Unchecked exceptions are subclasses of RuntimeException and do not have that compile-time requirement. Classes derived from Error are also unchecked and usually represent serious runtime conditions that applications do not attempt to recover from directly.

What is exception chaining?

Exception chaining preserves an underlying cause while throwing a higher-level exception. Prefer constructors that accept a cause when available, such as new IllegalStateException("message", cause). The following example uses initCause().

</>
Copy
import java.io.IOException;
public class ChainedException {
	public static void divide(int a, int b) {
		if(b==0) {
			ArithmeticException ae = new ArithmeticException("top layer");
			ae.initCause( new IOException("cause") );
			throw ae;
		} else {
			System.out.println(a/b);
		}
	}
	public static void main(String[] args) {
		try {
			divide(5, 0);
		} catch(ArithmeticException ae) {
			System.out.println( "caught : " +ae);
			System.out.println("actual cause: "+ae.getCause());
		}
	}
}

Java String Interview Questions

Why are Java Strings immutable?

A String object’s character sequence cannot be changed after construction. Reassigning a variable only makes that variable refer to another object. Immutability supports safe sharing, string pooling, predictable hashing, and easier use across threads.

</>
Copy
String str=”value”;

The original block above uses typographic quotes and would need normal double quotes to compile. Reassigning the reference creates or selects another string object:

</>
Copy
str=”new value”;

Can the String class be extended?

No. java.lang.String is explicitly declared final, so it cannot be subclassed.

Why were StringBuilder and StringBuffer introduced?

Repeatedly modifying a string with concatenation can create many temporary immutable objects. StringBuilder and StringBuffer maintain a mutable character buffer, making repeated append, insert, and delete operations more direct. StringBuffer synchronizes its methods; StringBuilder does not.

What is the difference between == and equals()?

For object references, == tests whether both references point to the same object. The equals() method tests logical equality as defined by the class. String overrides equals() to compare character content.

How do you convert between String and int?

Use Integer.parseInt() when a primitive int is required and Integer.valueOf() when an Integer object is useful. Convert an integer to text with String.valueOf(number) or Integer.toString(number).

</>
Copy
public class ConvertStringToInteger {
	public static void main(String[] args) {
		String str1 = "5";
		int result = Integer.parseInt(str1);
		System.out.println(result);
		String str2 = "5";
		Integer result2 = Integer.valueOf(str2);
		System.out.println(result2);
	}
}

What is the Java String pool?

The string pool is a JVM-managed table of canonical string instances. String literals are interned, so identical literals normally refer to the same pooled object. Calling intern() returns the canonical representation. In modern HotSpot JVMs the pool is associated with heap-managed strings; the older statement that it resides in PermGen is outdated.

Why can char[] be preferable to String for passwords?

A character array can be overwritten after use, while an immutable String cannot be cleared in place. This may reduce the period for which a password remains plainly represented in application memory. It does not guarantee removal from all copies, logs, buffers, or memory snapshots, so secure handling still requires care.

Which String concatenation methods are available?

  1. The + operator, which the compiler may optimize.
  2. String.concat().
  3. StringBuilder.append() or StringBuffer.append().
  4. String.join() or Collectors.joining() for delimited values.

What is the difference between String, StringBuilder, and StringBuffer?

  • String is immutable.
  • StringBuilder is mutable and normally preferred for local, single-threaded string construction.
  • StringBuffer is mutable and synchronizes its public methods, but compound operations may still require external coordination.

Java Multithreading Interview Questions

How can T2 run after T1 and T3 after T2?

Call join() in the coordinating thread: start T1 and join it, then start T2 and join it, then start T3. In production code, executors, futures, completion stages, or structured concurrency may express dependencies more clearly.

Why is thread scheduling unpredictable?

The operating system and JVM scheduler decide when runnable threads receive processor time. Scheduling can vary between executions because of timing, processor count, workload, synchronization, and operating-system decisions. Correct concurrent code must not depend on a particular interleaving unless that order is enforced explicitly.

Are Java threads lightweight processes?

A thread is commonly called lightweight because threads in the same process share the process address space and resources. A thread does not become a heavyweight process merely because it runs alongside a thread from another process. Platform threads still have operating-system scheduling and stack costs; virtual threads provide a lighter concurrency model for many blocking tasks.

How are threads created in Java?

Classic approaches include extending Thread or implementing Runnable. In application code, it is usually better to submit tasks to an ExecutorService, use CompletableFuture, or use virtual threads where appropriate, rather than manually managing many thread objects.

What is the difference between a process and a thread?

A process has its own virtual address space and operating-system resources. Threads within one process share heap memory and many process resources, while each thread has its own call stack and execution state. Process isolation is stronger; thread communication is cheaper but requires synchronization around shared mutable data.

What are preemptive scheduling and time slicing?

In preemptive scheduling, the scheduler may interrupt a running thread so another runnable thread can execute. Time slicing assigns runnable threads bounded intervals of processor time. Java does not guarantee a specific scheduling algorithm, so application correctness should not depend on priorities or time slices.

Why are wait(), notify(), and notifyAll() declared in Object?

These methods operate on an object’s intrinsic monitor. Any object can be used as a synchronization lock, so monitor coordination belongs to Object. A thread must own the object’s monitor before calling these methods, otherwise IllegalMonitorStateException is thrown.

What is the difference between sleep() and wait()?

  • Thread.sleep() pauses the current thread for a period and does not release intrinsic locks it already owns.
  • Object.wait() must be called while owning that object’s monitor, releases that monitor, and waits for notification, interruption, or timeout.

What is the difference between a user thread and a daemon thread?

The JVM normally remains alive while any non-daemon thread is running. Daemon threads provide background services and do not prevent JVM termination. A thread’s daemon status must be set before the thread starts, and a child thread initially inherits the daemon status of its creator.

What happens if start() is called twice on the same Thread?

The second call throws IllegalThreadStateException. A Thread instance can be started only once; create a new thread or resubmit a task to an executor when repeated execution is needed.

What is a deadlock?

A deadlock occurs when threads wait indefinitely for locks or resources held by one another. A common example is T1 holding lock A while waiting for B, and T2 holding B while waiting for A. Consistent lock ordering, timeouts, reducing nested locking, and higher-level concurrency utilities help prevent deadlocks.

What is a race condition and how is it prevented?

A race condition occurs when a result depends on unsafely interleaved access to shared mutable state. Prevention techniques include synchronization, locks, atomic variables, concurrent collections, immutability, thread confinement, and message-passing designs.

What is context switching?

Context switching is the act of pausing one executing thread or process and restoring another. It involves scheduler work and saving or restoring execution state. Excessive context switching can reduce throughput.

What does join() do?

join() makes the calling thread wait until the target thread terminates, or until an optional timeout expires. It does not stop every running thread.

What is the difference between notify() and notifyAll()?

notify() wakes one arbitrary thread waiting on the same monitor. notifyAll() wakes all waiting threads, which then compete to reacquire the monitor and recheck their condition. Waiting should normally occur in a loop because wakeups do not guarantee that the required condition is true.

How is thread safety achieved in Java?

Thread safety can be achieved through immutable objects, synchronized blocks and methods, explicit locks, atomic classes, concurrent collections, confinement of mutable state, safe publication, and designs that avoid sharing mutable data. The volatile keyword provides visibility and ordering guarantees but does not make compound operations such as increment automatically atomic.

Java Collections Framework Interview Questions

How does HashMap work in Java?

HashMap stores key-value mappings in buckets. It uses the key’s hashCode() to choose a bucket and equals() to distinguish keys within that bucket. Adding an equal key replaces the value associated with that key. The map may resize when its size passes a threshold derived from capacity and load factor. Modern implementations may convert heavily populated buckets into tree-based structures when the required conditions are met.

What is the difference between an array and ArrayList?

  • An array has a fixed length; an ArrayList grows and shrinks dynamically.
  • Arrays can directly store primitives or object references; ArrayList stores object references and uses boxing for primitive wrapper values.
  • Arrays have language-level indexing and a length field; ArrayList provides collection methods such as add(), remove(), and contains().
  • Use an array for fixed-size, compact, performance-sensitive data; use ArrayList when the number of elements changes or collection APIs are useful.

What is the difference between Enumeration and Iterator?

Enumeration is a legacy traversal interface used by older classes such as Vector and Hashtable. Iterator is part of the Collections Framework and may support removal through remove(). Neither interface automatically makes concurrent modification safe. Many standard iterators are fail-fast on a best-effort basis.

Why is the Java Collections Framework needed?

The Collections Framework provides standard interfaces and implementations for lists, sets, queues, deques, and maps, together with algorithms and utility methods. It reduces custom data-structure code and allows APIs to program against abstractions such as List, Set, and Map.

How do you convert an ArrayList to an array?

Use toArray(). To obtain a typed array, use an array generator or pass an appropriately typed array.

</>
Copy
List<String> names = List.of("Asha", "Ravi");
String[] values = names.toArray(String[]::new);

What is the difference between List and Set?

A List is ordered, index-based, and allows duplicates. A Set does not allow duplicate elements according to its equality rules. Ordering depends on the implementation: HashSet does not guarantee iteration order, LinkedHashSet preserves insertion order, and TreeSet maintains sorted order.

What is the difference between Comparable and Comparator?

Comparable<T> defines a class’s natural order through compareTo(). Comparator<T> defines an external ordering through compare(), allowing several sorting strategies without modifying the compared class.

What does fail-safe iterator mean?

Fail-safe is an informal term, not a formal Java API category. It usually describes iterators that traverse a snapshot or a data structure designed for concurrent access, such as CopyOnWriteArrayList or ConcurrentHashMap. Their behavior depends on the collection and is often weakly consistent rather than guaranteed to reflect every concurrent update.

Why does HashMap not store duplicate keys?

A map associates one current value with each key. When put() receives a key that is equal to an existing key, it replaces that key’s value. Hash collisions between different keys are normal and are handled within the bucket; a collision does not mean the keys are duplicates.

Which AWT containers use BorderLayout by default?

In AWT, Window, Frame, and Dialog use BorderLayout by default. A Panel uses FlowLayout by default.

Java Applets, AWT Controls, and Layout Interview Questions

Java applets are obsolete and are no longer supported by modern web browsers. Applet questions may still appear in legacy coursework, but current Java interviews are more likely to focus on desktop UI toolkits, web frameworks, or backend development.

What was the difference between an applet and a Java application?

An applet was designed to run inside a browser or applet viewer under a managed lifecycle. A Java application is launched independently and normally begins at main(). Browser plug-in support for applets has been removed from modern browsers, and the applet API is deprecated for removal.

What is the difference between Scrollbar and ScrollPane?

An AWT Scrollbar is an adjustable control that represents a numeric value. A ScrollPane is a container that displays a child component through a scrollable viewport and manages scrolling for that content.

Why are layout managers used in Java UI code?

Layout managers calculate component size and position based on container size, component preferences, and layout rules. They adapt better than fixed coordinates when a window is resized, fonts differ, text is localized, or the application runs on another platform.

What are the limitations of GridLayout?

GridLayout gives every cell the same size, so it is unsuitable when components need different widths, heights, or alignment behavior. GridBagLayout offers more control but is more complex.

How can controls be manually positioned in an AWT or Swing container?

Set the container layout to null and call setBounds() on each component. This absolute positioning is generally discouraged because it does not adapt well to resizing, fonts, localization, or platform differences.

What is the difference between TextField and TextArea?

An AWT TextField accepts a single line of text. A TextArea accepts multiple lines and can display scrollbars depending on its configuration.

Java Coding Questions Commonly Asked in Interviews

  1. Check whether a string is a palindrome.
  2. Reverse a string without using a library reverse method.
  3. Check whether two strings are anagrams.
  4. Calculate factorial iteratively and recursively.
  5. Generate Fibonacci numbers and discuss overflow.
  6. Reverse a singly linked list.
  7. Implement a queue using two stacks.
  8. Find the longest substring without repeating characters.
  9. Implement producer-consumer coordination.
  10. Detect or avoid a deadlock.
  11. Compare sorting algorithms such as merge sort, quicksort, insertion sort, heap sort, and counting sort.
  12. Use a priority queue to find the top K values.
  13. Write basic TCP and UDP client-server programs.

Java Interview Questions for Experienced Developers

What is the contract between equals() and hashCode()?

If two objects are equal according to equals(), they must return the same hash code. Unequal objects may still have the same hash code. Fields used by these methods should normally remain stable while an object is used as a key in a hash-based collection.

What is the difference between final, finally, and finalize?

final is a language keyword used with variables, methods, and classes. finally is an exception-handling block. finalize() was an unreliable object-cleanup mechanism and is deprecated for removal; use explicit resource management, try-with-resources, or cleaner-based designs only when appropriate.

What is the difference between volatile and synchronized?

volatile provides visibility and ordering guarantees for reads and writes to one variable. synchronized also provides mutual exclusion for a critical section. A volatile read-modify-write operation such as count++ is still not atomic.

When should Optional be used?

Optional is most useful as a return type when absence is a normal result. It is generally not intended as a universal replacement for every nullable field, method parameter, collection element, or serialization property.

What is the difference between Stream and Collection?

A collection stores elements. A stream describes a pipeline of operations over a source and is normally consumed once. Stream operations may be lazy, and parallel streams require careful consideration of ordering, thread safety, workload size, and the common fork-join pool.

Java Interview Questions FAQ

Which Java interview questions should freshers study first?

Start with JDK, JRE, JVM, primitive and reference types, classes, objects, constructors, inheritance, interfaces, overloading, overriding, strings, exceptions, arrays, collections, and basic threading. Practice explaining each concept with a small code example.

What Java questions are common for 3 to 5 years of experience?

Interviewers commonly move beyond definitions to HashMap internals, equals/hashCode, immutable classes, exception design, executors, synchronization, volatile, concurrent collections, streams, database access, testing, and debugging production issues.

Should interview answers mention the Java version?

Yes, when behavior or APIs differ by release. Interface default methods, modules, records, sealed classes, pattern matching, virtual threads, and deprecations are version-sensitive topics. State the relevant version instead of presenting old behavior as universal.

How should Java coding interview solutions be explained?

Clarify assumptions, describe the approach, analyze time and space complexity, implement readable code, test edge cases, and discuss alternatives. For concurrent code, also explain memory visibility, synchronization, cancellation, and failure handling.

Are applet questions still relevant in Java interviews?

They are mainly relevant to legacy systems or older academic material. Modern browser environments do not support Java applets, so current preparation should prioritize core Java, collections, concurrency, streams, JVM behavior, testing, and the technologies named in the job description.

Java Interview Questions Editorial QA Checklist

  • Verify that answers distinguish current Java behavior from obsolete applet, PermGen, and finalization material.
  • Check every Java code sample for normal quotation marks, valid types, required imports, and a compilable method or class context.
  • Confirm that concurrency answers do not promise a thread schedule, misuse volatile, or imply that join() stops unrelated threads.
  • Confirm that collections answers accurately describe hashCode(), equals(), duplicate keys, collisions, ordering, and iterator behavior.
  • Keep experience-level guidance aligned with the actual role instead of treating one question list as suitable for every Java position.