0% found this document useful (0 votes)
68 views6 pages

25 Essential Java Interview Questions

The document contains 25 Java interview questions and answers, covering a range of topics from basic to advanced concepts. Key topics include Java's features, differences between various Java components (JDK, JRE, JVM), data structures (ArrayList vs. LinkedList), exception handling, access modifiers, and multithreading. It also addresses advanced concepts like functional interfaces, streams, and deadlocks.

Uploaded by

ottacc2022
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views6 pages

25 Essential Java Interview Questions

The document contains 25 Java interview questions and answers, covering a range of topics from basic to advanced concepts. Key topics include Java's features, differences between various Java components (JDK, JRE, JVM), data structures (ArrayList vs. LinkedList), exception handling, access modifiers, and multithreading. It also addresses advanced concepts like functional interfaces, streams, and deadlocks.

Uploaded by

ottacc2022
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Here are 25 Java interview questions along with their answers, covering basic to advanced

concepts:

1. What is Java?

Java is a high-level, object-oriented programming language developed by Sun Microsystems


(now owned by Oracle). It is platform-independent due to its "Write Once, Run Anywhere"
(WORA) feature enabled by the Java Virtual Machine (JVM).

2. What are the main features of Java?

 Platform Independence (JVM)


 Object-Oriented
 Automatic Memory Management (Garbage Collection)
 Multi-threaded
 Secure and Robust
 Rich API

3. What is the difference between JDK, JRE, and JVM?

Component Description
Includes JRE + development tools (compiler, debugger,
JDK (Java Development Kit)
etc.)
JRE (Java Runtime
Includes JVM + libraries to run Java applications
Environment)
JVM (Java Virtual Machine) Converts bytecode into machine-specific code

4. What is the difference between an interface and an abstract class?

Feature Abstract Class Interface


Can have both abstract & Only abstract methods (Java 7); Java 8+
Methods
concrete methods allows default & static methods
Variables Can have instance variables Only public, static, and final constants
Multiple
Not supported Supported
Inheritance
Constructor Yes No

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


 == compares memory reference (checks if both objects refer to the same memory
location).
 .equals() compares content (checks if two objects have the same value).

Example:

String s1 = new String("Java");


String s2 = new String("Java");
[Link](s1 == s2); // false (different objects)
[Link]([Link](s2)); // true (same content)

6. What are wrapper classes in Java?

Wrapper classes convert primitive types into objects.


Example:

 int → Integer
 double → Double
 char → Character

Example:

Integer num = [Link](10); // Autoboxing


int value = [Link](); // Unboxing

7. What is the difference between ArrayList and LinkedList?

Feature ArrayList LinkedList


Storage Dynamic array Doubly linked list
Access time Fast (O(1) for get()) Slow (O(n) for get())
Insertion/Deletion Slow (O(n) at middle) Fast (O(1) at head/tail)

8. What is the difference between HashMap and Hashtable?

Feature HashMap Hashtable


Thread-safe No Yes (synchronized)
Null keys/values 1 null key, multiple null values No null keys or values
Performance Faster Slower

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

Feature String StringBuffer StringBuilder


Mutability Immutable Mutable Mutable
Thread-safe Yes Yes (synchronized) No (not synchronized)
Performance Slow Slower Fastest
Example:

StringBuilder sb = new StringBuilder("Hello");


[Link](" Java");
[Link](sb); // Hello Java

10. What is an exception in Java?

An exception is an unexpected event that disrupts program execution. Java has:

 Checked Exceptions (e.g., IOException)


 Unchecked Exceptions (e.g., NullPointerException)
 Errors (e.g., OutOfMemoryError)

Example:

try {
int a = 5 / 0;
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero!");
}

11. What are Java access modifiers?

Modifier Scope
public Accessible everywhere
protected Accessible within the same package + subclasses
default Accessible within the same package only
private Accessible within the same class only

12. What is polymorphism?

Polymorphism allows a method to have different forms.

 Compile-time polymorphism (Method Overloading)


 Runtime polymorphism (Method Overriding)

Example:

class Animal {
void sound() { [Link]("Animal makes a sound"); }
}
class Dog extends Animal {
void sound() { [Link]("Dog barks"); }
}

13. What is multithreading in Java?


Multithreading allows concurrent execution of multiple threads.
Example:

class MyThread extends Thread {


public void run() { [Link]("Thread running"); }
}
new MyThread().start();

14. What is the volatile keyword in Java?

volatile ensures that a variable's value is always read from main memory, preventing
caching issues in multi-threaded environments.

15. What is the final keyword in Java?

 Final variable → Cannot be reassigned.


 Final method → Cannot be overridden.
 Final class → Cannot be inherited.

Example:

final class MyClass { }


// class SubClass extends MyClass { } // Error: cannot inherit from final
class

16. What is serialization in Java?

Serialization converts an object into a byte stream for storage/transmission.

Example:

class Employee implements Serializable { int id; String name; }

17. What is the transient keyword?

transient prevents serialization of a variable.

Example:

class Employee implements Serializable {


transient int salary; // Won't be serialized
}

18. What is a constructor in Java?


A constructor initializes an object when it is created.

Example:

class Person {
Person() { [Link]("Constructor called"); }
}

19. What is the difference between throw and throws?

 throw → Used to explicitly throw an exception.


 throws → Declares exceptions in a method signature.

Example:

void myMethod() throws IOException { }

20. What is a functional interface in Java?

A functional interface has exactly one abstract method.

Example:

@FunctionalInterface
interface MyInterface {
void sayHello();
}

21. What are Java Streams?

Java Streams process data in a functional style.

Example:

List<String> names = [Link]("John", "Jane", "Jack");


[Link]().filter(n -> [Link]("J")).forEach([Link]::println);

22. What is the difference between Callable and Runnable?

 Runnable → Does not return a value.


 Callable → Returns a value.

Example:

Callable<Integer> task = () -> 10;


23. What is reflection in Java?

Reflection allows inspection/modification of classes, methods, and fields at runtime.

24. What is the purpose of the default method in interfaces?

default methods in interfaces provide implementation while allowing backward


compatibility.

25. What is a deadlock?

Deadlock occurs when two or more threads are waiting on each other, preventing execution.

Want more in-depth explanations? Let me know! 🚀

Common questions

Powered by AI

Java Streams offer a declarative approach to processing sequences of elements by using pipelining operations such as filter, map, and reduce, which enhance code readability and maintainability. Unlike traditional iteration, streams intrinsically support operations like filtering and parallel processing, providing more concise and potentially optimized ways to handle data workflows. This simplifies code for tasks like filtering names starting with 'J', which would require manual loops without streams .

Garbage collection in Java automatically handles memory management by reclaiming memory from objects no longer in use, preventing memory leaks and improving application stability. However, while it abstracts away manual memory management, it introduces challenges such as unpredictable GC pauses, which can cause latency in applications. Developers have limited control over when GC runs, necessitating understanding and adjustment of JVM parameters to optimize performance for specific application needs .

Wrapper classes in Java convert primitive types into objects, thereby enabling primitives to interact with collections which operate on objects and providing utility methods for conversion and manipulation. Autoboxing and unboxing support seamless type conversion operations needed for assigning, storing, and retrieving primitive values as objects, such as 'Integer' being a wrapper for 'int', demonstrating the flexibility and consistency they bring to Java's type system .

In Java, polymorphism allows methods to have different forms: compile-time polymorphism is achieved through method overloading, where multiple methods share the same name but differ in parameters. Runtime polymorphism is implemented through method overriding, where a method in a subclass overrides a method of the same signature in its superclass, allowing for dynamic method invocation. For instance, a 'Dog' class can override an 'Animal' class method sound() to return "Dog barks" instead of "Animal makes a sound" .

Multithreading in Java enables concurrent execution of multiple threads, allowing for efficient utilization of CPU by performing multiple operations simultaneously. This is critical in modern applications that require handling multiple tasks such as processing user interactions, performing I/O operations, and background processing without blocking the main thread, thereby improving performance and responsiveness. For example, with 'MyThread' extending 'Thread', the run method independently executes, demonstrating Java's multithreaded nature .

The 'volatile' keyword in Java ensures that a variable's value is always read from the main memory, rather than being cached to individual CPU caches. This is crucial in multi-threaded environments to maintain data consistency and visibility, as updates made by one thread on volatile variables are immediately visible to other threads. Without 'volatile', concurrent modifications might not be immediately reflected across threads due to caching, leading to inconsistent state and subtle concurrency bugs .

The Java Development Kit (JDK) includes the Java Runtime Environment (JRE) and provides development tools such as the compiler and debugger necessary for creating Java applications. The JRE, in contrast, comprises the Java Virtual Machine (JVM) and a set of libraries required to run Java applications, offering the execution environment but without development capabilities provided by the JDK .

The 'final' keyword in Java is used to create constants, enforce immutability, and prevent modification of content or behaviors. It can be applied to variables to ensure they cannot be reassigned, to methods to prevent overriding in subclasses, and to classes to prevent inheritance. For example, declaring a class as 'final' protects its methods from being redefined, which enhances security and stability in inheritance-heavy designs .

An abstract class in Java can have both abstract and concrete methods and can contain instance variables, allowing for a common base of code that subclasses can build upon. An interface, on the other hand, traditionally only contained abstract methods and allowed only public static final constants. However, since Java 8, interfaces can also include default and static methods, thus providing some concrete behavior. These changes introduce more flexibility in API design by reducing the need for extensive abstract class hierarchies solely for default behavior .

HashMap allows one null key and multiple null values, is not synchronized, and offers faster performance due to its non-thread-safe nature. Conversely, Hashtable is synchronized, which ensures thread safety but incurs performance overheads, disallowing null keys or values. Choosing between them depends on the application's need for thread safety: HashMap for performance in single-thread contexts and Hashtable for consistency across multiple threads, revealing a trade-off between speed and safety .

You might also like