1. what are default and static method in interface?
- A default method is a method in an interface that has a concrete implementation.
It is added to add new methods to interface without breaking existing
implementations. It provides common reusable logic to implementing classes.
A static method belongs to the interface itself, not to the implementing class or
instance. It is used to define utility methods related to the interface.
2. Suppose we have two interface and both interface is having same default method
name but differnt impelementation, now a class has implemented both the interfaces
and we want to use the default method of interface B, how do we do that?
- When both the interfaces have same default method, the implementation class will
have to override the default method otherwise it will get compilation error, once
overridden we can use Interface.super.methodName to call specific method of
interface.
3. Comparator, comparable Interface
- Comparable interface
is defined in Java.lang
used for natural ordering,
the class itself implements Comparable and overrides the compareTo method.,
Can only have one implementation of the compareTo method in a class
eg - Collections.sort(studentList); // Uses compareTo
- Comparator Interface
Defined in java.Util
Used to define custom ordering
A separate class or lambda expression can implement Comparator and override the
compare method
Can create multiple comparator implementations for different sorting criteria
eg - Comparator<Student> byAgeDesc = (s1, s2) -> Integer.compare(s2.getAge(),
s1.getAge());
Collections.sort(studentList, byAgeDesc);
You can also use : studentList.sort(Comparator.comparing(Student::getName));
Even though in both cases we call Collections.sort(), but how it behaves depends on
whether a comparator is passed or not
4. Java 17 Features
- Sealed Classes: Restricts which class can extend or implement a class or
interface
eg : public sealed class Animal permits Dog, Cat {} - so only Dog & Cat class can
extend Animal class
- Pattern Matching
- Record Classes: A Concise way to create immutable data classes
eg : public record Person(String name, int age){}
5. This vs super
- Below is the diff
Keyword Refers to Used For
this Current class instance accesses the current object's fields/methods, calls
its own constructor
Super Parent class instance Access superclass fields/methods, call superclass
constructor
6. is-A has-A relationship in java?
7. Abstraction, polymorphism, encapsulation, inheritance?
8. Can a class be static?
- Yes but only if its nested(inner) class. Outer class can not be static because
static means belong to a class but outer class doesn't have anything to belong to.
9. exception in java, checked and unchecked exception and how do we handle it?
- An exception is an event that occurs during the execution that disrupt the normal
flow of instructions. Checked exceptions are those exceptions which are checked by
the compiler during compliation like IOException, FileNotFoundException etc. On the
other hand, unchecked exceptions occur during the runtime of the program eg
NullPointerException, Arithmetic exception
10. what is exception handling in java?
- We can handle an exception in java by using try-catch block or we can throw that
exception to calling class using throws keyword.
11. Map vs Flatmap
- Flatmap is used for flattening the result into a single stream
- List<String> allPhoneNumbers = users.stream()
.map(User::getPhoneNumbers) // Stream<List<String>>
.flatMap(List::stream) // Stream<String>
.collect(Collectors.toList());
12. Lambda expressions
- Lambda expressions are anonymous functions without name, return type and access
modifier and having one lambda symbol.
13. Functional interface example in java and why to use functional interface?
- Runnable, Callable, Comparator, Function, Predicate, Consumer
A functional interface lets you treat functions as objects, enabling powerful
features like lambda expressions, stream operations, and cleaner, declarative code
in Java.
Functional interface is the foundation for lambda expression and method reference.
14. Memory distribution in java and how it works
- Heap Memory - All objects and their instance variables
- Stack Memory - Method call frames(local variables, references, method calls),
Each thread has its own stack, and data is popped off the stack when a method
finishes
- Method area - Class definitions, static variable, constant pool, method bytecode
-Program Counter(PC) Register - Stores the address of the current instructions
being executed for each thread. Each thread has its own PC register
- Native Method Stack - Used when java interacts with native(non java) code
Class loading -> Goes to Method Area
Object creation -> Allocated in Heap
Method call -> Stored in Stack
References -> Stored in stack (pointing to Heap)
Garbage Collector reclaims memory when objects are no longer referenced
15. heap / stack memory: how does it work in Java
- Stack memory stores variable references and method calls while heap memory stores
object
16. Final/Finally/Finalize
- Final is a modifier that can be applied to variables(values can not be changed),
methods(can not be overriden), and classes(can not be extended).
- Finally is a block that is used in a try-catch statement. It always executes,
whether an exception is thrown or not. Typically used for cleanup code like closing
file streams, db connections etc.
- Finalize is a protected method in object class, which is called by Garbage
collector before the object is destroyed. Its primary purpose is to allow an object
to clean up resources before it is removed from memory.
17. Garbage collection in java, and can we call gc on our own?
- Garbage Collection in java is the process by which JVM automatically clears
memory by removing the objects that are no longer used by the program
- Yes we can request GC manually by System.gc() but this doesn't gurantee that GC
will run immediately
18. singleton class and how does we achieve in java?
- Singleton class are those class which have only one instance across the
application for eg, logger class or db connection which is shared commonly across
the application but we can not have multiple instances of it.
We can achieve singleton class by using enums or some other ways in java, but in
springboot its easier because by default @services, @controller, @Repository,
@Component creates singleton class and if we have to change the we can change by
adding @scope("prototype") or request or session etc.
19. Can abstract class have constructor?
- Yes abstract class can have constructor. Eventhough we can't create object of
abstract class because abstract class is incomplete and it may not have any
behaviour but these constructors can have some common fields or perform setup logic
when a subclass is initiated.
20. transient and volatile keyword?
- Transient keyword is used to exclude a field from serialization, while volatile
is used to ensure visibility of changes to a variable across threads, which means
if a variable is volatile, its value is always read from main memory, not from
thread-local cache.
21. what is multithreading?
- Multithreading is a feature in java that allows concurrent execution of two or
more threads within a single program. Each thread runs in parallel, enabling
multitasking.
22. Private method in service class, how to write test cases for that?
- if your private method is used inside a public method, test that public method
23. is hashmap synchronous?
- No HashMap is not synchronized
24. suppose we created two threads, one is altering data in hashmap and other is
traversing the hashamp, what will happen in that scenario?
- It can give concurrentModificationException or corrupt data or even sometimes
program can crash due to Null pointer exception. We should be manually synchronise
the hashmap by using Collections.sychronisedMap() like below or use
concurrentHashMap()
eg - Map<String, String> syncMap = Collections.synchronizedMap(new HashMap<>());
or eg - Map<String, String> concurrentMap = new ConcurrentHashMap<>();
25. Design Pattern
- Design patterns in Java are standard solutions to common software design
problems. They represent best practices refined over time by experienced
developers. These patterns can help make your code more flexible, maintainable, and
scalable.
Categories of Design Patterns:
- Creational patterns:
- Structural patterns
- Behavioural patterns.
26. Creational Pattern?
- Singleton: Ensures only one instance of a class exists and provides a global
access point
- Factory Method: Creates objects without specifying the exact class to instantiate
- Abstract Factory: Produces families of related or dependent objects
- Builder: Separates the construction of a complex object from its representation
- Prototype: Clone existing objects instead of creating new ones from scratch.
27. How do we create a Singleton class in Java?
- Step 1: Create a private static variable once with the new keyword; this instance
will get memory once while class loading
- Step 2: Create a private constructor so that the object can not be created using
the new keyword
- Step 3: Create static getters only to get the instance and no setters
eg:
public class Singleton {
private static final Singleton instance = new Singleton();
// private constructor
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
28. How HashMap work internally?
- Internally, a HashMap uses an array of buckets. It calculates a hash for each key
using hashCode() and maps it to a bucket index. If multiple keys go to the same
index, it handles it using chaining (linked list or tree). During get() or put(),
it looks through the bucket to find the correct key using equals(). When the number
of entries exceeds a threshold, it resizes and rehashes everything. This gives
average-case O(1) performance.
Q. can two key have same hashcode in internal working of hashmap?
- Yes, two keys in a HashMap can have the same hashCode — this is known as a hash
collision. Java handles this by storing such entries in the same bucket, typically
using a linked list or balanced tree. The actual key comparison is done using
equals(), so even if hashcodes match, the keys must be equal to be considered the
same entry.
29. autoboxing, unboxing
- Autoboxing is automatic conversion of primitive type to its corresponding wrapper
class
- Unboxing is automatic conversion of wrapper calss object to its primitive type
eg: Collections like List, Map, Set only store objects, not primitives. Makes code
cleaner — Java handles conversion for you.
List<Integer> numbers = new ArrayList<>();
numbers.add(5); // Autoboxing: int → Integer
int n = numbers.get(0); // Unboxing: Integer → int
30. Marker Interface
- An Interface is recognized as an empty interface (no field or methods) it is
called a marker interface. Examples of marker interfaces are Serializable,
Cloneable, and Remote interfaces.
31. how to clone a class in java, object cloning?
- It can be done in two ways, shallow copy implementing Cloneable interface and
other manual deep copy
Approach 1 - shallow copy
public class Employee implements Cloneable {
private String name;
private int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public Employee clone() {
try {
return (Employee) super.clone(); // shallow copy
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
}
Approach 2 - Manual Deep Copy
public class Address {
String city;
public Address(String city) {
this.city = city;
}
public Address copy() {
return new Address(this.city);
}
}
public class Employee {
String name;
Address address;
public Employee(String name, Address address) {
this.name = name;
this.address = address;
}
public Employee deepCopy() {
return new Employee(this.name, this.address.copy());
}
}
32. notify, notifyall
- With notify(): Only one thread wakes up, others continue waiting. Which thread
gets notified is not guaranteed — it's chosen by the JVM.
With notifyAll(): All waiting threads are notified — they compete for the lock. All
threads are moved to the runnable state, but only one gets the lock at a time.
33. Access modifiers
- Public: Accessible from anywhere in the program.
- Private: Accessible only within the declared class.
- Protected: Accessible within the same package and subclasses in other packages.
- Default (Package-private): Accessible only within the same package (no modifier
needed).
34. Functional programming?
- Functional programming is about writing clean, predictable code using functions,
avoiding side effects, and working with immutable data. It improves code
readability, testability and parallelisation.
Key features of FP: Lambda expressions, Functional Interface, Streams API, Optional
Class, Method Reference
35. difference between Lambda and functional interface?
- Apart from the actual definition, lambda provides the implementation of the
single abstract method of a functional interface.
36. Stream is eager loading or lazy loading?
- Java Stream uses lazy evaluation for intermediate operations and executes only
when the terminal operation is invoked. like collect(), forEach() etc
37. throw vs throws
- throw is used to actually throw an exception object from inside a method, while
throws is used in the method signature to declare that the method might throw one
or more exceptions. throw is about the action; throws is about the declaration.
38. Runnable & callable?
39. Can we extend a functional interface? If yes, how?
- Yes, a functional interface can extend another interface as long as it doesn't
introduce more than one abstract method. The child interface will still be
considered functional if it inherits only one abstract method or adds only
default/static methods.
40. Collection and collections difference
-Collection is a root interface in the Java Collections Framework that defines the
basic operations for data structures like List, Set, and Queue. It represents a
group of objects and provides methods like add(), remove(), and size().
On the other hand, Collections is a utility class in the java.util package that
provides static methods to operate on collections. For example, we can use
Collections.sort() to sort a list, or Collections.synchronizedList() to make a list
thread-safe.
41. How to create immutable class
- public final class Department {
private final String name;
private final List<String> employees;
public Department(String name, List<String> employees) {
this.name = name;
this.employees = new ArrayList<>(employees); // Defensive copy
}
public String getName() {
return name;
}
public List<String> getEmployees() {
return new ArrayList<>(employees); // Defensive copy
}
}
42. Fail-fast & fail-safe iterator?
- Fail-fast iterators are fast but not safe for concurrent modification, while
fail-safe iterators are safe but may not reflect real-time changes or may be slower
due to copying or synchronization.
43. thread.run() vs thread.start()
- run() method calls the run() in main method and not in the new thread. But
thread.start() starts a new thread and call the new overridden run() method.