JAVA INTERVIEW QUESTION
JAVA INTERVIEW QUESTION
JAVA PROGRAMMING
16. What is the difference between an interface and multiple inheritance in Java?
18. What is the difference between a shallow copy and a deep copy in Java?
20. What are inner classes, and when would you use them?
Collections Framework
35. What are synchronized blocks, and why are they needed?
40. Explain deadlock, livelock, and starvation. How can you prevent them?
Exception Handling
44. Can we have multiple catch blocks for a single try block?
58. Explain the use of the Runtime and System classes in memory management.
64. What is the difference between forEach and map in Java Streams?
68. How do you handle date and time in Java 8 using the java.time package?
78. What is the NIO package, and how does it differ from traditional I/O?
85. What are servlets, and how are they used in web applications?
93. What are design patterns in Java? Can you explain a few with examples?
▪ Object-Oriented Programming
▪ Multithreading Support
o Answer:
Java achieves platform independence through the Java Virtual Machine
(JVM). The Java compiler converts source code into bytecode, which can run
on any system with a compatible JVM, irrespective of the underlying
hardware or OS.
o Answer:
o Answer:
Java uses automatic garbage collection to reclaim unused memory.
Developers don’t need to explicitly deallocate memory, as the JVM identifies
and removes objects no longer referenced.
o Answer:
o Answer:
o Answer:
Encapsulation is the practice of restricting direct access to object fields and
methods. It is achieved by declaring fields as private and providing public
getter and setter methods.
o Answer:
Polymorphism allows one interface to represent different underlying forms.
It is implemented through method overloading (compile-time) and
overriding (runtime).
o Answer:
Constructors initialize an object when it’s created. They can be overloaded
by defining multiple constructors with different parameter lists in the same
class.
Collections Framework
o Answer:
o Answer:
o Answer:
The Iterator interface provides a way to traverse a collection sequentially.
Methods include hasNext(), next(), and remove().
o Answer:
Collections can be sorted using the Collections.sort() method for lists.
Custom sorting can be achieved by implementing the Comparator or
Comparable interface.
o Platform Independence: Write code once and run it anywhere using the JVM.
o Extensive Libraries: Rich API for networking, I/O, multithreading, and more.
o JDK: Java Development Kit includes tools like the compiler (javac),
debugger, and libraries for developing Java programs.
o JRE: Java Runtime Environment contains the JVM and libraries required to
run Java programs but does not include development tools.
o ==: Compares memory references, checking if two objects point to the same
memory location.
o Providing public getter and setter methods to access and update private
fields.
java
Copy code
class Example {
Collections Framework
o ArrayList:
o LinkedList:
▪ Uses a doubly-linked list to store elements.
o If two keys map to the same bucket (collision), they are stored in a linked list
or tree within that bucket.
o HashMap: Not synchronized, allows one null key and multiple null values.
java
Copy code
• Abstract Class:
o Can have abstract and concrete methods.
• Interface:
o Contains only abstract methods (until Java 7). From Java 8 onwards,
supports default and static methods.
• Static Variables: Belong to the class rather than any object instance. Shared among
all objects.
• Static Methods: Can be called without creating an instance of the class. Cannot
access non-static fields or methods directly.
Example:
java
Copy code
class Example {
• Packages are namespaces used to group related classes and interfaces, improving
code organization and reusability.
Exception Handling
java
Copy code
try {
int data = 50 / 0;
} finally {
Example:
java
Copy code
java
Copy code
// Read file
} catch (IOException e) {
e.printStackTrace();
Multithreading
• Thread: Requires extending the Thread class. Cannot extend other classes
simultaneously.
java
Copy code
System.out.println("Running thread");
}
• synchronized: Ensures mutual exclusion, allowing only one thread to access the
critical section.
• volatile: Ensures visibility of changes made by one thread to other threads without
locking.
• wait(): Causes the current thread to wait until another thread invokes notify().
• Stack Memory: Stores method calls and local variables. Managed automatically
and is thread-specific.
Example:
java
Copy code
class Example implements Serializable {
java
Copy code
@Override
System.out.println("Finalize called");
Note: Starting with Java 9, finalize() is deprecated due to unpredictable behavior and
poor performance.
• Comparable:
java
Copy code
class Student implements Comparable<Student> {
int age;
@Override
• Comparator:
java
Copy code
@Override
java
Copy code
java
Copy code
Example:
java
Copy code
java
Copy code
@FunctionalInterface
interface Greeting {
void sayHello();
Java Streams
java
Copy code
numbers.stream()
.filter(n -> n % 2 == 0)
.forEach(System.out::println);
42. What is the difference between map() and flatMap() in Java Streams?
Answer:
java
Copy code
names.stream().map(String::toUpperCase).forEach(System.out::println);
java
Copy code
numbers.stream().flatMap(List::stream).forEach(System.out::println);
java
Copy code
System.out.println(name.orElse("Default Name"));
• Collection:
o Eagerly evaluated.
• Stream:
o Provides a functional approach for data processing.
o Lazily evaluated.
java
Copy code
System.out.println(sum); // 6
Java 8 Features
46. What is the difference between default and static methods in interfaces?
Answer:
java
Copy code
interface MyInterface {
Copy code
numbers.forEach(System.out::println);
• Parallel Streams: Split the data and process it in parallel using multiple threads.
Example:
java
Copy code
list.parallelStream().forEach(System.out::println);
50. What are the differences between Predicate, Function, and Supplier?
Answer:
java
Copy code
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(evenNumbers); // [2, 4]
java
Copy code
// Partitioning by length
java
Copy code
• Lock fairness.
java
Copy code
lock.lock();
try {
// Critical section
} finally {
lock.unlock();
java
Copy code
57. What is the difference between synchronized block and synchronized method?
Answer:
• Synchronized Method: Locks the entire method, allowing one thread to execute at a
time.
java
Copy code
void method() {
synchronized(this) { ... }
java
Copy code
class Singleton {
private Singleton() {}
return instance;
java
Copy code
class ShapeFactory {
return null;
java
Copy code
class Subject {
java
class Car {
private String engine;
private int wheels;
java
Copy code
String type;
@Override
return super.clone();
java
Copy code
@Override
vlcPlayer.playVLC(fileName);
java
Copy code
class Service {
class Client {
Client(Service service) {
this.service = service;
}
Service service = new Service();
Java Multithreading
java
Copy code
System.out.println("Thread running...");
t.start();
67. New: When a thread is created but not started (Thread t = new Thread();).
68. Runnable: When the thread is ready to run but is waiting for CPU time.
• sleep(): Called on a thread; pauses execution for a specified time without releasing
the lock.
Example:
java
Copy code
java
Copy code
System.out.println("Synchronized method");
java
Copy code
synchronized void methodA() {
java
Copy code
java
Copy code
executor.shutdown();
java
Copy code
java
Copy code
daemonThread.setDaemon(true);
daemonThread.start();
java
Copy code
java
Copy code
@RestController
@GetMapping("/hello")
java
Copy code
@Entity
@Id
@GeneratedValue
java
Copy code
@Entity
@Id
@GeneratedValue
java
Copy code
@Transactional
repository.save(entity);
81. What are some best practices for exception handling in Java?
Answer:
java
Copy code
try {
// Code
} catch (IOException e) {
e.printStackTrace();
} finally {
// Cleanup
• Optimize algorithms.
xml
Copy code
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.5</version>
</dependency>
java
Copy code
@Test
void testAddition() {
groovy
Copy code
dependencies {
implementation 'org.springframework:spring-core:5.3.5'
Miscellaneous
• What is a Stream?