SlideShare a Scribd company logo
Top Java Interview Questions for 10+ Year Experienced
Professionals
Java Interview Questions for 10 Years Experience
To excel in a Java interview with 10 years of experience, it’s crucial to have a deep understanding of advanced Java concepts,
multithreading, design patterns, and frameworks such as Spring and Hibernate. Your ability to tackle complex technical problems,
implement efficient solutions, and mentor junior developers will set you apart.
What can you expect in a Java interview for 10 years of experience?
The Java interview process for candidates with 10 years of experience is highly advanced, evaluating your deep expertise in Java
development, software architecture, and leadership skills. Here's what you can expect:
In-depth questions on core Java concepts, advanced OOP concepts, Multithreading, and memory management in Java.
Complex scenario-based tasks to assess your ability to write highly scalable, performant, and maintainable code.
Questions on Design patterns, focusing on Singleton, Factory, Observer, Strategy, and Decorator patterns.
Experience with Collection Framework, Spring, Hibernate, Spring Boot, and other enterprise-level frameworks.
Advanced knowledge of unit testing with frameworks like JUnit and Mockito, along with test-driven development (TDD) principles.
Expert understanding of Java performance tuning, including JVM internals, garbage collection, and heap management.
Hands-on experience with cloud services (AWS, Azure), REST and SOAP APIs, and integration with databases using JPA and
Hibernate.
Knowledge of CI/CD pipelines, containerization with Docker, and orchestration tools like Kubernetes.
Leadership experience, including mentoring junior developers, conducting code reviews, and designing enterprise architectures that
align with business requirements.
In this Java tutorial, we’ll focus on Java Interview Questions for 10 Years of Experience, dive deep into high-level topics, and offer
guidance on what interviewers expect from senior candidates. With the right preparation, you’ll be ready to showcase your expertise and
lead teams effectively.
Top 30 Java Interview Questions for 10 Years of Experience
1. How does the Java Memory Model (JMM) ensure visibility and ordering in multithreaded
programs?
Ans: The Java Memory Model (JMM) defines how threads interact through memory and ensures visibility and order of operations in a
multithreaded environment. Key principles include:
Volatile variables: Ensure visibility of updates across threads by preventing caching.
Happens-before relationship: Guarantees that one action’s effects are visible to another.
Synchronization: Enforces ordering and visibility via synchronized blocks or methods.
Example Code:
public class Main {
private volatile boolean flag = false;
public static void main(String[] args) {
Main example = new Main();
public void reader() {
// Small delay to let the writer thread run first
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Create and start writer thread
Thread writerThread = new Thread(new Runnable() {
@Override
public void writer() {
flag = true; // Visible to all threads
System.out.println("Writer thread has set flag to true.");
}
if (flag) {
System.out.println("Reader thread sees flag as true.");
} else {
System.out.println("Reader thread sees flag as false.");
}
}
Output
Example Code:
2. What is the difference between deep copy and shallow copy in Java?
Ans: In Java, a shallow copy creates a new object, but the fields are still references to the same objects as the original. In contrast, a deep
copy creates a completely independent copy of the original object, including the objects referenced by its fields. A deep copy is more
resource-intensive but ensures complete independence between the original and copied objects.
Try it Yourself >>
import java.util.ArrayList;
import java.util.List;
public void run() {
example.writer();
}
});
writerThread.start();
Writer thread has set flag to true.
Reader thread sees flag as true.
}
// Create and start reader thread
Thread readerThread = new Thread(new Runnable() {
@Override
public void run() {
example.reader();
}
});
readerThread.start();
}
// Shallow copy (reference copy) List
shallowCopy = originalList;
// Deep copy (creating a new ArrayList)
List deepCopy = new ArrayList<>(originalList);
originalList.add("C++");
System.out.println("Original List: " + originalList);
public class Main {
public static void main(String[] args) {
// Correcting the raw type usage by specifying the generic type
List originalList = new ArrayList<>();
originalList.add("Java");
Output
Output
Example Code:
3. What is the difference between HashMap and TreeMap in Java?
Ans: The main difference between HashMap and TreeMap is their ordering of keys:
Try it Yourself >>
Try it Yourself >>
HashMap: Does not maintain any order of the keys. It is faster and allows null keys and values.
TreeMap: Maintains the keys in sorted order based on their natural ordering or a custom comparator.
import java.util.*;
Original List: [Java, C++]
Shallow Copy: [Java, C++]
Deep Copy: [Java]
HashMap: {Java=100, C++=90}
TreeMap: {C++=90, Java=100}
Map treeMap = new TreeMap<>();
treeMap.put("Java", 100);
treeMap.put("C++", 90);
public class Main {
public static void main(String[] args) {
Map hashMap = new HashMap<>();
hashMap.put("Java", 100);
hashMap.put("C++", 90);
}
System.out.println("HashMap: " + hashMap);
System.out.println("TreeMap: " + treeMap);
}
System.out.println("Shallow Copy: " + shallowCopy);
System.out.println("Deep Copy: " + deepCopy);
}
}
Try it Yourself >>
Try it Yourself >>
Read More: HashMap in Java
Ans: Java’s garbage collection (GC) automatically reclaims memory by identifying and clearing objects that are no longer reachable from
active threads. It helps prevent memory leaks and ensures efficient memory management by using techniques like mark-and-sweep and
reference counting.
Ans: Lambda expressions in Java, introduced in Java 8, allow you to write instances of functional interfaces in a concise and expressive
way. They provide a more functional style of programming and are mainly used to implement methods of functional interfaces. The
syntax is: (parameters) -> expression.
5. How does Java’s Garbage Collection work?
4. Explain the concept of Lambda Expressions in Java.
Output
Example Code:
Example Code:
Java
C++
Python
import java.util.*;
}
System.gc(); // Hint for garbage collection
}
public class LambdaExample {
public static void main(String[] args) {
List names = Arrays.asList("Java", "C++", "Python");
// Lambda expression
names.forEach(name -> System.out.println(name));
}
}
public class GarbageCollectionExample {
public static void main(String[] args) {
GarbageCollectionExample example = new GarbageCollectionExample();
example = null; // Eligible for garbage collection
Output
Output
Example Code:
Example Code:
Try it Yourself >>
Read More: .NET Garbage Collection In-Depth
Ans: In Java:
String: Immutable, meaning its value cannot be changed once created.
StringBuilder: Mutable and not synchronized, suitable for single-threaded applications.
StringBuffer: Mutable and synchronized, suitable for multithreaded environments.
Ans: Functional interfaces are interfaces that contain exactly one abstract method. They are used primarily with lambda expressions and
method references to provide a more compact and readable code. Common examples are Runnable, Callable, and Comparator.
6. What are functional interfaces and how are they used in Java?
7. What are the differences between String, StringBuilder, and StringBuffer in Java?
Functional Interface method.
@FunctionalInterface
interface MyFunctionalInterface {
}
void myMethod();
public class StringExample {
public static void main(String[] args) {
String str1 = "Hello";
StringBuilder sb = new StringBuilder("World");
sb.append("!");
System.out.println(str1);
[Output may vary]
A message indicating that garbage collection is triggered might be printed.
public class FunctionalInterfaceExample {
}
public static void main(String[] args) {
MyFunctionalInterface myInterface = () -> System.out.println("Functional Interface method.");
myInterface.myMethod();
}
Output
Output
Example Code:
8. What isa reflectionin Java, and how is it used?
Ans: Reflection in Java is the ability of a program to examine and modify the structure and behavior of classes, methods, fields, etc. It is
mainly used for:
9. What is the use of default methods in Java interfaces?
Ans: Default methods allow you to add method implementations in interfaces without breaking the implementing classes. This feature,
introduced in Java 8, helps maintain backward compatibility with older versions of interfaces.
Try it Yourself >>
Try it Yourself >>
Accessing private members of a class.
Invoking methods dynamically.
Creating new objects at runtime.
Hello
World!
String length: 5
}
System.out.println(sb);
}
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws Exception {
Class cls = Class.forName("java.lang.String");
Method method = cls.getMethod("length");
String str = "Hello";
int length = (int) method.invoke(str); // invoking the 'length' method on the string object
System.out.println("String length: " + length);
}
}
Output
Example Code:
Example Code:
10. Explain the concept of Java Streams and provide an example.
Ans: Java Streams provide a functional approach to processing sequences of elements, such as collections, in a declarative way.
Streams can be processed in parallel, improving performance in large datasets. Key operations are map, filter, reduce, and collect.
Try it Yourself >>
import java.util.Arrays;
import java.util.List;
This is a default method.
public class Main implements MyInterface {
}
public static void main(String[] args) {
new Main().printMessage();
}
public class StreamExample {
public static void main(String[] args) {
List numbers = Arrays.asList(1, 2, 3, 4, 5);
interface MyInterface {
}
default void printMessage() {
System.out.println("This is a default method.");
}
// Correct way to sum using streams
int sum = numbers.stream().mapToInt(Integer::intValue).sum();
System.out.println("Sum: " + sum);
}
Output
Output
Example Code:
Example Code:
11. What is the difference between Concurrency and Parallelism in Java?
Ans: In Java:
12. What are the functional interfaces in Java, and how do they work with lambda expressions?
Ans: A functional interface is an interface that has exactly one abstract method, which can be implemented using lambda expressions.
Common examples include Runnable, Callable, and Comparator.
Try it Yourself >>
Try it Yourself >>
Concurrency: Refers to the ability of a system to manage multiple tasks at the same time but not necessarily execute them
simultaneously. Tasks might be executed on a single thread or distributed across multiple threads.
Parallelism: Refers to the simultaneous execution of tasks, typically using multiple processors or cores. It is a subset of concurrency
focused on performing multiple operations at the same time.
}
Sum: 15
Concurrency: Task 1
Concurrency: Task 2
Parallelism: Task 1
Parallelism: Task 2
public class ConcurrencyVsParallelism {
public static void main(String[] args) {
// Simulating concurrency using a single thread
System.out.println("Concurrency: Task 1");
System.out.println("Concurrency: Task 2");
}
// Simulating parallelism using two threads Thread task1 = new Thread(() ->
System.out.println("Parallelism: Task 1")); Thread task2 = new Thread(() ->
System.out.println("Parallelism: Task 2"));
task1.start();
task2.start();
}
Output
Output
Example Code:
13. What are the benefits of using Java Streams over traditional looping?
Ans: Java Streams provide several benefits over traditional looping mechanisms:
Try it Yourself >>
Try it Yourself >>
Declarative syntax: It allows you to express the logic in a more readable and concise way.
Built-in operations: You can filter, map, and reduce data with built-in methods.
Parallelism: Streams support parallel processing to improve performance on large datasets.
Addition: 8
import java.util.*;
@FunctionalInterface
interface MathOperation {
}
int operate(int a, int b);
}
System.out.println("Sum of even numbers: " + sum);
}
public class LambdaWithFunctionalInterface {
}
public static void main(String[] args) {
MathOperation addition = (a, b) -> a + b;
System.out.println("Addition: " + addition.operate(5, 3));
}
public class StreamExample {
public static void main(String[] args) {
List numbers = Arrays.asList(1, 2, 3, 4, 5); // Use List for type safety
// Using Stream to sum even numbers
int sum = numbers.stream()
.filter(n -> n % 2 == 0)
.mapToInt(Integer::intValue)
.sum();
// Filter even numbers
// Convert Integer to int
// Sum the integers
14. What is the role of Java's final keyword?
Ans: The final keyword in Java has different roles depending on where it is applied:
15. How does Java's Fork/Join Framework improve parallel computing, and how is it
implemented?
Ans: The Fork/Join Framework in Java is used to achieve parallelism by dividing tasks into smaller subtasks (forking) and then
combining their results (joining). It is part of the java.util.concurrent package and is especially useful for divide-and-conquer algorithms.
Try it Yourself >>
Final variables: Once initialized, their value cannot be changed.
Final methods: The method cannot be overridden by subclasses.
Final classes: The class cannot be subclassed.
Output
Example Code:
Example Code:
Value: 10
Sum of even numbers: 6
final class FinalClass {
final int value = 10;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.ForkJoinPool;
public class FinalExample {
}
public static void main(String[] args) {
FinalClass obj = new FinalClass();
obj.showValue();
}
}
final void showValue() {
System.out.println("Value: " + value);
}
class SumTask extends RecursiveTask { // Specify Integer as the type of result
private static final int THRESHOLD = 10;
private int[] numbers;
private int start;
Output
Total Sum: 5050
private int end;
}
return leftResult + rightResult;
}
}
public SumTask(int[] numbers, int start, int end) {
this.numbers = numbers;
this.start = start;
this.end = end;
}
@Override
protected Integer compute() {
if (end - start <= THRESHOLD) {
int sum = 0;
for (int i = start; i < end; i++) {
sum += numbers[i];
}
return sum;
} else {
int mid = (start + end) / 2;
SumTask leftTask = new SumTask(numbers, start, mid);
SumTask rightTask = new SumTask(numbers, mid, end);
public class ForkJoinExample {
public static void main(String[] args) {
int[] numbers = new int[100];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i + 1; // Fill the array with numbers 1 to 100
}
}
int result = pool.invoke(task); // Invoke the task using the pool
System.out.println("Total Sum: " + result); // Print the total sum
}
leftTask.fork(); // Start the left task asynchronously
int rightResult = rightTask.compute(); // Compute the right task directly
int leftResult = leftTask.join(); // Wait for the left task to complete
ForkJoinPool pool = new ForkJoinPool(); // Create a ForkJoinPool to manage tasks
SumTask task = new SumTask(numbers, 0, numbers.length); // Create the sum task
Try it Yourself >>
16. Explain the Java Serialization process and how to implement it.
Ans: Serialization in Java is the process of converting an object into a byte stream to save it to a file or transmit it over a network. The
Serializable interface is used to mark a class whose objects can be serialized.
Try it Yourself >>
Output
Example Code:
import java.io.*;
Object serialized: Alice, 30
Deserialized Person: Alice, 30
class Person implements Serializable {
String name;
int age;
public Person(String name, int age) {
}
this.name = name;
this.age = age;
}
public class SerializationExample {
public static void main(String[] args) {
Person person = new Person("Alice", 30);
// Serialize the object
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
out.writeObject(person);
System.out.println("Object serialized: " + person.name + ", " + person.age);
} catch (IOException e) {
System.out.println("Serialization error: " + e.getMessage());
}
// Deserialize the object
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("person.ser"))) {
}
Person deserializedPerson = (Person) in.readObject();
System.out.println("Deserialized Person: " + deserializedPerson.name + ", " + deserializedPerson.age);
} catch (IOException | ClassNotFoundException e) {
System.out.println("Deserialization error: " + e.getMessage());
}
}
17. What are Java Annotations, and how are they used?
Ans: Java annotations provide metadata about the code. They are used to give information to the compiler or runtime environment and
can be used for documentation, code analysis, or generating code. Some common annotations include @Override, @Deprecated, and
@SuppressWarnings.
Try it Yourself >>
Output
Example Code:
Annotation value: Hello, World!
import java.lang.annotation.*;
import java.lang.reflect.Method;
}
// Call the method
example.displayMessage();
}
// Class to demonstrate annotation usage
public class Main {
// Define the custom annotation with runtime retention
@Retention(RetentionPolicy.RUNTIME)
@interface MyCustomAnnotation {
}
String value();
@MyCustomAnnotation(value = "Hello, World!")
public void displayMessage() {
System.out.println("This is a custom annotation.");
}
// The main method to execute the program
public static void main(String[] args) throws Exception {
// Create an instance of Main (formerly AnnotationExample)
Main example = new Main();
// Use reflection to check if the method is annotated
Method method = example.getClass().getMethod("displayMessage");
// Check if the method has the MyCustomAnnotation annotation
if (method.isAnnotationPresent(MyCustomAnnotation.class)) {
MyCustomAnnotation annotation = method.getAnnotation(MyCustomAnnotation.class);
System.out.println("Annotation value: " + annotation.value());
}
19. What is the Adapter Design Pattern, and how is it used in Java?
Ans: The Adapter Design Pattern is a structural design pattern that allows incompatible interfaces to work together. It involves creating
an adapter class that acts as a bridge between the two interfaces.
18. What is the Singleton Design Pattern, and how is it implemented in Java?
Ans:TheSingleton Design Patternis a design pattern in Javathat ensures that aclasshas only one instance and provides a global point of
access to that instance.It is typically implemented using a private static instance and a public static method to retrieve it.
Try it Yourself >>
Read More: Static Keyword in Java
Output
Example Code:
true
This is a custom annotation.
public class Singleton {
private static Singleton instance;
private Singleton() { }
public static Singleton getInstance() {
}
if (instance == null) {
instance = new Singleton();
}
r e t u r n i n s t a n c e ;
}
public class SingletonPatternExample {
public static void main(String[] args) {
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
System.out.println(singleton1 == singleton2); // Should print true
}
}
Output
Example Code:
Try it Yourself >>
Explore More:
Mediator Pattern
Model-View-Controller (MVC) Pattern
Playing MP4 file: song.mp4
interface MediaPlayer {
}
void play(String fileName);
interface MediaAdapter {
}
void play(String fileName);
class MediaAdapterClass implements MediaAdapter {
private MediaPlayer player;
public MediaAdapterClass(MediaPlayer player) {
this.player = player;
}
public void play(String fileName) {
}
player.play(fileName);
}
class MP4Player implements MediaPlayer {
}
public void play(String fileName) {
System.out.println("Playing MP4 file: " + fileName);
}
public class AdapterPatternExample {
}
public static void main(String[] args) {
MediaPlayer mp4Player = new MP4Player();
MediaAdapter adapter = new MediaAdapterClass(mp4Player);
adapter.play("song.mp4");
}
State Pattern
Command Pattern
Ans: The Template Method Design Pattern defines the skeleton of an algorithm in a base class but lets subclasses override specific
steps of the algorithm without changing its structure. This pattern is useful for code reuse and promoting consistent logic across
related classes.
20. What is the Template Method Design Pattern, and how is it implemented in Java?
Example Code:
protected abstract void step1();
protected abstract void step2();
abstract class Template {
public final void templateMethod() {
step1();
step2();
step3();
}
public class TemplateMethodPatternExample {
public static void main(String[] args) {
Template templateA = new ConcreteClassA();
}
protected void step3() {
System.out.println("Common step 3 executed.");
}
class ConcreteClassA extends Template {
protected void step1() {
System.out.println("Step 1 in ConcreteClassA.");
}
}
protected void step2() {
System.out.println("Step 2 in ConcreteClassA.");
}
class ConcreteClassB extends Template {
protected void step1() {
System.out.println("Step 1 in ConcreteClassB.");
}
}
protected void step2() {
System.out.println("Step 2 in ConcreteClassB.");
}
Output
Example Code:
21. What is the Proxy Design Pattern, and how is it implemented in Java?
Ans: The Proxy Design Pattern provides a surrogate or placeholder object to control access to another object. It can be used for lazy
initialization, access control, or logging. The pattern involves creating a proxy class that implements the same interface as the real
object, and delegates calls to it.
Try it Yourself >>
interface RealSubject {
}
void request();
Step 1 in ConcreteClassA.
Step 2 in ConcreteClassA.
Common step 3 executed.
Step 1 in ConcreteClassB.
Step 2 in ConcreteClassB.
Common step 3 executed.
public class ProxyPatternExample {
templateA.templateMethod();
class Proxy implements RealSubject {
private RealSubjectImpl realSubject;
}
public void request() {
if (realSubject == null) {
realSubject = new RealSubjectImpl();
}
r e a l S u b j e c t . r e q u e s t ( ) ;
}
}
Template templateB = new ConcreteClassB();
templateB.templateMethod();
}
class RealSubjectImpl implements RealSubject {
}
public void request() {
System.out.println("Request made to real subject.");
}
Output
Example Code:
22. What is the Strategy Design Pattern, and how is it implemented in Java?
Ans: The Strategy Design Pattern allows a class to change its behavior at runtime by changing the algorithm it uses. It involves defining a
family of algorithms and encapsulating each one in a separate class, making them interchangeable.
Try it Yourself >>
interface Strategy {
}
void execute();
Request made to real subject.
class Context {
private Strategy strategy;
public void executeStrategy() {
strategy.execute();
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
class ConcreteStrategyA implements Strategy {
}
public void execute() {
System.out.println("Executing strategy A.");
}
class ConcreteStrategyB implements Strategy {
}
public void execute() {
System.out.println("Executing strategy B.");
}
}
public static void main(String[] args) {
RealSubject proxy = new Proxy();
proxy.request(); // Real subject is instantiated and request is made
}
Output
Example Code:
23. What is the Observer Design Pattern, and how is it implemented in Java?
Ans: The Observer Design Pattern defines a one-to-many dependency between objects so that when one object changes state, all its
dependent objects are notified. This pattern is widely used in implementing event-handling systems.
Try it Yourself >>
}
}
Executing strategy A.
Executing strategy B.
import java.util.ArrayList;
import java.util.List;
interface Observer {
}
void update(String message);
public ConcreteObserver(String name) {
this.name = name;
}
class ConcreteObserver implements Observer {
private String name;
interface Subject {
void registerObserver(Observer observer);
void removeObserver(Observer observer);
public class StrategyPatternExample {
}
public static void main(String[] args) {
Context context = new Context(new ConcreteStrategyA());
context.executeStrategy(); // Executes strategy A
context.setStrategy(new ConcreteStrategyB());
context.executeStrategy(); // Executes strategy B
}
}
public void update(String message) {
System.out.println(name + " received message: " + message);
}
Output
24. What is the Factory Method Design Pattern, and how is it implemented in Java?
}
void notifyObservers();
subject.registerObserver(observer1);
subject.registerObserver(observer2);
}
public void setMessage(String message) {
this.message = message;
notifyObservers();
}
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(message);
}
}
Observer 1 received message: State has changed.
Observer 2 received message: State has changed.
}
subject.setMessage("State has changed.");
}
public void removeObserver(Observer observer) {
observers.remove(observer);
}
public void registerObserver(Observer observer) {
observers.add(observer);
}
public class ObserverPatternExample {
public static void main(String[] args) {
ConcreteSubject subject = new ConcreteSubject(); Observer
observer1 = new ConcreteObserver("Observer 1");
Observer observer2 = new ConcreteObserver("Observer 2");
class ConcreteSubject implements Subject {
private List observers = new ArrayList<>(); // Use generic type List
private String message;
Try it Yourself >>
Ans: The Factory Method Design Pattern defines an interface for creating objects but allows subclasses to alter the type of objects that
will be created. It promotes loose coupling by eliminating the need to bind application-specific classes into the code.
Example Code:
abstract class Product {
}
public abstract void doSomething();
class ConcreteCreatorA extends Creator {
}
public Product factoryMethod() {
return new ConcreteProductA();
}
class ConcreteCreatorB extends Creator {
}
public Product factoryMethod() {
return new ConcreteProductB();
}
abstract class Creator {
}
public abstract Product factoryMethod();
public class FactoryMethodPatternExample {
public static void main(String[] args) {
Creator creatorA = new ConcreteCreatorA();
Product productA = creatorA.factoryMethod();
productA.doSomething();
}
Creator creatorB = new ConcreteCreatorB();
Product productB = creatorB.factoryMethod();
productB.doSomething();
}
class ConcreteProductA extends Product {
}
public void doSomething() {
System.out.println("Doing something in ConcreteProductA.");
}
class ConcreteProductB extends Product {
}
public void doSomething() {
System.out.println("Doing something in ConcreteProductB.");
}
Output
Example Code:
Try it Yourself >>
Read More: Factory Method Design Pattern
Ans: The Chain of Responsibility Design Pattern allows a request to be passed along a chain of handlers, where each handler processes
the request or passes it to the next handler in the chain. This pattern is useful when more than one object can handle a request, and the
handler is determined dynamically.
25. What is the Chain of Responsibility Design Pattern, and how is it implemented in Java?
abstract class Handler {
protected Handler nextHandler;
Doing something in ConcreteProductA.
Doing something in ConcreteProductB.
}
public abstract void handleRequest(int request);
public void setNextHandler(Handler nextHandler) {
this.nextHandler = nextHandler;
}
class ConcreteHandlerA extends Handler {
}
public void handleRequest(int request) {
if (request == 1) {
System.out.println("Handler A handled the request.");
} else if (nextHandler != null) {
nextHandler.handleRequest(request);
}
}
class ConcreteHandlerB extends Handler {
}
public void handleRequest(int request) {
if (request == 2) {
System.out.println("Handler B handled the request.");
} else if (nextHandler != null) {
nextHandler.handleRequest(request);
}
}
Output
Example Code:
26. What is the Decorator Design Pattern, and how is it implemented in Java?
Ans: The Decorator Design Pattern allows you to dynamically add behavior to an object at runtime without affecting the behavior of other
objects from the same class. It involves creating decorator classes that implement the same interface and delegate calls to the wrapped
object.
Try it Yourself >>
interface Coffee {
double cost();
}
Handler B handled the request.
}
public double cost() {
return decoratedCoffee.cost();
}
class SimpleCoffee implements Coffee {
}
public double cost() {
return 5.0;
}
class MilkDecorator extends CoffeeDecorator {
abstract class CoffeeDecorator implements Coffee {
protected Coffee decoratedCoffee;
public class ChainOfResponsibilityPatternExample {
public static void main(String[] args) {
Handler handlerA = new ConcreteHandlerA();
Handler handlerB = new ConcreteHandlerB();
handlerA.setNextHandler(handlerB);
public CoffeeDecorator(Coffee decoratedCoffee) {
this.decoratedCoffee = decoratedCoffee;
}
}
handlerA.handleRequest(2); // Handler B will handle the request
}
Output
Example Code:
27. What is the State Design Pattern, and how is it implemented in Java?
Ans: The State Design Pattern allows an object to change its behavior when its internal state changes. The pattern is typically used to
model objects whose behavior depends on their state and to avoid complex conditionals.
Try it Yourself >>
interface State {
void handle();
}
Cost of Simple Coffee: 5.0
Cost of Coffee with Milk: 6.0
}
public double cost() {
return decoratedCoffee.cost() + 1.0;
}
class ConcreteStateA implements State {
}
public void handle() {
System.out.println("Handling state A");
}
class ConcreteStateB implements State {
}
public void handle() {
System.out.println("Handling state B");
}
public MilkDecorator(Coffee decoratedCoffee) {
super(decoratedCoffee);
}
public class DecoratorPatternExample {
public static void main(String[] args) {
Coffee coffee = new SimpleCoffee();
System.out.println("Cost of Simple Coffee: " + coffee.cost());
}
coffee = new MilkDecorator(coffee);
System.out.println("Cost of Coffee with Milk: " + coffee.cost());
}
Output
Example Code:
28. What is the Flyweight Design Pattern, and how is it implemented in Java?
Ans: The Flyweight Design Pattern is a structural pattern that allows the sharing of objects to support large numbers of fine-grained
objects efficiently. It reduces memory usage by sharing common parts of the state between multiple objects.
Try it Yourself >>
Handling state A
Handling state B
interface Flyweight {
}
void display();
class Context {
private State state;
import java.util.HashMap;
import java.util.Map;
}
public void request() {
state.handle();
}
public void setState(State state) {
this.state = state;
}
public class StatePatternExample {
public static void main(String[] args) {
Context context = new Context();
class ConcreteFlyweight implements Flyweight {
private String intrinsicState;
context.setState(new ConcreteStateA());
context.request(); // Handling state A
}
context.setState(new ConcreteStateB());
context.request(); // Handling state B
}
Output
Example Code:
29. What is the Memento Design Pattern, and how is it implemented in Java?
Ans: The Memento Design Pattern captures and externalizes an object's internal state so that the object can be restored to this state later
without violating encapsulation. It involves three components: Originator, Memento, and Caretaker.
Try it Yourself >>
class Memento {
Flyweight with state: State1
Flyweight with state: State1
}
flyweight1.display();
flyweight2.display();
}
public ConcreteFlyweight(String state) {
this.intrinsicState = state;
}
public class FlyweightPatternExample {
public static void main(String[] args) {
FlyweightFactory factory = new FlyweightFactory();
Flyweight flyweight1 = factory.getFlyweight("State1");
Flyweight flyweight2 = factory.getFlyweight("State1");
}
public Flyweight getFlyweight(String state) {
if (!flyweights.containsKey(state)) {
flyweights.put(state, new ConcreteFlyweight(state));
}
r e t u r n f l y w e i g h t s . g e t ( s t a t e ) ;
}
}
public void display() {
System.out.println("Flyweight with state: " + intrinsicState);
}
class FlyweightFactory {
private Map flyweights = new HashMap<>(); // Use generics for type safety
private String state;
class Originator {
private String state;
class Caretaker {
private Memento memento;
}
public String getState() {
return state;
}
public String getState() {
return state;
}
public Memento(String state) {
this.state = state;
}
}
public Memento retrieveState() {
return memento;
}
public void setState(String state) {
this.state = state;
}
public Memento saveStateToMemento() {
return new Memento(state);
}
public void saveState(Memento memento) {
this.memento = memento;
}
public class MementoPatternExample {
public static void main(String[] args) {
Originator originator = new Originator();
Caretaker caretaker = new Caretaker();
}
public void getStateFromMemento(Memento memento) {
state = memento.getState();
}
originator.setState("State1");
caretaker.saveState(originator.saveStateToMemento());
originator.setState("State2");
System.out.println("Current State: " + originator.getState());
Output
Example Code:
30. What is the Composite Design Pattern, and how is it implemented in Java?
Ans: The Composite Design Pattern is a structural pattern that allows you to compose objects into tree-like structures to represent part-
whole hierarchies. It will enable clients to treat individual objects and compositions of objects uniformly.
Try it Yourself >>
interface Component {
void operation();
}
Current State: State2
Restored State: State1
import java.util.ArrayList;
import java.util.List;
public class CompositePatternExample {
public void add(Component component) {
children.add(component);
}
}
public void operation() {
for (Component component : children) {
component.operation();
}
}
class Leaf implements Component {
}
public void operation() {
System.out.println("Leaf operation.");
}
}
originator.getStateFromMemento(caretaker.retrieveState());
System.out.println("Restored State: " + originator.getState());
}
class Composite implements Component {
private List<Component> children = new ArrayList<>(); // Specify the generic type for type safety
Output
Summary
This article focused on the key skills of Java developers, covering Java Interview Questions for 10 Years of Experience. It emphasized
mastering advanced Java concepts, multithreading, design patterns, and frameworks like Spring and Hibernate. Additionally, it
highlighted problem-solving, leadership, and communication skills as essential for senior developers.
Try it Yourself >>
(a) To make a variable immutable
(b) To prevent serialization of a variable
(c) To mark a variable as thread-safe
(d) To mark a method as final
View Answer ⬇
(a) ̀`HashMap` allows null keys, while ̀`ConcurrentHashMap` does not
(b) ̀`HashMap` is not thread-safe, while ̀`ConcurrentHashMap` is thread-safe
(c) ̀`ConcurrentHashMap` allows duplicate keys, while ̀`HashMap` does not
(d) ̀`HashMap` has better performance than ̀`ConcurrentHashMap` in multi-threaded environments
View Answer ⬇
Enhance your Java expertise with the Scholarhat Java Programming Course, designed to help you master complex Java concepts for
career advancement.Scholarhat Master Classes offer specialized training in Java, ReactJS, and Python. Join now to advance your
career!
Test Your Advanced Java Knowledge!
Q 1: What is the main difference between `HashMap` and `ConcurrentHashMap` in Java?
Q 2: What is the purpose of the `transient` keyword in Java?
Leaf operation.
Leaf operation.
}
root.operation();
}
public static void main(String[] args) {
Composite root = new Composite();
Composite composite1 = new Composite();
Leaf leaf1 = new Leaf();
Leaf leaf2 = new Leaf();
composite1.add(leaf1);
composite1.add(leaf2);
root.add(composite1);
Q 3: Which method in Java is used to start a thread?
(a) ̀`run()`
(b) ̀`start()`
(c) ̀`execute()`
(d) ̀`launch()`
Q 4: What is the output of the following code snippet?
Q 5: What is the difference between `==` and `equals()` in Java?
(a) ̀ `==` compares object references, while ̀ `equals()` compares object values (b) ̀ `==`
compares object values, while ̀`equals()` compares object references (c) ̀`==` is used for
primitive data types, while ̀`equals()` is used for objects (d) Both are used interchangeably
View Answer
(a) 15
(b) 10
(c) 5 (d)
Error
View Answer
View Answer ⬇
⬇
⬇
public class Test {
public static void main(String[] args) {
int x = 10;
int y = 5;
System.out.println(x + y);
}
}
Ad

More Related Content

Similar to Java Interview Questions for 10+ Year Experienced PDF By ScholarHat (20)

Java 8 Interview Questions and Answers PDF By ScholarHat.pdf
Java 8 Interview Questions and Answers PDF By ScholarHat.pdfJava 8 Interview Questions and Answers PDF By ScholarHat.pdf
Java 8 Interview Questions and Answers PDF By ScholarHat.pdf
Scholarhat
 
Object Oriented Programming unit 1 content for students
Object Oriented Programming unit 1 content for studentsObject Oriented Programming unit 1 content for students
Object Oriented Programming unit 1 content for students
ASHASITTeaching
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
Sujit Majety
 
Towards Improving Interface Modularity in Legacy Java Software Through Automa...
Towards Improving Interface Modularity in Legacy Java Software Through Automa...Towards Improving Interface Modularity in Legacy Java Software Through Automa...
Towards Improving Interface Modularity in Legacy Java Software Through Automa...
New York City College of Technology Computer Systems Technology Colloquium
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Raffi Khatchadourian
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.ppt
rani marri
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
Hamid Ghorbani
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Emiel Paasschens
 
Towards Improving Interface Modularity in Legacy Java Software Through Automa...
Towards Improving Interface Modularity in Legacy Java Software Through Automa...Towards Improving Interface Modularity in Legacy Java Software Through Automa...
Towards Improving Interface Modularity in Legacy Java Software Through Automa...
Raffi Khatchadourian
 
Infosys Interview Questions By ScholarHat
Infosys Interview Questions By ScholarHatInfosys Interview Questions By ScholarHat
Infosys Interview Questions By ScholarHat
Scholarhat
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for Mainframers
Rich Helton
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
Rafael Coutinho
 
Basics of java 1
Basics of java 1Basics of java 1
Basics of java 1
Vijay Kankane
 
Java 8 Overview
Java 8 OverviewJava 8 Overview
Java 8 Overview
Nicola Pedot
 
01slide
01slide01slide
01slide
Usha Sri
 
01slide
01slide01slide
01slide
cdclabs_123
 
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Ayes Chinmay
 
JavaBasicsCore1.ppt
JavaBasicsCore1.pptJavaBasicsCore1.ppt
JavaBasicsCore1.ppt
buvanabala
 
Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
Jyothsna Sree
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
Satya Johnny
 
Java 8 Interview Questions and Answers PDF By ScholarHat.pdf
Java 8 Interview Questions and Answers PDF By ScholarHat.pdfJava 8 Interview Questions and Answers PDF By ScholarHat.pdf
Java 8 Interview Questions and Answers PDF By ScholarHat.pdf
Scholarhat
 
Object Oriented Programming unit 1 content for students
Object Oriented Programming unit 1 content for studentsObject Oriented Programming unit 1 content for students
Object Oriented Programming unit 1 content for students
ASHASITTeaching
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
Sujit Majety
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Raffi Khatchadourian
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.ppt
rani marri
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
Hamid Ghorbani
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Emiel Paasschens
 
Towards Improving Interface Modularity in Legacy Java Software Through Automa...
Towards Improving Interface Modularity in Legacy Java Software Through Automa...Towards Improving Interface Modularity in Legacy Java Software Through Automa...
Towards Improving Interface Modularity in Legacy Java Software Through Automa...
Raffi Khatchadourian
 
Infosys Interview Questions By ScholarHat
Infosys Interview Questions By ScholarHatInfosys Interview Questions By ScholarHat
Infosys Interview Questions By ScholarHat
Scholarhat
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for Mainframers
Rich Helton
 
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Ayes Chinmay
 
JavaBasicsCore1.ppt
JavaBasicsCore1.pptJavaBasicsCore1.ppt
JavaBasicsCore1.ppt
buvanabala
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
Satya Johnny
 

More from Scholarhat (20)

React Redux Interview Questions PDF By ScholarHat
React Redux Interview Questions PDF By ScholarHatReact Redux Interview Questions PDF By ScholarHat
React Redux Interview Questions PDF By ScholarHat
Scholarhat
 
React Redux Interview Questions PDF By ScholarHat
React Redux Interview Questions PDF By ScholarHatReact Redux Interview Questions PDF By ScholarHat
React Redux Interview Questions PDF By ScholarHat
Scholarhat
 
React Router Interview Questions PDF By ScholarHat
React Router Interview Questions PDF By ScholarHatReact Router Interview Questions PDF By ScholarHat
React Router Interview Questions PDF By ScholarHat
Scholarhat
 
JavaScript Array Interview Questions PDF By ScholarHat
JavaScript Array Interview Questions PDF By ScholarHatJavaScript Array Interview Questions PDF By ScholarHat
JavaScript Array Interview Questions PDF By ScholarHat
Scholarhat
 
Infosys Angular Interview Questions PDF By ScholarHat
Infosys Angular Interview Questions PDF By ScholarHatInfosys Angular Interview Questions PDF By ScholarHat
Infosys Angular Interview Questions PDF By ScholarHat
Scholarhat
 
DBMS Interview Questions PDF By ScholarHat
DBMS Interview Questions PDF By ScholarHatDBMS Interview Questions PDF By ScholarHat
DBMS Interview Questions PDF By ScholarHat
Scholarhat
 
API Testing Interview Questions PDF By ScholarHat
API Testing Interview Questions PDF By ScholarHatAPI Testing Interview Questions PDF By ScholarHat
API Testing Interview Questions PDF By ScholarHat
Scholarhat
 
System Design Interview Questions PDF By ScholarHat
System Design Interview Questions PDF By ScholarHatSystem Design Interview Questions PDF By ScholarHat
System Design Interview Questions PDF By ScholarHat
Scholarhat
 
Python Viva Interview Questions PDF By ScholarHat
Python Viva Interview Questions PDF By ScholarHatPython Viva Interview Questions PDF By ScholarHat
Python Viva Interview Questions PDF By ScholarHat
Scholarhat
 
Linux Interview Questions PDF By ScholarHat
Linux Interview Questions PDF By ScholarHatLinux Interview Questions PDF By ScholarHat
Linux Interview Questions PDF By ScholarHat
Scholarhat
 
Kubernetes Interview Questions PDF By ScholarHat
Kubernetes Interview Questions PDF By ScholarHatKubernetes Interview Questions PDF By ScholarHat
Kubernetes Interview Questions PDF By ScholarHat
Scholarhat
 
Collections in Java Interview Questions PDF By ScholarHat
Collections in Java Interview Questions PDF By ScholarHatCollections in Java Interview Questions PDF By ScholarHat
Collections in Java Interview Questions PDF By ScholarHat
Scholarhat
 
CI CD Pipeline Interview Questions PDF By ScholarHat
CI CD Pipeline Interview Questions PDF By ScholarHatCI CD Pipeline Interview Questions PDF By ScholarHat
CI CD Pipeline Interview Questions PDF By ScholarHat
Scholarhat
 
Azure DevOps Interview Questions PDF By ScholarHat
Azure DevOps Interview Questions PDF By ScholarHatAzure DevOps Interview Questions PDF By ScholarHat
Azure DevOps Interview Questions PDF By ScholarHat
Scholarhat
 
TypeScript Interview Questions PDF By ScholarHat
TypeScript Interview Questions PDF By ScholarHatTypeScript Interview Questions PDF By ScholarHat
TypeScript Interview Questions PDF By ScholarHat
Scholarhat
 
UIUX Interview Questions PDF By ScholarHat
UIUX Interview Questions PDF By ScholarHatUIUX Interview Questions PDF By ScholarHat
UIUX Interview Questions PDF By ScholarHat
Scholarhat
 
Python Interview Questions PDF By ScholarHat
Python Interview Questions PDF By ScholarHatPython Interview Questions PDF By ScholarHat
Python Interview Questions PDF By ScholarHat
Scholarhat
 
OOPS JavaScript Interview Questions PDF By ScholarHat
OOPS JavaScript Interview Questions PDF By ScholarHatOOPS JavaScript Interview Questions PDF By ScholarHat
OOPS JavaScript Interview Questions PDF By ScholarHat
Scholarhat
 
Git Interview Questions PDF By ScholarHat
Git Interview Questions PDF By ScholarHatGit Interview Questions PDF By ScholarHat
Git Interview Questions PDF By ScholarHat
Scholarhat
 
Cloud Computing Interview Questions PDF By ScholarHat
Cloud Computing Interview Questions PDF By ScholarHatCloud Computing Interview Questions PDF By ScholarHat
Cloud Computing Interview Questions PDF By ScholarHat
Scholarhat
 
React Redux Interview Questions PDF By ScholarHat
React Redux Interview Questions PDF By ScholarHatReact Redux Interview Questions PDF By ScholarHat
React Redux Interview Questions PDF By ScholarHat
Scholarhat
 
React Redux Interview Questions PDF By ScholarHat
React Redux Interview Questions PDF By ScholarHatReact Redux Interview Questions PDF By ScholarHat
React Redux Interview Questions PDF By ScholarHat
Scholarhat
 
React Router Interview Questions PDF By ScholarHat
React Router Interview Questions PDF By ScholarHatReact Router Interview Questions PDF By ScholarHat
React Router Interview Questions PDF By ScholarHat
Scholarhat
 
JavaScript Array Interview Questions PDF By ScholarHat
JavaScript Array Interview Questions PDF By ScholarHatJavaScript Array Interview Questions PDF By ScholarHat
JavaScript Array Interview Questions PDF By ScholarHat
Scholarhat
 
Infosys Angular Interview Questions PDF By ScholarHat
Infosys Angular Interview Questions PDF By ScholarHatInfosys Angular Interview Questions PDF By ScholarHat
Infosys Angular Interview Questions PDF By ScholarHat
Scholarhat
 
DBMS Interview Questions PDF By ScholarHat
DBMS Interview Questions PDF By ScholarHatDBMS Interview Questions PDF By ScholarHat
DBMS Interview Questions PDF By ScholarHat
Scholarhat
 
API Testing Interview Questions PDF By ScholarHat
API Testing Interview Questions PDF By ScholarHatAPI Testing Interview Questions PDF By ScholarHat
API Testing Interview Questions PDF By ScholarHat
Scholarhat
 
System Design Interview Questions PDF By ScholarHat
System Design Interview Questions PDF By ScholarHatSystem Design Interview Questions PDF By ScholarHat
System Design Interview Questions PDF By ScholarHat
Scholarhat
 
Python Viva Interview Questions PDF By ScholarHat
Python Viva Interview Questions PDF By ScholarHatPython Viva Interview Questions PDF By ScholarHat
Python Viva Interview Questions PDF By ScholarHat
Scholarhat
 
Linux Interview Questions PDF By ScholarHat
Linux Interview Questions PDF By ScholarHatLinux Interview Questions PDF By ScholarHat
Linux Interview Questions PDF By ScholarHat
Scholarhat
 
Kubernetes Interview Questions PDF By ScholarHat
Kubernetes Interview Questions PDF By ScholarHatKubernetes Interview Questions PDF By ScholarHat
Kubernetes Interview Questions PDF By ScholarHat
Scholarhat
 
Collections in Java Interview Questions PDF By ScholarHat
Collections in Java Interview Questions PDF By ScholarHatCollections in Java Interview Questions PDF By ScholarHat
Collections in Java Interview Questions PDF By ScholarHat
Scholarhat
 
CI CD Pipeline Interview Questions PDF By ScholarHat
CI CD Pipeline Interview Questions PDF By ScholarHatCI CD Pipeline Interview Questions PDF By ScholarHat
CI CD Pipeline Interview Questions PDF By ScholarHat
Scholarhat
 
Azure DevOps Interview Questions PDF By ScholarHat
Azure DevOps Interview Questions PDF By ScholarHatAzure DevOps Interview Questions PDF By ScholarHat
Azure DevOps Interview Questions PDF By ScholarHat
Scholarhat
 
TypeScript Interview Questions PDF By ScholarHat
TypeScript Interview Questions PDF By ScholarHatTypeScript Interview Questions PDF By ScholarHat
TypeScript Interview Questions PDF By ScholarHat
Scholarhat
 
UIUX Interview Questions PDF By ScholarHat
UIUX Interview Questions PDF By ScholarHatUIUX Interview Questions PDF By ScholarHat
UIUX Interview Questions PDF By ScholarHat
Scholarhat
 
Python Interview Questions PDF By ScholarHat
Python Interview Questions PDF By ScholarHatPython Interview Questions PDF By ScholarHat
Python Interview Questions PDF By ScholarHat
Scholarhat
 
OOPS JavaScript Interview Questions PDF By ScholarHat
OOPS JavaScript Interview Questions PDF By ScholarHatOOPS JavaScript Interview Questions PDF By ScholarHat
OOPS JavaScript Interview Questions PDF By ScholarHat
Scholarhat
 
Git Interview Questions PDF By ScholarHat
Git Interview Questions PDF By ScholarHatGit Interview Questions PDF By ScholarHat
Git Interview Questions PDF By ScholarHat
Scholarhat
 
Cloud Computing Interview Questions PDF By ScholarHat
Cloud Computing Interview Questions PDF By ScholarHatCloud Computing Interview Questions PDF By ScholarHat
Cloud Computing Interview Questions PDF By ScholarHat
Scholarhat
 
Ad

Recently uploaded (20)

YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
Ad

Java Interview Questions for 10+ Year Experienced PDF By ScholarHat

  • 1. Top Java Interview Questions for 10+ Year Experienced Professionals Java Interview Questions for 10 Years Experience To excel in a Java interview with 10 years of experience, it’s crucial to have a deep understanding of advanced Java concepts, multithreading, design patterns, and frameworks such as Spring and Hibernate. Your ability to tackle complex technical problems, implement efficient solutions, and mentor junior developers will set you apart. What can you expect in a Java interview for 10 years of experience? The Java interview process for candidates with 10 years of experience is highly advanced, evaluating your deep expertise in Java development, software architecture, and leadership skills. Here's what you can expect: In-depth questions on core Java concepts, advanced OOP concepts, Multithreading, and memory management in Java. Complex scenario-based tasks to assess your ability to write highly scalable, performant, and maintainable code. Questions on Design patterns, focusing on Singleton, Factory, Observer, Strategy, and Decorator patterns. Experience with Collection Framework, Spring, Hibernate, Spring Boot, and other enterprise-level frameworks. Advanced knowledge of unit testing with frameworks like JUnit and Mockito, along with test-driven development (TDD) principles. Expert understanding of Java performance tuning, including JVM internals, garbage collection, and heap management. Hands-on experience with cloud services (AWS, Azure), REST and SOAP APIs, and integration with databases using JPA and Hibernate. Knowledge of CI/CD pipelines, containerization with Docker, and orchestration tools like Kubernetes. Leadership experience, including mentoring junior developers, conducting code reviews, and designing enterprise architectures that align with business requirements. In this Java tutorial, we’ll focus on Java Interview Questions for 10 Years of Experience, dive deep into high-level topics, and offer guidance on what interviewers expect from senior candidates. With the right preparation, you’ll be ready to showcase your expertise and lead teams effectively.
  • 2. Top 30 Java Interview Questions for 10 Years of Experience 1. How does the Java Memory Model (JMM) ensure visibility and ordering in multithreaded programs? Ans: The Java Memory Model (JMM) defines how threads interact through memory and ensures visibility and order of operations in a multithreaded environment. Key principles include: Volatile variables: Ensure visibility of updates across threads by preventing caching. Happens-before relationship: Guarantees that one action’s effects are visible to another. Synchronization: Enforces ordering and visibility via synchronized blocks or methods. Example Code: public class Main { private volatile boolean flag = false; public static void main(String[] args) { Main example = new Main(); public void reader() { // Small delay to let the writer thread run first try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } // Create and start writer thread Thread writerThread = new Thread(new Runnable() { @Override public void writer() { flag = true; // Visible to all threads System.out.println("Writer thread has set flag to true."); } if (flag) { System.out.println("Reader thread sees flag as true."); } else { System.out.println("Reader thread sees flag as false."); } }
  • 3. Output Example Code: 2. What is the difference between deep copy and shallow copy in Java? Ans: In Java, a shallow copy creates a new object, but the fields are still references to the same objects as the original. In contrast, a deep copy creates a completely independent copy of the original object, including the objects referenced by its fields. A deep copy is more resource-intensive but ensures complete independence between the original and copied objects. Try it Yourself >> import java.util.ArrayList; import java.util.List; public void run() { example.writer(); } }); writerThread.start(); Writer thread has set flag to true. Reader thread sees flag as true. } // Create and start reader thread Thread readerThread = new Thread(new Runnable() { @Override public void run() { example.reader(); } }); readerThread.start(); } // Shallow copy (reference copy) List shallowCopy = originalList; // Deep copy (creating a new ArrayList) List deepCopy = new ArrayList<>(originalList); originalList.add("C++"); System.out.println("Original List: " + originalList); public class Main { public static void main(String[] args) { // Correcting the raw type usage by specifying the generic type List originalList = new ArrayList<>(); originalList.add("Java");
  • 4. Output Output Example Code: 3. What is the difference between HashMap and TreeMap in Java? Ans: The main difference between HashMap and TreeMap is their ordering of keys: Try it Yourself >> Try it Yourself >> HashMap: Does not maintain any order of the keys. It is faster and allows null keys and values. TreeMap: Maintains the keys in sorted order based on their natural ordering or a custom comparator. import java.util.*; Original List: [Java, C++] Shallow Copy: [Java, C++] Deep Copy: [Java] HashMap: {Java=100, C++=90} TreeMap: {C++=90, Java=100} Map treeMap = new TreeMap<>(); treeMap.put("Java", 100); treeMap.put("C++", 90); public class Main { public static void main(String[] args) { Map hashMap = new HashMap<>(); hashMap.put("Java", 100); hashMap.put("C++", 90); } System.out.println("HashMap: " + hashMap); System.out.println("TreeMap: " + treeMap); } System.out.println("Shallow Copy: " + shallowCopy); System.out.println("Deep Copy: " + deepCopy); } }
  • 5. Try it Yourself >> Try it Yourself >> Read More: HashMap in Java Ans: Java’s garbage collection (GC) automatically reclaims memory by identifying and clearing objects that are no longer reachable from active threads. It helps prevent memory leaks and ensures efficient memory management by using techniques like mark-and-sweep and reference counting. Ans: Lambda expressions in Java, introduced in Java 8, allow you to write instances of functional interfaces in a concise and expressive way. They provide a more functional style of programming and are mainly used to implement methods of functional interfaces. The syntax is: (parameters) -> expression. 5. How does Java’s Garbage Collection work? 4. Explain the concept of Lambda Expressions in Java. Output Example Code: Example Code: Java C++ Python import java.util.*; } System.gc(); // Hint for garbage collection } public class LambdaExample { public static void main(String[] args) { List names = Arrays.asList("Java", "C++", "Python"); // Lambda expression names.forEach(name -> System.out.println(name)); } } public class GarbageCollectionExample { public static void main(String[] args) { GarbageCollectionExample example = new GarbageCollectionExample(); example = null; // Eligible for garbage collection
  • 6. Output Output Example Code: Example Code: Try it Yourself >> Read More: .NET Garbage Collection In-Depth Ans: In Java: String: Immutable, meaning its value cannot be changed once created. StringBuilder: Mutable and not synchronized, suitable for single-threaded applications. StringBuffer: Mutable and synchronized, suitable for multithreaded environments. Ans: Functional interfaces are interfaces that contain exactly one abstract method. They are used primarily with lambda expressions and method references to provide a more compact and readable code. Common examples are Runnable, Callable, and Comparator. 6. What are functional interfaces and how are they used in Java? 7. What are the differences between String, StringBuilder, and StringBuffer in Java? Functional Interface method. @FunctionalInterface interface MyFunctionalInterface { } void myMethod(); public class StringExample { public static void main(String[] args) { String str1 = "Hello"; StringBuilder sb = new StringBuilder("World"); sb.append("!"); System.out.println(str1); [Output may vary] A message indicating that garbage collection is triggered might be printed. public class FunctionalInterfaceExample { } public static void main(String[] args) { MyFunctionalInterface myInterface = () -> System.out.println("Functional Interface method."); myInterface.myMethod(); }
  • 7. Output Output Example Code: 8. What isa reflectionin Java, and how is it used? Ans: Reflection in Java is the ability of a program to examine and modify the structure and behavior of classes, methods, fields, etc. It is mainly used for: 9. What is the use of default methods in Java interfaces? Ans: Default methods allow you to add method implementations in interfaces without breaking the implementing classes. This feature, introduced in Java 8, helps maintain backward compatibility with older versions of interfaces. Try it Yourself >> Try it Yourself >> Accessing private members of a class. Invoking methods dynamically. Creating new objects at runtime. Hello World! String length: 5 } System.out.println(sb); } import java.lang.reflect.Method; public class Main { public static void main(String[] args) throws Exception { Class cls = Class.forName("java.lang.String"); Method method = cls.getMethod("length"); String str = "Hello"; int length = (int) method.invoke(str); // invoking the 'length' method on the string object System.out.println("String length: " + length); } }
  • 8. Output Example Code: Example Code: 10. Explain the concept of Java Streams and provide an example. Ans: Java Streams provide a functional approach to processing sequences of elements, such as collections, in a declarative way. Streams can be processed in parallel, improving performance in large datasets. Key operations are map, filter, reduce, and collect. Try it Yourself >> import java.util.Arrays; import java.util.List; This is a default method. public class Main implements MyInterface { } public static void main(String[] args) { new Main().printMessage(); } public class StreamExample { public static void main(String[] args) { List numbers = Arrays.asList(1, 2, 3, 4, 5); interface MyInterface { } default void printMessage() { System.out.println("This is a default method."); } // Correct way to sum using streams int sum = numbers.stream().mapToInt(Integer::intValue).sum(); System.out.println("Sum: " + sum); }
  • 9. Output Output Example Code: Example Code: 11. What is the difference between Concurrency and Parallelism in Java? Ans: In Java: 12. What are the functional interfaces in Java, and how do they work with lambda expressions? Ans: A functional interface is an interface that has exactly one abstract method, which can be implemented using lambda expressions. Common examples include Runnable, Callable, and Comparator. Try it Yourself >> Try it Yourself >> Concurrency: Refers to the ability of a system to manage multiple tasks at the same time but not necessarily execute them simultaneously. Tasks might be executed on a single thread or distributed across multiple threads. Parallelism: Refers to the simultaneous execution of tasks, typically using multiple processors or cores. It is a subset of concurrency focused on performing multiple operations at the same time. } Sum: 15 Concurrency: Task 1 Concurrency: Task 2 Parallelism: Task 1 Parallelism: Task 2 public class ConcurrencyVsParallelism { public static void main(String[] args) { // Simulating concurrency using a single thread System.out.println("Concurrency: Task 1"); System.out.println("Concurrency: Task 2"); } // Simulating parallelism using two threads Thread task1 = new Thread(() -> System.out.println("Parallelism: Task 1")); Thread task2 = new Thread(() -> System.out.println("Parallelism: Task 2")); task1.start(); task2.start(); }
  • 10. Output Output Example Code: 13. What are the benefits of using Java Streams over traditional looping? Ans: Java Streams provide several benefits over traditional looping mechanisms: Try it Yourself >> Try it Yourself >> Declarative syntax: It allows you to express the logic in a more readable and concise way. Built-in operations: You can filter, map, and reduce data with built-in methods. Parallelism: Streams support parallel processing to improve performance on large datasets. Addition: 8 import java.util.*; @FunctionalInterface interface MathOperation { } int operate(int a, int b); } System.out.println("Sum of even numbers: " + sum); } public class LambdaWithFunctionalInterface { } public static void main(String[] args) { MathOperation addition = (a, b) -> a + b; System.out.println("Addition: " + addition.operate(5, 3)); } public class StreamExample { public static void main(String[] args) { List numbers = Arrays.asList(1, 2, 3, 4, 5); // Use List for type safety // Using Stream to sum even numbers int sum = numbers.stream() .filter(n -> n % 2 == 0) .mapToInt(Integer::intValue) .sum(); // Filter even numbers // Convert Integer to int // Sum the integers
  • 11. 14. What is the role of Java's final keyword? Ans: The final keyword in Java has different roles depending on where it is applied: 15. How does Java's Fork/Join Framework improve parallel computing, and how is it implemented? Ans: The Fork/Join Framework in Java is used to achieve parallelism by dividing tasks into smaller subtasks (forking) and then combining their results (joining). It is part of the java.util.concurrent package and is especially useful for divide-and-conquer algorithms. Try it Yourself >> Final variables: Once initialized, their value cannot be changed. Final methods: The method cannot be overridden by subclasses. Final classes: The class cannot be subclassed. Output Example Code: Example Code: Value: 10 Sum of even numbers: 6 final class FinalClass { final int value = 10; import java.util.concurrent.RecursiveTask; import java.util.concurrent.ForkJoinPool; public class FinalExample { } public static void main(String[] args) { FinalClass obj = new FinalClass(); obj.showValue(); } } final void showValue() { System.out.println("Value: " + value); } class SumTask extends RecursiveTask { // Specify Integer as the type of result private static final int THRESHOLD = 10; private int[] numbers; private int start;
  • 12. Output Total Sum: 5050 private int end; } return leftResult + rightResult; } } public SumTask(int[] numbers, int start, int end) { this.numbers = numbers; this.start = start; this.end = end; } @Override protected Integer compute() { if (end - start <= THRESHOLD) { int sum = 0; for (int i = start; i < end; i++) { sum += numbers[i]; } return sum; } else { int mid = (start + end) / 2; SumTask leftTask = new SumTask(numbers, start, mid); SumTask rightTask = new SumTask(numbers, mid, end); public class ForkJoinExample { public static void main(String[] args) { int[] numbers = new int[100]; for (int i = 0; i < numbers.length; i++) { numbers[i] = i + 1; // Fill the array with numbers 1 to 100 } } int result = pool.invoke(task); // Invoke the task using the pool System.out.println("Total Sum: " + result); // Print the total sum } leftTask.fork(); // Start the left task asynchronously int rightResult = rightTask.compute(); // Compute the right task directly int leftResult = leftTask.join(); // Wait for the left task to complete ForkJoinPool pool = new ForkJoinPool(); // Create a ForkJoinPool to manage tasks SumTask task = new SumTask(numbers, 0, numbers.length); // Create the sum task Try it Yourself >>
  • 13. 16. Explain the Java Serialization process and how to implement it. Ans: Serialization in Java is the process of converting an object into a byte stream to save it to a file or transmit it over a network. The Serializable interface is used to mark a class whose objects can be serialized. Try it Yourself >> Output Example Code: import java.io.*; Object serialized: Alice, 30 Deserialized Person: Alice, 30 class Person implements Serializable { String name; int age; public Person(String name, int age) { } this.name = name; this.age = age; } public class SerializationExample { public static void main(String[] args) { Person person = new Person("Alice", 30); // Serialize the object try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("person.ser"))) { out.writeObject(person); System.out.println("Object serialized: " + person.name + ", " + person.age); } catch (IOException e) { System.out.println("Serialization error: " + e.getMessage()); } // Deserialize the object try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("person.ser"))) { } Person deserializedPerson = (Person) in.readObject(); System.out.println("Deserialized Person: " + deserializedPerson.name + ", " + deserializedPerson.age); } catch (IOException | ClassNotFoundException e) { System.out.println("Deserialization error: " + e.getMessage()); } }
  • 14. 17. What are Java Annotations, and how are they used? Ans: Java annotations provide metadata about the code. They are used to give information to the compiler or runtime environment and can be used for documentation, code analysis, or generating code. Some common annotations include @Override, @Deprecated, and @SuppressWarnings. Try it Yourself >> Output Example Code: Annotation value: Hello, World! import java.lang.annotation.*; import java.lang.reflect.Method; } // Call the method example.displayMessage(); } // Class to demonstrate annotation usage public class Main { // Define the custom annotation with runtime retention @Retention(RetentionPolicy.RUNTIME) @interface MyCustomAnnotation { } String value(); @MyCustomAnnotation(value = "Hello, World!") public void displayMessage() { System.out.println("This is a custom annotation."); } // The main method to execute the program public static void main(String[] args) throws Exception { // Create an instance of Main (formerly AnnotationExample) Main example = new Main(); // Use reflection to check if the method is annotated Method method = example.getClass().getMethod("displayMessage"); // Check if the method has the MyCustomAnnotation annotation if (method.isAnnotationPresent(MyCustomAnnotation.class)) { MyCustomAnnotation annotation = method.getAnnotation(MyCustomAnnotation.class); System.out.println("Annotation value: " + annotation.value()); }
  • 15. 19. What is the Adapter Design Pattern, and how is it used in Java? Ans: The Adapter Design Pattern is a structural design pattern that allows incompatible interfaces to work together. It involves creating an adapter class that acts as a bridge between the two interfaces. 18. What is the Singleton Design Pattern, and how is it implemented in Java? Ans:TheSingleton Design Patternis a design pattern in Javathat ensures that aclasshas only one instance and provides a global point of access to that instance.It is typically implemented using a private static instance and a public static method to retrieve it. Try it Yourself >> Read More: Static Keyword in Java Output Example Code: true This is a custom annotation. public class Singleton { private static Singleton instance; private Singleton() { } public static Singleton getInstance() { } if (instance == null) { instance = new Singleton(); } r e t u r n i n s t a n c e ; } public class SingletonPatternExample { public static void main(String[] args) { Singleton singleton1 = Singleton.getInstance(); Singleton singleton2 = Singleton.getInstance(); System.out.println(singleton1 == singleton2); // Should print true } }
  • 16. Output Example Code: Try it Yourself >> Explore More: Mediator Pattern Model-View-Controller (MVC) Pattern Playing MP4 file: song.mp4 interface MediaPlayer { } void play(String fileName); interface MediaAdapter { } void play(String fileName); class MediaAdapterClass implements MediaAdapter { private MediaPlayer player; public MediaAdapterClass(MediaPlayer player) { this.player = player; } public void play(String fileName) { } player.play(fileName); } class MP4Player implements MediaPlayer { } public void play(String fileName) { System.out.println("Playing MP4 file: " + fileName); } public class AdapterPatternExample { } public static void main(String[] args) { MediaPlayer mp4Player = new MP4Player(); MediaAdapter adapter = new MediaAdapterClass(mp4Player); adapter.play("song.mp4"); }
  • 17. State Pattern Command Pattern Ans: The Template Method Design Pattern defines the skeleton of an algorithm in a base class but lets subclasses override specific steps of the algorithm without changing its structure. This pattern is useful for code reuse and promoting consistent logic across related classes. 20. What is the Template Method Design Pattern, and how is it implemented in Java? Example Code: protected abstract void step1(); protected abstract void step2(); abstract class Template { public final void templateMethod() { step1(); step2(); step3(); } public class TemplateMethodPatternExample { public static void main(String[] args) { Template templateA = new ConcreteClassA(); } protected void step3() { System.out.println("Common step 3 executed."); } class ConcreteClassA extends Template { protected void step1() { System.out.println("Step 1 in ConcreteClassA."); } } protected void step2() { System.out.println("Step 2 in ConcreteClassA."); } class ConcreteClassB extends Template { protected void step1() { System.out.println("Step 1 in ConcreteClassB."); } } protected void step2() { System.out.println("Step 2 in ConcreteClassB."); }
  • 18. Output Example Code: 21. What is the Proxy Design Pattern, and how is it implemented in Java? Ans: The Proxy Design Pattern provides a surrogate or placeholder object to control access to another object. It can be used for lazy initialization, access control, or logging. The pattern involves creating a proxy class that implements the same interface as the real object, and delegates calls to it. Try it Yourself >> interface RealSubject { } void request(); Step 1 in ConcreteClassA. Step 2 in ConcreteClassA. Common step 3 executed. Step 1 in ConcreteClassB. Step 2 in ConcreteClassB. Common step 3 executed. public class ProxyPatternExample { templateA.templateMethod(); class Proxy implements RealSubject { private RealSubjectImpl realSubject; } public void request() { if (realSubject == null) { realSubject = new RealSubjectImpl(); } r e a l S u b j e c t . r e q u e s t ( ) ; } } Template templateB = new ConcreteClassB(); templateB.templateMethod(); } class RealSubjectImpl implements RealSubject { } public void request() { System.out.println("Request made to real subject."); }
  • 19. Output Example Code: 22. What is the Strategy Design Pattern, and how is it implemented in Java? Ans: The Strategy Design Pattern allows a class to change its behavior at runtime by changing the algorithm it uses. It involves defining a family of algorithms and encapsulating each one in a separate class, making them interchangeable. Try it Yourself >> interface Strategy { } void execute(); Request made to real subject. class Context { private Strategy strategy; public void executeStrategy() { strategy.execute(); public Context(Strategy strategy) { this.strategy = strategy; } public void setStrategy(Strategy strategy) { this.strategy = strategy; } class ConcreteStrategyA implements Strategy { } public void execute() { System.out.println("Executing strategy A."); } class ConcreteStrategyB implements Strategy { } public void execute() { System.out.println("Executing strategy B."); } } public static void main(String[] args) { RealSubject proxy = new Proxy(); proxy.request(); // Real subject is instantiated and request is made }
  • 20. Output Example Code: 23. What is the Observer Design Pattern, and how is it implemented in Java? Ans: The Observer Design Pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependent objects are notified. This pattern is widely used in implementing event-handling systems. Try it Yourself >> } } Executing strategy A. Executing strategy B. import java.util.ArrayList; import java.util.List; interface Observer { } void update(String message); public ConcreteObserver(String name) { this.name = name; } class ConcreteObserver implements Observer { private String name; interface Subject { void registerObserver(Observer observer); void removeObserver(Observer observer); public class StrategyPatternExample { } public static void main(String[] args) { Context context = new Context(new ConcreteStrategyA()); context.executeStrategy(); // Executes strategy A context.setStrategy(new ConcreteStrategyB()); context.executeStrategy(); // Executes strategy B } } public void update(String message) { System.out.println(name + " received message: " + message); }
  • 21. Output 24. What is the Factory Method Design Pattern, and how is it implemented in Java? } void notifyObservers(); subject.registerObserver(observer1); subject.registerObserver(observer2); } public void setMessage(String message) { this.message = message; notifyObservers(); } public void notifyObservers() { for (Observer observer : observers) { observer.update(message); } } Observer 1 received message: State has changed. Observer 2 received message: State has changed. } subject.setMessage("State has changed."); } public void removeObserver(Observer observer) { observers.remove(observer); } public void registerObserver(Observer observer) { observers.add(observer); } public class ObserverPatternExample { public static void main(String[] args) { ConcreteSubject subject = new ConcreteSubject(); Observer observer1 = new ConcreteObserver("Observer 1"); Observer observer2 = new ConcreteObserver("Observer 2"); class ConcreteSubject implements Subject { private List observers = new ArrayList<>(); // Use generic type List private String message; Try it Yourself >>
  • 22. Ans: The Factory Method Design Pattern defines an interface for creating objects but allows subclasses to alter the type of objects that will be created. It promotes loose coupling by eliminating the need to bind application-specific classes into the code. Example Code: abstract class Product { } public abstract void doSomething(); class ConcreteCreatorA extends Creator { } public Product factoryMethod() { return new ConcreteProductA(); } class ConcreteCreatorB extends Creator { } public Product factoryMethod() { return new ConcreteProductB(); } abstract class Creator { } public abstract Product factoryMethod(); public class FactoryMethodPatternExample { public static void main(String[] args) { Creator creatorA = new ConcreteCreatorA(); Product productA = creatorA.factoryMethod(); productA.doSomething(); } Creator creatorB = new ConcreteCreatorB(); Product productB = creatorB.factoryMethod(); productB.doSomething(); } class ConcreteProductA extends Product { } public void doSomething() { System.out.println("Doing something in ConcreteProductA."); } class ConcreteProductB extends Product { } public void doSomething() { System.out.println("Doing something in ConcreteProductB."); }
  • 23. Output Example Code: Try it Yourself >> Read More: Factory Method Design Pattern Ans: The Chain of Responsibility Design Pattern allows a request to be passed along a chain of handlers, where each handler processes the request or passes it to the next handler in the chain. This pattern is useful when more than one object can handle a request, and the handler is determined dynamically. 25. What is the Chain of Responsibility Design Pattern, and how is it implemented in Java? abstract class Handler { protected Handler nextHandler; Doing something in ConcreteProductA. Doing something in ConcreteProductB. } public abstract void handleRequest(int request); public void setNextHandler(Handler nextHandler) { this.nextHandler = nextHandler; } class ConcreteHandlerA extends Handler { } public void handleRequest(int request) { if (request == 1) { System.out.println("Handler A handled the request."); } else if (nextHandler != null) { nextHandler.handleRequest(request); } } class ConcreteHandlerB extends Handler { } public void handleRequest(int request) { if (request == 2) { System.out.println("Handler B handled the request."); } else if (nextHandler != null) { nextHandler.handleRequest(request); } }
  • 24. Output Example Code: 26. What is the Decorator Design Pattern, and how is it implemented in Java? Ans: The Decorator Design Pattern allows you to dynamically add behavior to an object at runtime without affecting the behavior of other objects from the same class. It involves creating decorator classes that implement the same interface and delegate calls to the wrapped object. Try it Yourself >> interface Coffee { double cost(); } Handler B handled the request. } public double cost() { return decoratedCoffee.cost(); } class SimpleCoffee implements Coffee { } public double cost() { return 5.0; } class MilkDecorator extends CoffeeDecorator { abstract class CoffeeDecorator implements Coffee { protected Coffee decoratedCoffee; public class ChainOfResponsibilityPatternExample { public static void main(String[] args) { Handler handlerA = new ConcreteHandlerA(); Handler handlerB = new ConcreteHandlerB(); handlerA.setNextHandler(handlerB); public CoffeeDecorator(Coffee decoratedCoffee) { this.decoratedCoffee = decoratedCoffee; } } handlerA.handleRequest(2); // Handler B will handle the request }
  • 25. Output Example Code: 27. What is the State Design Pattern, and how is it implemented in Java? Ans: The State Design Pattern allows an object to change its behavior when its internal state changes. The pattern is typically used to model objects whose behavior depends on their state and to avoid complex conditionals. Try it Yourself >> interface State { void handle(); } Cost of Simple Coffee: 5.0 Cost of Coffee with Milk: 6.0 } public double cost() { return decoratedCoffee.cost() + 1.0; } class ConcreteStateA implements State { } public void handle() { System.out.println("Handling state A"); } class ConcreteStateB implements State { } public void handle() { System.out.println("Handling state B"); } public MilkDecorator(Coffee decoratedCoffee) { super(decoratedCoffee); } public class DecoratorPatternExample { public static void main(String[] args) { Coffee coffee = new SimpleCoffee(); System.out.println("Cost of Simple Coffee: " + coffee.cost()); } coffee = new MilkDecorator(coffee); System.out.println("Cost of Coffee with Milk: " + coffee.cost()); }
  • 26. Output Example Code: 28. What is the Flyweight Design Pattern, and how is it implemented in Java? Ans: The Flyweight Design Pattern is a structural pattern that allows the sharing of objects to support large numbers of fine-grained objects efficiently. It reduces memory usage by sharing common parts of the state between multiple objects. Try it Yourself >> Handling state A Handling state B interface Flyweight { } void display(); class Context { private State state; import java.util.HashMap; import java.util.Map; } public void request() { state.handle(); } public void setState(State state) { this.state = state; } public class StatePatternExample { public static void main(String[] args) { Context context = new Context(); class ConcreteFlyweight implements Flyweight { private String intrinsicState; context.setState(new ConcreteStateA()); context.request(); // Handling state A } context.setState(new ConcreteStateB()); context.request(); // Handling state B }
  • 27. Output Example Code: 29. What is the Memento Design Pattern, and how is it implemented in Java? Ans: The Memento Design Pattern captures and externalizes an object's internal state so that the object can be restored to this state later without violating encapsulation. It involves three components: Originator, Memento, and Caretaker. Try it Yourself >> class Memento { Flyweight with state: State1 Flyweight with state: State1 } flyweight1.display(); flyweight2.display(); } public ConcreteFlyweight(String state) { this.intrinsicState = state; } public class FlyweightPatternExample { public static void main(String[] args) { FlyweightFactory factory = new FlyweightFactory(); Flyweight flyweight1 = factory.getFlyweight("State1"); Flyweight flyweight2 = factory.getFlyweight("State1"); } public Flyweight getFlyweight(String state) { if (!flyweights.containsKey(state)) { flyweights.put(state, new ConcreteFlyweight(state)); } r e t u r n f l y w e i g h t s . g e t ( s t a t e ) ; } } public void display() { System.out.println("Flyweight with state: " + intrinsicState); } class FlyweightFactory { private Map flyweights = new HashMap<>(); // Use generics for type safety
  • 28. private String state; class Originator { private String state; class Caretaker { private Memento memento; } public String getState() { return state; } public String getState() { return state; } public Memento(String state) { this.state = state; } } public Memento retrieveState() { return memento; } public void setState(String state) { this.state = state; } public Memento saveStateToMemento() { return new Memento(state); } public void saveState(Memento memento) { this.memento = memento; } public class MementoPatternExample { public static void main(String[] args) { Originator originator = new Originator(); Caretaker caretaker = new Caretaker(); } public void getStateFromMemento(Memento memento) { state = memento.getState(); } originator.setState("State1"); caretaker.saveState(originator.saveStateToMemento()); originator.setState("State2"); System.out.println("Current State: " + originator.getState());
  • 29. Output Example Code: 30. What is the Composite Design Pattern, and how is it implemented in Java? Ans: The Composite Design Pattern is a structural pattern that allows you to compose objects into tree-like structures to represent part- whole hierarchies. It will enable clients to treat individual objects and compositions of objects uniformly. Try it Yourself >> interface Component { void operation(); } Current State: State2 Restored State: State1 import java.util.ArrayList; import java.util.List; public class CompositePatternExample { public void add(Component component) { children.add(component); } } public void operation() { for (Component component : children) { component.operation(); } } class Leaf implements Component { } public void operation() { System.out.println("Leaf operation."); } } originator.getStateFromMemento(caretaker.retrieveState()); System.out.println("Restored State: " + originator.getState()); } class Composite implements Component { private List<Component> children = new ArrayList<>(); // Specify the generic type for type safety
  • 30. Output Summary This article focused on the key skills of Java developers, covering Java Interview Questions for 10 Years of Experience. It emphasized mastering advanced Java concepts, multithreading, design patterns, and frameworks like Spring and Hibernate. Additionally, it highlighted problem-solving, leadership, and communication skills as essential for senior developers. Try it Yourself >> (a) To make a variable immutable (b) To prevent serialization of a variable (c) To mark a variable as thread-safe (d) To mark a method as final View Answer ⬇ (a) ̀`HashMap` allows null keys, while ̀`ConcurrentHashMap` does not (b) ̀`HashMap` is not thread-safe, while ̀`ConcurrentHashMap` is thread-safe (c) ̀`ConcurrentHashMap` allows duplicate keys, while ̀`HashMap` does not (d) ̀`HashMap` has better performance than ̀`ConcurrentHashMap` in multi-threaded environments View Answer ⬇ Enhance your Java expertise with the Scholarhat Java Programming Course, designed to help you master complex Java concepts for career advancement.Scholarhat Master Classes offer specialized training in Java, ReactJS, and Python. Join now to advance your career! Test Your Advanced Java Knowledge! Q 1: What is the main difference between `HashMap` and `ConcurrentHashMap` in Java? Q 2: What is the purpose of the `transient` keyword in Java? Leaf operation. Leaf operation. } root.operation(); } public static void main(String[] args) { Composite root = new Composite(); Composite composite1 = new Composite(); Leaf leaf1 = new Leaf(); Leaf leaf2 = new Leaf(); composite1.add(leaf1); composite1.add(leaf2); root.add(composite1);
  • 31. Q 3: Which method in Java is used to start a thread? (a) ̀`run()` (b) ̀`start()` (c) ̀`execute()` (d) ̀`launch()` Q 4: What is the output of the following code snippet? Q 5: What is the difference between `==` and `equals()` in Java? (a) ̀ `==` compares object references, while ̀ `equals()` compares object values (b) ̀ `==` compares object values, while ̀`equals()` compares object references (c) ̀`==` is used for primitive data types, while ̀`equals()` is used for objects (d) Both are used interchangeably View Answer (a) 15 (b) 10 (c) 5 (d) Error View Answer View Answer ⬇ ⬇ ⬇ public class Test { public static void main(String[] args) { int x = 10; int y = 5; System.out.println(x + y); } }