Wednesday, August 7, 2024

SSE -Java/J2ee Interview questions

 

1.ArrayList vs LinkedList

First of all, you should be aware that they both implement the List interface, an abstract structure built to maintain the ordering of the elements inserted. The main difference is that LinkedList additionally implements the Deque interface, so developers can use it as a standard FIFO-like structure.

The internals of the two collections differ a lot. While ArrayList is based on an auto-resizable array, LinkedList uses pointers to the next and previous elements, building a chain of elements to grant access to data. This means that choosing the correct structure depends on the use case, as the performance may vary greatly depending on this.


2. REST vs SOAP 

The theoretical differences, such as “SOAP is a protocol and REST is not,” . Something that is usually not mentioned during comparisons and that can help detect if the candidate has real experience with both, is the use of Web Service Definition Language (WSDL) files.

WSDL files are usually used to generate communication STUBs in Java. Is there any tool or technology that helps us do the same with REST endpoints? The answer is yes, and it’s called OpenAPI. Documenting web services is one of the most important things to do when providing functionality.  

3. Merge vs rebase

 

When it’s not possible to merge two branches because of conflicts, developers have two options: merging or rebasing. A rebase may be needed when reserving a clean Git history is important. Rebasing means to move the base of a branch on top of the leaf of another. Instead of having branches intersect multiple times, you can have a clean Git history, as long as everyone follows the golden rule of rebasing: never rebase a public branch.

Stashing is a powerful tool to put aside code that you just wrote, without pushing it to any remote tracked branch. While it’s possible to create multiple stashes at once by giving them different names, it’s usually better to not have more than one stash, as things can become complex to restore. 

4. Define the testing pyramid and its layers

 Being able to identify all the layers (unit testing, integration testing, UI testing) should be enough for a junior developer, but for more experienced candidates, it’s better to make sure they have also implemented some of those using different tools or technologies. 

5. How to sort HashSet of integers?

 Set is by default an unordered structure. So the answer is simply no unless we use an additional data structure.

Starting from this question, it’s possible to:

  1. Investigate the candidate's knowledge of Java collections. TreeSet, LinkedHashSet, and List are only some of the possible solutions.

6. Describe an exception hierarchy 

This abstraction is useful in several ways: first, it’s possible to catch exceptions at various levels of the hierarchy, and second, it’s possible to further extend the family of exceptions with peculiar and ad-hoc use cases.

A further related question to ask regards the concept of “fault barriers,” which I encourage every senior Java developer to understand if they aren’t already familiar with the construct.

7. How to identify performance issues in an application?

 The first step in identifying and resolving a performance issue is measuring the actual performance of the behavior. Only then can an optimization make any sense, otherwise the enhancement cannot be measured.

Identification of the precise piece of the business logic to optimize may occur manually by inserting logs measuring time, or by using profiling tools that automatically decouple the various pieces of the flow measuring time spent in the execution.

When asked this senior Java developer interview question, experienced candidates may also want to describe one of the hardest performance issues they have faced, or trivial issues that can be easily avoided by adopting a series of good practices and keeping an eye on performance during the whole development lifecycle.

8. How to handle huge data on Redis cache?

The candidate’s first reaction to this question should be, “Does it make sense to have huge data on Redis?” A distributed cache is built primarily to enhance the performance of a distributed microservice application. Together with the physical limit of the RAM available for the Redis host, there is a software limit on a single item of 512MB. To store a huge data load, we should be able to split it into chunks and retrieve results, for example by using the HGETALL command. Compression before storing the data might also be an option.

Generally speaking, Redis was not built to achieve this. Retrieving vast chunks of data has been indicated as one of the worst practices. A way better solution could be to store the data object in a standard NoSQL database.

The goal of this interview question is to check the previous experience of senior Java developer candidates, with a focus on how they propose new solutions instead of sticking to the plan.

9. Define AOP and its biggest pitfall

Aspect-oriented programming (AOP) is a powerful feature implemented in the Spring framework. Its most common use cases are logging, authorization, and caching.

The most common pitfall that the candidate should be aware of is the probable performance drop when using AOP, as it uses reflection under the hood, and Java reflection isn’t free (direct call to methods is way faster). This can make business logic a little difficult to read to someone who’s skilled in this way of programming.

10. What are the limitations of GET?

The GET method in HTTP should be used only to retrieve resources from a web server, without altering the state of the application in any way. An exception to this is when we have caching. In this case, a slight modification to the state of the application might be tolerable.

Limitations of GET usually regard the fact that the method cannot theoretically have a request body, so every parameter should be included in the URL, and the URL has a limited length (~2K characters). In practice, it is possible to send a body with the GET method even if this is not a good practice and should be avoided.

With 2K characters available, we are certain to have all the input needed to retrieve a resource from a web server.



Topic 1: Project flow and architecture


inquire about its functionality, flow, and architecture. I’ll also ask about the tech stack and how it is deployed in production, as well as their role and contributions.




Topic 2: Core Java

  • String Concepts/Hashcode-Equal Methods

      String Concepts

  1. Immutability:

    • Definition: Once a String object is created, it cannot be changed.
    • Reason: Immutability ensures thread safety and enables the string pool mechanism.
  2. String Pool:

    • Definition: A special memory region where Java stores String literals.
    • Benefit: It saves memory by reusing instances of String literals.
  3. String Methods:

    • Common methods include length(), charAt(int index), substring(int beginIndex, int endIndex), toUpperCase(), toLowerCase(), concat(String str), replace(char oldChar, char newChar), etc.
  4. Creating Strings:

    • Using literals: String str = "Hello";
    • Using new keyword: String str = new String("Hello");

    hashCode() and equals() Methods

            These methods are essential for the correct functioning of collections like HashSet, HashMap, HashTable, etc.

        equals() Method

  • Purpose: To check if two objects are logically equal.
  • Default Implementation: Inherited from Object class, which compares memory addresses.
  • Override: Override this method to compare the values of the objects.

   hashCode() Method

  • Purpose: To return an integer representation of the object’s memory address.
  • Contract with equals():
    • If two objects are equal (equals() returns true), they must have the same hash code.
    • If two objects have the same hash code, they are not necessarily equal.
  • Immutability(custom immutable class and example in JDK)


             Immutability means that once an object is created, its state cannot be modified. Immutable objects are inherently thread-safe and have several benefits, including simplicity, safety, and ease of maintenance.

             Creating a Custom Immutable Class

                To create an immutable class, follow these principles:

    1. Declare the class as final so it cannot be subclassed.
    2. Declare all fields as private and final so they cannot be modified after initial assignment.
    3. Do not provide setter methods.
    4. Initialize all fields via the constructor.
    5. Ensure that mutable fields are not exposed (e.g., by returning copies instead of direct references).

      Benefits of Immutability

      1. Thread Safety: Immutable objects can be shared freely between threads without synchronization.
      2. Simplicity: Immutable objects are easier to understand and reason about since their state cannot change after construction.
      3. Security: Immutable objects are inherently more secure since their state cannot be altered, reducing the risk of unintended side effects.
      4. Cache-Friendly: Immutable objects can be cached or used as keys in hash-based collections without the risk of their state changing, ensuring consistency
  • OOPS concepts(all four pillars and solid principle)

                Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code to manipulate that data. The four main pillars of OOP are encapsulation, abstraction, inheritance, and polymorphism. Additionally, the SOLID principles are a set of guidelines that can help improve object-oriented design.

### Four Pillars of OOP

1. **Encapsulation**
   - **Definition**: Encapsulation is the bundling of data (attributes) and methods (functions) that operate on the data into a single unit or class. It restricts direct access to some of the object's components, which can protect the object's internal state from unintended interference and misuse.
   - **Example**:
     ```java
     public class Person {
         private String name;
         private int age;

         public String getName() {
             return name;
         }

         public void setName(String name) {
             this.name = name;
         }

         public int getAge() {
             return age;
         }

         public void setAge(int age) {
             this.age = age;
         }
     }
     ```

2. **Abstraction**
   - **Definition**: Abstraction is the concept of hiding the complex implementation details and showing only the essential features of the object. It helps in reducing programming complexity and effort.
   - **Example**:
     ```java
     public abstract class Animal {
         public abstract void makeSound();
     }

     public class Dog extends Animal {
         @Override
         public void makeSound() {
             System.out.println("Bark");
         }
     }
     ```

3. **Inheritance**
   - **Definition**: Inheritance is the mechanism by which one class (child or subclass) can inherit the properties and behaviors (methods) of another class (parent or superclass). This promotes code reuse and establishes a natural hierarchy.
   - **Example**:
     ```java
     public class Vehicle {
         protected String brand;

         public void honk() {
             System.out.println("Beep Beep!");
         }
     }

     public class Car extends Vehicle {
         private String modelName;

         public Car(String brand, String modelName) {
             this.brand = brand;
             this.modelName = modelName;
         }

         public String getModelName() {
             return modelName;
         }
     }
     ```

4. **Polymorphism**
   - **Definition**: Polymorphism allows objects to be treated as instances of their parent class rather than their actual class. The two types of polymorphism are compile-time (method overloading) and runtime (method overriding).
   - **Example**:
     ```java
     public class Animal {
         public void makeSound() {
             System.out.println("Some sound");
         }
     }

     public class Cat extends Animal {
         @Override
         public void makeSound() {
             System.out.println("Meow");
         }
     }

     public class Main {
         public static void main(String[] args) {
             Animal myCat = new Cat();
             myCat.makeSound();  // Outputs "Meow"
         }
     }
     ```

### SOLID Principles

1. **Single Responsibility Principle (SRP)**
   - **Definition**: A class should have only one reason to change, meaning it should have only one job or responsibility.
   - **Example**:
     ```java
     public class Invoice {
         private final Order order;

         public Invoice(Order order) {
             this.order = order;
         }

         public void printInvoice() {
             // Print the invoice
         }

         public void saveToFile() {
             // Save the invoice to a file
         }
     }
     ```
     To adhere to SRP, the printing and saving functionality should be moved to separate classes.

2. **Open/Closed Principle (OCP)**
   - **Definition**: Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification.
   - **Example**:
     ```java
     public abstract class Shape {
         public abstract double calculateArea();
     }

     public class Rectangle extends Shape {
         private final double length;
         private final double width;

         public Rectangle(double length, double width) {
             this.length = length;
             this.width = width;
         }

         @Override
         public double calculateArea() {
             return length * width;
         }
     }

     public class Circle extends Shape {
         private final double radius;

         public Circle(double radius) {
             this.radius = radius;
         }

         @Override
         public double calculateArea() {
             return Math.PI * radius * radius;
         }
     }
     ```

3. **Liskov Substitution Principle (LSP)**
   - **Definition**: Objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program.
   - **Example**:
     ```java
     public class Bird {
         public void fly() {
             System.out.println("Flying");
         }
     }

     public class Ostrich extends Bird {
         @Override
         public void fly() {
             // Ostriches can't fly
             throw new UnsupportedOperationException("Ostriches can't fly");
         }
     }
     ```
     The `Ostrich` class violates LSP. It should not be a subclass of `Bird` if it cannot perform the `fly` operation.

4. **Interface Segregation Principle (ISP)**
   - **Definition**: Clients should not be forced to depend on interfaces they do not use. It’s better to have many small, specific interfaces rather than a single, general-purpose interface.
   - **Example**:
     ```java
     public interface Workable {
         void work();
     }

     public interface Eatable {
         void eat();
     }

     public class Worker implements Workable, Eatable {
         @Override
         public void work() {
             // working
         }

         @Override
         public void eat() {
             // eating
         }
     }
     ```

5. **Dependency Inversion Principle (DIP)**
   - **Definition**: High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions.
   - **Example**:
     ```java
     public interface Keyboard {
     }

     public interface Monitor {
     }

     public class StandardKeyboard implements Keyboard {
     }

     public class StandardMonitor implements Monitor {
     }

     public class Computer {
         private final Keyboard keyboard;
         private final Monitor monitor;

         public Computer(Keyboard keyboard, Monitor monitor) {
             this.keyboard = keyboard;
             this.monitor = monitor;
         }
     }
     ```

                    By adhering to the four pillars of OOP and the SOLID principles, you can create software that is modular, maintainable, and scalable. These principles help manage complexity and ensure that your codebase can evolve over time without becoming unmanageable.
  • Serialization (serialversionUUID)
  • Collection Framework/concurrent collection(they Hashamap, concurrent hashmap, ArrayList,HashSet)
  • Exception Handling(especially Runtime exception)
  • Multithreading especially Executor Framework which includes ThreadPool(deadlock, Thread-dump)
  • Java Memory Model(how objects, methods, and variable gets stored in each area of Java memory)
  • Garbage collection(working of it, how it garbage collects the object, algorithm used while doing it)




Question:

How does ThreadPoolExecutor work?
How do you create a custom immutable class? What are examples of immutable classes in Java?
What are hashCode() and equals()? If you have Object as a custom key in a map, what will happen? How to use it correctly?
What are deep copy and shallow copy?
What is CompletableFuture?
What is the Java Memory Model as per the latest Java version?
What is a concurrent collection?
What are the time/space complexities of HashMap, ArrayList, and LinkedList?
What algorithm is used by these Java APIs Arrays.sort() and Collections.sort()?
How do you create a custom annotation in Java?
What is CompletableFuture?
What are deep copy and shallow copy?
How do HashMap and HashSet work internally?
What is the use of String’s join() method?



Topic 3: Java-8/Java-11/Java17

Topics:

  • Java 8 features
  • Default/Static methods
  • Lambda expression
  • Functional interfaces
  • optional API
  • stream API
  • pattern matching
  • text block
  • modules






Questions:

What is new in Java 8/Java11/Java17?
What is a parallel stream in Java and how does it work?
What is the new improvement in the Java memory model, improvement in Java 8 hashmap?



Topic 4: Spring Framework, Spring-Boot, Microservice, and Rest API


Topics:

  • Dependency Injection/IOC, Spring MVC
  • configuration, Annotations, CRUD operations
  • Bean, Scopes, Profiles, Bean lifecycle
  • App context/Bean context
  • AOP, Exception Handler, Control Advice
  • Security(JWT,Oauth)
  • Actuators
  • WebFlux and Mono Framework
  • HTTP methods
  • Microservice concepts
  • Spring Cloud
  • JPA

Questions:

What is the use of these annotations — @RequestMapping @RestController @Serivice @Repository @entity

What is an Actuator and its uses?
How do you make your application fault-tolerant and resilient?
What is distributed tracing? What is the use of traceId and spanId in a Spring Boot application?
What is WebFlux and Mono Framework in Spring Boot?
What is a cyclic dependency in Spring, and how do you prevent it?
How to secure REST APIs?
What is distributed tracing? What is the use of traceId and spanId in a Spring Boot application?
What is WebFlux and Mono Framework in Spring Boot?
How to make your application fault-tolerant and resilient?
How do you disable auto-configuration in a Spring Boot application?



Topic 5: Hibernate/Spring-data Jpa/Database(SQL or NoSQL)

Topics You should be aware are,

  • JPA Repositories
  • Relationship with Entities
  • SQL queries on Employee department queries, Highest Nth salary queries
  • Relational and No-Relational DB concepts
  • CRUD operations in DB
  • joins, indexing, procs, functions,

Questions

What is the Difference between SQL and NoSQL?
What is sharding in databases?
What is JPA?
What is the Parent-Child Relationship?
What are joins?


Topic 6: Coding


Topics:

  • Stream API coding Questions
  • Normal Coding questions related to String and Array
  • Sorting and searching using Java API.

Questions

Write a program to find the second-highest element from an array. The array can contain duplicate elements. Solve it using Java 8 streams.

Find the duplicate element and its occurrence in a given string using the Stream API.

Write a program to find the first non-repeating element from a given string using Java Streams.

Write a program to find unique elements in a given string using Java streams.

Write a program to find the longest string in a given array.

Write a program to sort two types of numbers to the left and right in an array. Example: Integer array[] = [5, 5, 0, 5, 0] -> output: [0, 0, 5, 5, 5]

Write a program to find the first repeating element/character from a given string using Java Streams.

Write a program for valid parenthesis.

WAP to find the duplicate characters in a list of strings using the Stream API?

Topic 7: Devops questions on deployment Tools(Kubernetes,Cloud,Kafka,cache)



Questions:

What are POD, Configmap, Node, and cluster in Kubernetes?

What is a Hybrid cloud?
What is Apache Spark? Can you give me a use case using a Spring Boot application?
What is Kafka? How does it work? What are offset and consumer groups?



Topics 8: Best practice(Design pattern/Microservice pattern)



Microservice is heavily used nowadays, and with that different types of patterns also come into the picture like,

Circuit Breaker
SAGA
CQRS
Two-phase commit, BFF, API Gateway,

 

Question:

What is a Singleton design pattern, builder design pattern, or facade design pattern?
What are the common microservice patterns we should be using? Tell me about any two.
These topics always get repeated so by preparing them you can crack the final part of it.



https://rathod-ajay.medium.com/your-guide-to-clear-java-developer-interview-in-2024-36a926ec6719

No comments:

Post a Comment