2. Random Interview Question

 






Object Class Methods (total are 11 Methods)

1. toString() method

2. hashCode() method

3. equals(Object obj) method

4. finalize() method

5. getClass() method

6. clone() method

7. wait(), 

8. notify() 

9. notifyAll() methods



What is Difference between @Componet and @Bean ?

- both Indicate Object creation.

- but if we have source code we can open the class on the top of class we can write at @Component if class is programmer define means we created the class then we can use it @Component . 

- If class is predefined and if we want create object inside container then at that time we have to use @Bean(Java Based Configuration)  annotation along with @Configuration (Java Based Configuration).  



Use of @Required Annotation ?

- @Required annotation is applied to bean property setter methods.

- @Required is an annotation that indicates that a bean property must be populated at configuration time. It ensures that a required dependency is injected before the bean is used.

- Note that @Required only applies to setter methods, not constructor arguments. It's a way to ensure that dependencies are injected through setter methods, making it explicit that the bean requires this dependency to function properly.




------------


1. Difference between Hashcode() and equal() Methods

-

1. equals() Method

2. hashcode() Method .


- Both are equals() and hashcode() method override from Object class. 

- equals() checks for content equality, while hashCode() generates a unique code for an object.

- equals() is used for comparison, while hashCode() is used for storage and retrieval in hash-based collections.

- equals() takes an Object as a parameter, while hashCode() takes no parameters.

- Contract between equals() and hashCode():

- If two objects are equal according to the equals() method, then they must have the same hash code according to the hashCode() method.

- If two objects have the same hash code, it does not mean they are equal according to the equals() method.

1. The equals() method is used to compare the content of two objects.

1. The hashCode() method is used to generate a hash code value for an object.

2. It checks whether the values of the objects are equal or not.

2. It is used to store and retrieve objects from a hash-based collection like HashMap or HashSet.


3. It return Boolean value either true or false.

3. It takes no parameters and returns an int value.

            




------------


2. Difference btw Comparable & Comparator

 -

Java provides two interfaces to sort objects using data members of the class: 


1. Comparable 

2. Comparator


1. Comparable provide a single sorting sequence. In other word, can sort the collection on the basis of single element such as id, name and price.

1. Comparator provide multiple sorting sequences. In other word can sort the collection on the basis of multiple element such as id, name and price.


2. Comparable affects the original class. that is the actual class is modified. 

2. Comparator doesn't affect the original class that is actual class is not modified.


3. Comparable provides compareTo() method to sort element.

3. Comparator provide compare() method to sort elements.

4. Comparable is present in java.lang package.

4. A comparator is present in java.util package.

5. We can sort the list element of Comparable type by Collections.sort(List) method.

5. We can sort the list elements of Comparator type Collections.sort(List, Comparator) method.






------------



3. What does the @springBootApplication annotation do internally ?

- @SpringBootApplication


1. @Configuration

- @Configuration is used in class level and it specifically indicates that a class Contains one or more than one @Bean methods.

- @Configuration allow to register(add) extra beans in the context or import additional configuration classes

- when we use @Configuration annotation then spring automatically identify that class and process its bean method .


2. @EnableAutoConfiguration

- Using @EnableAutoConfiguration annotation, Spring Boot automatically configures the  beans based on classpath settings, existing beans, or jar Dependency that we added in POM.xml file.

- This annotation will automatically configures our application we don’t need to configure manually.


3. @ComponentScan

- @ComponentScan scans for Spring components.

- @ComponentScan annotation will automatically scans all the beans, current package and its sub-packages for components.

- It will automatically scan all the components added to our project.

- Developers can customize the base package using the basePackages attribute.



------------



4. How we handle validation in spring boot application ?

- Hibernate validator offers validation annotations for Spring Boot that can be applied to the data fields within your Entity class.

- We have to need add a spring-boot-starter-validation  dependency.

- We have some validation annotation that we apply with the field  with specific validation rule.

- Annotation are :

1. @NotNull: Ensures a field is not null.

2. @NotBlank: Enforces non-nullity and requires at least one non-whitespace character.

3. @NotEmpty: Guarantees that collections or arrays are not empty.

4. @Min(value): Checks if a numeric field is greater than or equal to the specified minimum value.

5. @Max(value): Checks if a numeric field is less than or equal to the specified maximum value.

6. @Size(min, max): Validates if a string or collection size is within a specific range.

7. @Pattern(regex): Verifies if a field matches the provided regular expression.

8. @Email: Ensures a field contains a valid email address format.

9. @Digits(integer, fraction): Validates that a numeric field has a specified number of integer and fraction digits.

10. @Past and @Future : Checks that a date or time field is in the past and future respectively.

11. @AssertTrue and @AssertFalse: Ensures that a boolean field is true. and false respectively.

12. @CreditCardNumber: Validates that a field contains a valid credit card number.

13. @Valid: Triggers validation of nested objects or properties.

14. @Validated: Specifies validation groups to be applied at the class or method level.





------------


5. How to Handle Exception in Spring Boot Application ?

-

There are multiple way to Handle Exception in spring boot application.  as like Gloabl exception handle using @ControllerAdvice annotation, Controller specific exception using @ExceptionHandler annotation, then we can  @RestControllerAdvice annotation which combination of @ControllerAdvice and @ResponseBody , or we can create our own custom Exception , we can also handle Asynchronous Exception using @AsyncExceptionHandler Annotation , or we can handle exception implementing the HandlerExceptionResolver interface.



1. Global Exception Handling with @ControllerAdvice

- One of the fundamental ways to handle exceptions globally in a Spring Boot application is by using the @ControllerAdvice annotation. 

- we can apply global exception handler across all controller. 

- This annotation allows you to define global exception handlers that will be applied across all controllers.

Example :

@ControllerAdvice

public class GlobalExceptionHandler {


  @ExceptionHandler(Exception.class)

    public ResponseEntity<String> handleException(Exception e) {

        return new ResponseEntity<>("An unexpected error occurred: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);

    }

}

2. Controller-Specific Exception Handling 

- using @ExceptionHandler annotation we can handle exception directly in the controller class.

3. ResponseEntityExceptionHandler

- Spring Boot provides ResponseEntityExceptionHandler for handling exceptions and returning appropriate ResponseEntity instances.


4. Default Exception Handling with @RestControllerAdvice

- Similar to @ControllerAdvice, Spring Boot 2.3 introduced @RestControllerAdvice, which combines @ControllerAdvice and @ResponseBody.

Example :

@RestControllerAdvice

public class GlobalRestControllerAdvice {


    @ExceptionHandler(RuntimeException.class)

    public ResponseEntity<String> handleRuntimeException(RuntimeException e) {

        return new ResponseEntity<>("A runtime exception occurred: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);

    }

}

By using @RestControllerAdvice, you can directly return the response body without needing to wrap it in a ResponseEntity.


5. Custom Exception Classes

- Create custom exception classes to represent different types of exceptions in your application. This improves code readability and maintainability.




6. Asynchronous Exception Handling

- When dealing with asynchronous methods, Spring provides @Async and @AsyncExceptionHandler to handle exceptions in these scenarios.

7. Exception Handling with HandlerExceptionResolver

- Another way to handle exceptions in Spring Boot is by implementing the HandlerExceptionResolver interface.





------------


6. How does HashMap Internally work ?


Node : Hash | key | value | next |


- It key-value pair .

- 16 is initially bucket size of HashMap.

- HashMap use hash code to find the bucket.

- HashMap use singly linked list to store elements, these are called bins or buckets.

  - HashMap works on hashing algorithm and uses hashCode() and equals() method on key for get and put operations.

- using Hashcode  we can identify bucket, hashCode is used to check if there is already a key with same hashCode or not. 

- then we check key using equal() method if there is key matched then value will overwrite.

- If there is no key with same hashCode then mapping is inserted into the bucket.



Hashing Collision : A hash collision occurs when a hash algorithm produces the same hash value for two different input values. 




- Difference between Hashcode() and equals() Method ?



------------



7. Java doesn’t support multiple Inheritance. Why?

Ans: To maintain a simpler and more manageable class hierarchy, Java does not support multiple inheritances to avoid ambiguity and complexity which arises from inheriting multiple classes.




------------


- @Data Annotation in  Lombok  

@Data = @ToString , @EqualsAndHashCode , @Getter on all field , @Setter on all non-final field  and @RequiredArgsConstructor.

 




---------


8. Difference btw REST API and a web application?

- Web Application : That is response from a web application is generally view (HTML/css) bcoz they are intended for human viewers.

- REST API just returns data in form of JSON or XML bcoz most of the REST clients are programs.




------------


- What is the Contract between the API and the Client?

- In order to successfully consume the API, the Client must have prior knowledge of these Media Types. In fact, the definition of these media types represents the entire contract.

- So the Media Type definitions are part of the contract.



------------


9. Difference between @SpringBootConfiguration and @SpringBootApplication ?

- The main difference is that @SpringBootConfiguration allows configuration to be automatically located. This can be especially useful for unit or integration tests. The recommendation is to only have one @SpringBootConfiguration or @SpringBootApplication for your application.




------------


10.  What are the differences between @MockBean and mock?

- Main difference between @MockBean and @Mock annotation is that @MockBean creates mock and injects it into Application Context, while @Mock annotation only creates it, if you want to inject it, you can do it manually or with @InjectMocks annotation, however injection is being done to the class not whole Application




------------


- There are three steps to create a WAR for deployment:

1. Extends the SpringBootServletInitializer class in the main class.

2. Marked the embedded servlet container as provided.

3. Update packaging JAR to.



------------




11. Fail-Fast vs Fail-safe (Non Fail-Fast) Iterator


- iterator is interface use to traverse collection objects, such as Arraylist or Hashset.

- When we try to modify collection such add element or remove element while using an itertor then ConcurrentModificationException occur.



Fail-Fast iterator

- The fail fast iterator throw ConcurrentModifiacationException immediately while when we try Modify the collection.

- Structural Modification means add , remove , update the value of an element in data Collection while another thread is iterating over that collection.

- at time of modification when collection is iterating if we try modify as add new element where one thread adding new element and  then another thread iterating over that collection then not allow  . 

- its happens bcoz Fail Fast iterator use original collection to transverse over the collection element.

- Example of Fail Fast iterator are iterator on Array list, HashMap collection classes.



Fail Safe Iterator

- Fail Safe iterator not throw the ConcurrentModificationException during the iteration.

-  bcoz Fail safe use the copy of Collection to traverse over the element. 

- However , there is not ant actual word written as Fail-safe in JavaSE documentation , instead the Fail Safe is termed as non-Fail fast iterator.

- Unlike the fail fast, they require more memory as they cloned the Collection.

- Fail Safe iteration use the more memory bcoz they cloned the collection.

- Example of fail safe iterator are ConcurrentHashMap , CopyOnWriteArrayList.




-------------


12. What is Marker Interface ?

- Marker interface is empty interface bcoz its not contain any field or methods.

- It provides run-time type information about objects, so the compiler and JVM have additional information about the object. 

- A marker interface is also called a tagging interface.

- Examples of marker interface are Serializable, Cloneable and Remote interface. All these interfaces are empty interfaces. 

- The Cloneable interface in Java is a marker interface. A marker interface doesn't have any methods but simply marks a class as having a certain capability. In the case of Cloneable, it indicates that instances of the implementing class can be cloned using the clone() method.



-------------



13. What is Object Cloning ? what shallow & Deep copy ?

- The Prototype Pattern works on the Cloning concept. However, in Java, if you’d like to use cloning, you can utilize the clone () method and the Cloneable interface. By default, clone () performs a shallow copy. Moreover, Serializable can be used to simplify deep copying.


-  Shallow Copy and Deep Copy

-  Shallow Copy 

- If We have object which reference to other object. When we perform the shallow copy ,then we copying top-level structure it including primitives data types, not a object. so copy object & original object  share the same reference to same object. if we change one of it then it changes for both.

 

- Deep Copy 

- deep copy creates a new instance of each referenced object within the original object. So, even if you make changes to the referenced objects through one instance, it won't affect the other instance. This ensures that changes made in one instance don't affect the other.




-----------


14. Differences Between Shallow Copy and Deep Copy


Shallow Copy        Deep Copy

-It is fast as no new memory is allocated. - It is slow as new memory is allocated.

-Changes in one entity is reflected in other entity. - Changes in one entity are not reflected in changes in another identity.

-The default version of the clone() method supports shallow copy. - In order to make the clone() method support the deep copy, one has to override the clone() method.

-A shallow copy is less expensive. - Deep copy is highly expensive.-

-Cloned object and the original object are not disjoint. - Cloned object and the original object are disjoint.

- A shallow copy is faster. - Deep copy is comparatively slower.

- Shallow Copy stores the references of objects to the original memory address.   - Deep copy stores copies of the object’s value.

- Shallow Copy reflects changes made to the copied object in the original object. - Deep copy doesn’t reflect changes made to the copied object in the original object.

Shallow Copy stores the copy of the original object and points the references to the objects. Deep copy stores the copy of the original object and recursively copies the objects as well.

 


---------------


15. Explain HashTable  ?

- hashtable contains the data in key-value pair & each key-value pair is known as entry.

- In hashtable, key should always be unique but values can be duplicate

- Hashtable can store heterogeneous elements or different type of elements at key positive.

- We cannot store null value in Hashtable

- Hashtable does not follows the insertion & sorting order.

- Hashtable are synchronized data-Structure.

- The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.



16. What is  Concurrent Hashmap (2 ascept : race condition , concurrent modification exception)  


Map

| extends

    ConcurrentMap

| extends


   ConcurrentNavigableMap   Serializable

| implement

  ConcurrentHashMap


- ConcurrentHashMap is a thread-safe implementation of the Map interface in Java, which means multiple threads can access it simultaneously without any synchronization issues.

-One of the key features of the ConcurrentHashMap is that it provides fine-grained locking, meaning that it locks only the portion of the map being modified, rather than the entire map.

-In ConcurrentHashMap, at a time any number of threads can perform retrieval operation but for updated in the object, the thread must lock the particular segment in which the thread wants to operate. This type of locking mechanism is known as Segment locking or bucket locking. Hence at a time, 16 update operations can be performed by threads.

-Inserting null objects is not possible in ConcurrentHashMap as a key or value.


- It provides a thread-safe implementation of hashmap.

- It designed to allow multiple threads to access and modify the map concurrently without need for explicit synchronization.

- This makes it well-suited for scenarios where high concurrency is required and difference thread need to access and manipulate the map concurrently.




Internal Working of ConcurrentHashMap

- Segmented or bucket or fine-grained locking.this locking mechanism concurrent hashmap follow. 

  -1. ConcurrentHashMap achieves high concurrency by dividing its data into segments or partitions, each acting as an indepenedent hash table. (Hashmap internal dataStructure is an Array)

-2. Read operation are fully concurrent , allowing multiple threads to read simultaneously from the same or different segments.

-3. Write operations are synchronized at the segment level to ensure thread safety during updates.( here every segement has lock so cannot write & there is no way to override).

-4. It provides total concurrency for reads, allowing multiple threads to read without blocking.

-5. Unlike Hashtable, ConcurrentHashMap lock only the affected segment during write operation, preventing unncecessary contention. ( During write operation there only one segment are lock other free to read )

-6.This results in better performance and throughput in multi-threaded environments.

-7.Any number of threads can perform READ operation but for WRITE  in object, the thread must lock the particular segment in which  the thread wants to operate.





----------------


16. Differenct between Concurrent HahsMap and Collections.synchronizedMap() ?


1. Concurrent HashMap

2. Collections.synchronizedMap() 


  1. ConcurrentHashMap designed for high level concurrency. Divides the map to segments, where each can be locked independently.

1. synchronizedMap() has lower concurrency. Uses a single monitor to synchronize access to the entire map.


2. Performance better in high-concurrency scenarious.

2. Lower performance due to coarse-grained locking.

3. Thread can access element without causing a ConcurrentModificationException during the iteration.

3. During iteration, if the underlying map is modified by another thread. It may result in a ConcurrentModificationException .


4. Does not support null in key or values.

4. Null support depends on the input Map.


5.ConcurrentHashMap follow Fine-grained locking, enables concurrent access to differenct segments.

5. Coarse-grained locking , locks the entire map for each operation.


----------------------



17. Difference between HashMap and ConcurrentHashMap


- HashMap is the Class which is under Traditional Collection and ConcurrentHashMap is a Class which is under Concurrent Collections, apart from this there are various differences between them which are:


- HashMap is non-Synchronized in nature i.e. HashMap is not Thread-safe whereas ConcurrentHashMap is Thread-safe in nature.

- HashMap performance is relatively high because it is non-synchronized in nature and any number of threads can perform simultaneously. But ConcurrentHashMap performance is low sometimes because sometimes Threads are required to wait on ConcurrentHashMap.

- While one thread is Iterating the HashMap object, if other thread try to add/modify the contents of Object then we will get Run-time exception saying ConcurrentModificationException.Whereas In ConcurrentHashMap we wont get any exception while performing any modification at the time of Iteration.




------------------------



18. What are several Thread-safe classes provided by Java Collections framework?


Answer: Several Thread-safe classes in Java Collections framework are as follows:


Stack

Properties

Vector

Hashtable

BlockingQueue

ConcurrentMap

ConcurrentNavigableMap




----------------



19 Differenect between TreeSet and TreeMap

1. TreeSet implements SortedSet in Java.

TreeMap implements Map Interface in Java


2. TreeSet stored a single object in java.

TreeMap stores two Object one Key and one value.


3. TreeSet does not allow duplication Object in java.

TreeMap in java allows duplication of values.


4. TreeSet implements NavigableSet in Java.

TreeMap implements NavigableMap in Java.


5. TreeSet is sorted based on objects.

TreeMap is sorted based on keys.




---------------



20. What do you know about Factory Design Pattern in Java ?

- Factory design pattern is the most commonly used pattern in Java.

- They belong to creational Pattern bcoz it provides means of creating object of different instances.

- Here, the logic of object creation is not exposed to the client, It is implemented by using standard interface.

- It gives provision to select object types that we need to creation. This is why , they aslo known as Virtual Constructors.



---------------


21. What are the most important feature of Java 8 ?

- Lambda Expression ,Functional Interface , Default Method & Static Method in interface,  Optional , Method reference ,  Stream API , Date API , Nashorn ,Javascript engine.




---------------



22. What are the Spring Boot Staters?

- Spring Boot Starters are a set of pre-configured depedencies that can be easily include in our project to quickly get started with common feature or technologies.

- By including a starter in our project , we can quikcly get up and running with minimal configuration.


Q : What is actually inside spring boot starter dependency

- Spring boot starter is a maven template that contain a collection of all the relevant transitive dependecies that are needed to start a particular functionality.

- Like we need to import spring-boot-starter-web dependency for creating a web application.


---------------



23. What is Spring Boot Actuator ?

- Spring Boot Actuator is set of feature that provide monitoring and management capabilities for our Spring Boot Application.

- Actuator endpoints expose information about our application, such as health status, metric and environment variable, that can be used to monitor and manage our application.


---------------



24. How do u configure same property with different value for difference environment ?

- Profiles in Spring framework enable user to map components and beans to specific profiles. such as the Development(dev) profile , Production(prd) profile, or the Test profile.

- In Spring Boot, the Annotation @Profile is used to  map component and beans to a certain profile.

- Developer can also set up profile using the SpringApplication , for instace, SpringApplication.setAdditionalProfiles("dev");

- Also we can add property in application.properties like -spring.profiles.active=dev

- The profile names can also be passed in via a JVM system parameters. These profiles will be activated during application startup : -Dspring.profiles.active=dev




---------------



25. How can you share your Rest endpoint API contracts with consumers of your applications/clients

- swagger is used to describing the structure of APIs.

- Swagger 2 is an open-source service provided in Spring Boot which makes it easier for the machines to find out the structure of APIs like RESTful Web services.



---------------



26. What is the difference between first Level cache & second level cache ?


- First Level Cache

1. This is local to the Session object and cannot be shared between multiple session.

2. This cache is enable by default & there is no way to disable it. 

3. The first level cache is available only until the session is open , once the session is closed, the first level cache is destroyed.


- Second Level Cache

1. This cache is maintained at the SessionFactory level and shared among all session in Hibernate.

2. This is disabled by default, but we can enable it through configuration.

3. The Second-level cache is available through the application life cycle , it is only destroyed and recreated when an application is restarted.



---------------



27. can we use custom class as key in hashmap ?

- see basically class is mutable object and in collection we use only immutable object that is Wrapper Classes. but still we can include class as key by overriding the equal() and  hashcode() method bcoz class is mutable object so there will be different hashcode generated when once the data of object is changed . so we need to make sure that our class object return only single same hashcode and equals time the object is passed is key . as such way can use custom class as key but we have to use hashcode and equal method.



---------------------



28. What is Reflection in Java ?




-----


29. add and put method (not sure question : visit - https://youtu.be/JXOwT86h0gg?si=EcvmW3Ki5SON6W83    timing 16:00 )


- the method that  will not change the state of  server even if multiple times the same resources is being requested so this is --- like put and delete if you are trying to access same thing multiple time that's what's it is. 



---------


30. How will you prevent the cloning of singleton object ?

- Prevent Singleton Pattern From Cloning

To overcome the above issue, we need to implement/override the clone() method and throw an exception CloneNotSupportedException from the clone method. If anyone tries to create a clone object of Singleton , it will throw an exception



--------------


31. How To create an immutable class in Java ? 


1. Declare the class as final so it can’t be extended.

2. Make all of the fields private so that direct access is not allowed.

3. Don’t provide setter methods for variables.

4. Make all mutable fields final so that a field’s value can be assigned only once.

5. Initialize all fields using a constructor method performing deep copy.

6. Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.



-----------------


32. Do you know profile in Spring boot ?

- the profile is where you have classes and multiple environment while using application there are multiple environment as like Dev environment,  production environment , test environment ,

- so we can have conditional classes for eg . if there is dev environment then i need instance of this class if there is production environment i need instance of this class so to do conditional creation of beans we go for profiles generally if we have profile it is difficult to maintain and best practice is generally to avoid profile unless it is absolutely necessary to use.

- There are multiple way of activating profiles.

1. Environment Variable

2. Maven profile

3. WebApplicationInitializer 

4. JVM System parameter

5. Context parameter in web.xml





-----------


33. Can you tell me what are the main components of microservices and what is the use of API Gateway ?

- In case of microservices architecture so there are for each business related functionality there is one micro project which is either in spring boot or any other language and there are multiple projects running on different port on the same machine or different machine .

- so if you want to access the rest API all the application then we need URL and port in short we need address of each microservice but client cannot have address of each microservices so generally there is API Gateway so client only knows the address of API Gateway

- and API gateway knows for this request which microservice to contact so the basic duty of API Gateway is to accept the request from client and then redirect that request to appropriate microservice and then return the response back to the client 

- so there are various other functionalities which API Gateway handles API Gateway also handle authentication and authorization , API Gateway also handle rate limiting so multiple request are coming from one client which is not acceptable then we can add that logic in API Gateway .

- Azure is common example of API Gateway .



- Core Component of Microservices 

-  API Gateway : An entry point for client requests that routes requests to the appropriate microservices, performs authentication and authorization, and handles other tasks such as caching and request-response mapping.


- Service Discovery : A service registry that helps services locate and communicate with each other.

- Service Orchestration : A layer that coordinates communication and interactions between microservices to ensure that they work together correctly.

- Load Balancer : A component that distributes incoming requests to the appropriate service instances.

- Service Registry : A database of all available microservices, their endpoints, and metadata.


- Circuit Breaker : A mechanism that helps prevent cascading failures by interrupting communication between services when one service is not responding.


- Service Monitoring : A system that tracks the health and performance of microservices and generates alerts in case of failures or performance degradation.


-  Configuration Server : A centralized repository for storing configuration information that is accessible to all microservices.




- Use of API Gateway ?

An API Gateway is a server that acts as an intermediary for API requests.

- An API gateway can provide a single, unified entry point for all of your APIs, and can also handle things like authentication, authorization, and rate limiting. 

- This can make it much easier for developers to consume your APIs, and can also help to reduce the complexity of your overall API landscape.

- We can Improve Security by implementing features authentication, authorization and rate limiting. It protect our API from unauthorized access and abuse.

- API improve performance by chaching response and aggregating request.

- API Gateway can help to scale our APIs by distributing traffic across multiples users. This can help to ensure that your APIs are able to handle large volumes of traffic.




34. What is Jackson ? 

- Jackson is one of the most used libraries of spring boot which translates JSON data to a Java POJO by itself and vice-versa. JSON stands for JavaScript-object-Notation and POJO is our plain-old-java-object class






----------------


35. Async call ?


Before Async 

- Synchronization means every process or thread should be Synchronized together. It means executing process by process that’s we can say Synchronization. This is used when one task is complete and only then does another task want to come and be executed. so It looks like there are some limitations. That’s why asynchronization comes into the picture. The Asynchronization process means We are making a different thread for the same processing. Process or thread does not need to wait for someone to execute. This is The Asynchronization process.



- The @Async annotation is a powerful tool that can be used to improve the performance of our Spring Boot application. 

- @Async annotation is used when you wanna make any method asynchronize. Annotating a method of a bean with @Async will make it execute in a separate thread. - In other words, the caller will not wait for the completion of the called method.


- Method should be public  and method return type should be void, avoid unchecked Exception , we have to use CompletableFuture class which implemented from Future Interface .



- Easier to implement

- Easier to debug

- More intuitive code flow

- Improved Performance

- Better Scalability



- So we have to use  @EnableSync Annotation in  class so that asynchronous method run in background thread pool. 

- and we also use Executor method for that asynchronous method so this that can in background. 




------------


36. What difference between Interface and Abstract class ?

1. Variable : variable in interface are by default public static and final & variable in Abstract class can have final, non-final, static, and non-static variables.

2. Method : interface method by default public and abstract and in abstract class  both abstract and non-abstract (concrete) methods. 

3. Constructor : Inside an interface, we cannot declare/define a constructor because the purpose of constructor is to perform initialization of instance variable but inside interface every variable is always static. and Since an abstract class can have instance variables. Therefore, we can define constructors within the abstract class to initialize instance variables.

4. instance and static block : we cannot declare both of in interface and  in abstract class we can declare.

5. Single vs Multiple inheritance : abstract class extend only one class but in interface  one class can implement multiple interfaces.

6. Uses: If you know nothing about the implementation. You have just requirement specification then you should go to use interface. and If you know about implementation but not completely (i.e. partial implementation) then you should go for using abstract class.



-------------


37. Difference between throw and throws

1. Throw

2. Throws

1. Throw : Used within a method (or constructor)  and Throws : Used with method (or constructor) signature

2. Throw : Used to throw an exception explicitly and Throws : Used to declare exceptions

3. Throw : Can only throw a single exception and Throws : Can declare multiple exceptions

4. Throw : Followed by a throwable instance and Throws : Followed by an exception class name

5. Throw : Cannot be used to propagate checked exceptions by itself and Throws : Can be used to propagate checked exceptions by itself



-------------


38. What is Generic in Java , Types , Advantages ?

- Generics in Java is a mechanism that allows writing code for one type (say T) that is applicable for all types of data, instead of writing separate classes for each type.

- An element such as a class, interface, or method that works on parameterized type is called generic in java. In the above example program, T is the name of a type parameter.

- Type Parameter in Generics

- The type parameter is used as a place holder for the argument types. It can be any non-primitive type such as class, array, interface, or even another type parameter.

- The name of type parameters is usually single and uppercase letters. Java has five kinds of type parameters. They are as:

1. T denotes a Type.

2. E denotes an Element.

3. K denotes a Key

4. N denotes a Number

5. V denotes a Value.



- Advantages of Generics in Java

- The main advantage of generics is reusability. We can reuse the same code for different data types.

- Another advantage of generics is type safety.

- Using generics, we can eliminate typecasting.

- It helps to avoid ClassCastException at runtime.


---------------------


39. Difference between @bean and @Componrnt 

1. Creating in beans in spring.

2. Beans are nothing but objects created by spring container.


 @Component is used for automatic scanning and registering of beans, @Bean is used for explicit manual registration of beans. - Another difference is that @Component is used for general classes while @Bean is used for creating a specific instance of a class and providing it to the Spring container.


1. @Bean

2. @Component 

1. Bean is method level annotation.

1. component is class level annotation.


2. Bean is used to explicitly declare a single bean.

2. Component is used for automatic scanning and registering the bean.

3. It works only when class is also annotated with @Configuration

3. It works without @Configuration annotation.


4. We should use @bean, if you want specific implementation based on dynamic condition.

4. We can’t write specific implementation based on dynamic condition


{ @Configuration + @Bean || @Component }





---------------------

40. What is JWT ?

- JWT stands for JSON Web Token a widely used authentication and authorization technology in web development.

- In Java , JWT is used to create  and verify tokens for secure communication between clients and servers.

- The purpose of JWT : JWT is used for authentication and authorization , allowing servers to verify the authenticity of requests and ensure secure data transmission.

- Structure : A JWT consists of three parts : 1. Header, 2.Payload, 3. Signature encoded in Base64 and separated by dots.


Example Answer : 

- JSON is a standardized method for securely transmitting information between parties. In java, i have used JWT for authentication and authorization, creating and verifying tokens to ensure secure data exchange. Its compact and stateless nature makes it ideal for modern web applications. I have implemented JWT using popular libraries like JJWT or jjwt, ensuring secure user authentication and authorization in my previous projects.


---------------------


41. Authentication and Authorization ?

1. Authentication 

- Verifies the identity of a user , device or system

- Ensure the user is who they claim to be 

- Involves checking credentials (e.g., username/password, token, biometrics)

- Goal - To Confirm the users identity.

2. Authorization 

- Determines what actions an authenticated user can perform

- Checks if the user has the necessary permissions or roles to access resources

- Ensures that users only have access to authorized resources and actions

- Goal : To control access to resources based on user identity and permissions.


Difference :

- Authentication verifies identity.

- Authorization determines access and permission


Ex : Think of it like a bank  :

- Authentication is verifying our identity to log in to our account

- Authorization  is determining what actions you can perform, like withdrawing cash or transferring funds .



------------------------------


42. What is SQL Injection & How to prevent them ?

- What is SQL Injection?

- SQL injection is a type of hacking attack where an attacker inserts malicious code into a website's database to access or modify sensitive information.

- It generally occurs when an application uses user-input data without proper validation or - allowing an attacker to inject malicious SQL code. This can lead to data tampering, data theft, and even complete system compromise.

- Prevent 

- To prevent it, I would keep user input separate from the database code, filter out malicious code, limit database access, and keep software up-to-date. By following these simple steps, we can protect our websites and databases from SQL injection attacks.


- We can use tools like a SonarQube , MySQL Workbench, Burp Suite to  prevent SQL Injection .  




------------------------------


43. Casting Types in Java

1. Implicit Casting (Widening ) :  small to large : byte -> short -> int 

2. Explicit Casting (Narrowing) : Large to small : double -> float -> Long -> int 




------------------------------



44. which method we can use for make non-thread collection object to thread safe ?

1. Collections.synchronizedList()   : List<String> synchronizedList = Collections.synchronizedList(new ArrayList<>());

2. Collections.synchronizedCollection() : Collection<String> synchronizedCollection = Collections.synchronizedCollection(new HashSet<>());

3. ConcurrentHashMap : Map<String, String> concurrentMap = new ConcurrentHashMap<>();

4. CopyOnWriteArrayList : List<String> threadSafeList = new CopyOnWriteArrayList<>();

5. CopyOnWriteArraySet : Set<String> threadSafeSet = new CopyOnWriteArraySet<>();

6. Vector : List<String> synchronizedList = new Vector<>(); (Vector is synchronized by default)

7. Hashtable : Map<String, String> synchronizedMap = new Hashtable<>(); (Hashtable is synchronized by default)






----------------------------



45. profile in spring boot ? 

- In Spring Boot, a "profile" represents a set of configuration settings that can be activated or deactivated based on the environment or deployment scenario.

- Profiles allow you to manage different configurations for different situations, such as development, testing, staging, and production.


Comments

Popular posts from this blog

1. Microservices Interview Question

Food Order System : Customer Service