Java Interview question-15
Java || SpringBoot ||AWS
Question 141: What is the use of default methods in Java?
Interface evolution: They allow adding new methods to interfaces without breaking existing implementations.
Backward compatibility: Default methods enable enhancing interfaces without breaking existing code.
Interface extension methods: They provide a way to define utility methods or common behavior within an interface.
Multiple inheritances of behavior: Default methods allow an interface to inherit behavior from multiple interfaces.
Question 142: What is the use of static methods in Java?
Utility methods: Static methods in interfaces provide utility functions that can be used by implementing classes without the need for an instance of the interface.
Helper methods: They can encapsulate common logic or provide helper functionality related to the interface.
Code organization: Static methods help in organizing related functionality within the interface itself, making the code more structured and maintainable.
Interface-specific behavior: Static methods allow interfaces to provide default implementation or behavior that can be shared among multiple implementing classes.
Question 143: Can we call the non-static method from the static method and why not?
In Java, you cannot directly call a non-static method from a static method. Static methods belong to the class itself and do not have access to instance-specific members, such as non-static fields or methods. Non-static methods require an instance of the class to be invoked, and static methods do not have an associated instance.
However, you can call a non-static method from a static method if you have an instance of the class. This means you either need to create an instance of the class inside the static method or pass an instance of the class as a parameter to the static method.
public class MyClass {
public void nonStaticMethod() {
// Method implementation
}
public static void staticMethod() {
MyClass myObject = new MyClass(); //Create an instance of the class
myObject.nonStaticMethod(); // Call the non-static method
//using the instance
}
}
Question 144: Can abstract class can have final methods in it?
No, an abstract class cannot have final methods in it. The final keyword is used to indicate that a method or class cannot be overridden or extended, respectively. Since an abstract class is intended to be subclassed and extended, declaring a method as final would contradict the purpose of an abstract class.
Question 145: If two interfaces have the same two defaults methods what will happen, and how to resolve that?
If two interfaces define the same default method with the same method signature, it will cause a compilation error. This situation is known as a “diamond problem”
To resolve the diamond problem in Java 8 interfaces, you have a few options:
Override the default method: In the class implementing both interfaces, you can override the conflicting default method and provide your own implementation. This resolves the ambiguity by explicitly specifying which implementation to use.
Specify the desired default method explicitly: You can use the interface name followed by the method name to explicitly call the default method you want to use. For example, if two interfaces,
AandB, have a default method calleddoSomething(), you can callA.super.doSomething()orB.super.doSomething()to specify which default method implementation to invoke.
Question 146: What is the covariant return type in Java?
Covariant return type refers to the concept in object-oriented programming where a subclass (derived class) can have a method that returns a more specific type than the type returned by the same method in the superclass (base class). This allows for more flexibility and specialization in the inheritance hierarchy.
Question 147: What is LinkedHashmap? how it maintains the insertion order, if we add the same key twice what will happen, will it maintain the same order?
Java LinkedHashMap class is a Hashtable and Linked list implementation of the Map interface, with predictable iteration order. It inherits the HashMap class and implements the Map interface.
This class extends HashMap and maintains a linked list of the entries in the map, in the order in which they were inserted.
public class Test{
public static void main(String[] args) {
Map<String, Integer> lmap = new LinkedHashMap<>();
lmap.put("key1", 1);
lmap.put("key2", 2);
lmap.put("key3", 3);
lmap.put("key1", 4);
System.out.println(lmap);
}
}
Output : {key1=4, key2=2, key3=3}
So the answer is, Yes even if we insert a duplicate key it will override the value and maintain the order as per the above program output.
Question 148: Most popular API Architecture Styles

REST (Representational State Transfer): REST is a widely adopted architectural style for designing networked applications. It is based on a set of principles and constraints, such as using standard HTTP methods (GET, POST, PUT, DELETE) for resource manipulation, statelessness, and a uniform interface. REST APIs use URIs (Uniform Resource Identifiers) to identify resources, and they exchange data in various formats like JSON or XML.
Let’s say we have a simple e-commerce system with a RESTful API for managing products. We can define endpoints and HTTP methods to perform various operations on the product’s resources.
SOAP (Simple Object Access Protocol): SOAP is an XML-based protocol for exchanging structured information over networks. It follows a strict set of rules and uses the XML schema for defining the structure of messages. SOAP APIs typically use the HTTP protocol, but they can also use other protocols like SMTP or TCP. SOAP APIs provide a higher level of protocol abstraction and support more advanced features like encryption and transaction management. The banking and finance industry generally uses soap for security reasons.
SOAP is commonly used in enterprise environments where complex integrations between different systems are required. It provides a strict and standardized messaging protocol that supports advanced features like encryption, digital signatures, and reliable messaging. This makes it suitable for scenarios where security, reliability, and transactional support are critical
GraphQL: GraphQL is an API query language and runtime that allows clients to request specific data from a server. It provides a flexible and efficient approach to data fetching, where clients can request only the data they need and receive it in a single response. Unlike REST, where each endpoint returns a fixed set of data, GraphQL APIs have a single endpoint and clients can shape the response according to their requirements.
powerful querying capabilities of GraphQL make it attractive for companies facebook, GitHub, Shopify, and Twitter to use GraphQL
gRPC (Google Remote Procedure Call): gRPC is a high-performance, open-source framework developed by Google for building remote procedure call (RPC) APIs. It uses the Protocol Buffers (protobuf) as the interface definition language and supports multiple programming languages. gRPC APIs enable efficient communication between services by utilizing binary serialization and HTTP/2 for transport, providing features like bidirectional streaming and authentication.
gRPC offers to build efficient and scalable distributed systems. Google, Netflix, Square, and Uber are some of the companies that uses them.
WebSocket: WebSocket is a communication protocol that provides full-duplex communication channels over a single TCP connection. Unlike traditional HTTP connections that are request-response based, WebSocket allows real-time, two-way communication between a client and a server. It enables continuous data exchange, where both the client and server can send messages to each other without the need for repeated requests. WebSocket is commonly used in applications that require real-time updates, such as chat applications, collaborative tools, and streaming services.
WebSocket’s ability to provide low-latency, bidirectional communication makes it suitable for applications requiring real-time data exchange and instant updates.
Generally messaging application uses WebSocket for example Slack, Discord, Trello, and Robinhood these companies use.
Webhook: A webhook is a mechanism for automatically notifying or triggering events in one system by sending HTTP POST requests to a predefined URL (endpoint) in another system. It allows two systems to communicate with each other by sending data in near real-time. When a specific event or condition occurs in the source system, it triggers the webhook, which then sends the relevant data payload to the target system’s endpoint. Webhooks are commonly used for integrating different services and systems, enabling real-time data synchronization, event-driven workflows, and automated notifications.
Companies like Stripe and GitHub uses this API style
Question 149: Why String is immutable?
Strings are immutable because their values cannot be changed after they are created. Once a string is created, its contents cannot be modified. This immutability provides several advantages, such as efficient memory usage, thread safety, and enabling string interning for improved performance.
Question 150: How to create a Custom Immutable class?
Declare the class
finalto prevent inheritance.Make all the fields
privateandfinal, so they cannot be modified once assigned.Do not provide any setter methods for the fields.
If the class contains mutable objects, make sure to create copies of those objects to avoid modification from external sources.
Ensure that any methods that return the class’s internal state do not expose the actual references to mutable objects.
If necessary, provide methods to access the fields, but make sure they return copies or immutable versions of the objects.
Implement the
hashCode()andequals()methods correctly, considering the immutable state of the object.Consider making the class implement the
Serializableinterface to support serialization if needed.
