Infosys
100+ UNii Engineering Consultancy Interview Questions and Answers
String should be preferred for frequent updates due to its immutability.
String is immutable, so every update creates a new instance, leading to memory overhead.
StringBuffer is mutable and allows for efficient updates without creating new instances.
Use StringBuffer when frequent updates are required to avoid unnecessary memory allocation.
Example: StringBuffer is preferred for building dynamic strings in loops.
Q2. 1.What is Singleton in java and create your own singleton class countering all breakable conditions? 2. What is Auto Configuration? 3. @Primary vs @Qualifier 4. What is idempotent? 5. What is class loader? Type...
read moreThe interview questions cover various topics related to Java development, including Singleton pattern, memory management, exception handling, Spring framework, and design patterns.
Singleton pattern ensures a class has only one instance and provides a global point of access to it.
Auto Configuration in Spring Boot automatically configures the Spring application based on dependencies present in the classpath.
@Primary annotation is used to give higher preference to a bean when mu...read more
Q3. write a code to filter out loans with incomplete status using java 8 features.
Code to filter out loans with incomplete status using Java 8 features.
Use stream() method to convert the list of loans into a stream
Use filter() method to filter out loans with incomplete status
Use collect() method to collect the filtered loans into a new list
Abstract class can have both abstract and non-abstract methods, while interface can only have abstract methods.
Abstract class can have constructor, fields, and methods, while interface cannot have any implementation.
A class can implement multiple interfaces but can only extend one abstract class.
Abstract class is used to define common characteristics of subclasses, while interface is used to define a contract for classes to implement.
Example: Abstract class 'Animal' with abst...read more
An interface in OOP is a blueprint of a class that defines a set of methods that a class must implement.
Interfaces in Java are used to achieve abstraction and multiple inheritance.
Interfaces contain only method signatures, not method bodies.
Classes can implement multiple interfaces but can only extend one class.
Example: interface Shape { void draw(); }
Example: class Circle implements Shape { public void draw() { // draw circle } }
The starter dependency of the Spring Boot module is spring-boot-starter-parent.
The starter dependency provides a set of default configurations and dependencies to kickstart a Spring Boot project.
It includes commonly used dependencies like spring-boot-starter-web, spring-boot-starter-data-jpa, etc.
By including the spring-boot-starter-parent in your project, you inherit all the default configurations and dependencies managed by Spring Boot.
Q7. Difference Between Comparator and Comparable. What is fully qualified domain name? What is the working principle for an ArrayList? How do you handle an exception? What is custom exception? What is the differenc...
read moreComparator is used to compare objects for sorting, while Comparable is implemented by objects to define their natural ordering.
Comparator is an external class, while Comparable is implemented by the object itself.
Comparator can compare objects of different classes, while Comparable can only compare objects of the same class.
Comparator uses the compare() method, while Comparable uses the compareTo() method.
User threads are non-daemon threads that keep the program running until they complete, while Daemon threads are background threads that do not prevent the program from exiting.
User threads are non-daemon threads that keep the program running until they complete
Daemon threads are background threads that do not prevent the program from exiting
User threads are created using the Thread class, while Daemon threads are created by calling setDaemon(true) on a Thread object
Examples: ...read more
Enable debugging logs in a Spring Boot application
Add 'logging.level.root=DEBUG' in application.properties file
Use '@Slf4j' annotation in the Java class to enable logging
Set logging level for specific packages or classes using 'logging.level.packageName=DEBUG'
The @SpringBootApplication annotation is used to mark a class as a Spring Boot application and enables auto-configuration and component scanning.
Enables auto-configuration by scanning the classpath for specific types and configuring beans based on their presence.
Enables component scanning to automatically discover and register Spring components such as @Component, @Service, @Repository, and @Controller.
Combines @Configuration, @EnableAutoConfiguration, and @ComponentScan anno...read more
Runnable interface is used for running a task without returning a result, while Callable interface is used for running a task that returns a result and can throw an exception.
Runnable interface has a run() method that does not return a result.
Callable interface has a call() method that returns a result and can throw an exception.
Runnable tasks can be submitted to an ExecutorService for execution.
Callable tasks can be submitted to an ExecutorService as well, but they return a ...read more
MVC components include Model, View, and Controller. Model represents data, View displays data, and Controller handles user input.
Model: Represents data and business logic
View: Displays data to the user
Controller: Handles user input and updates the model and view accordingly
A View is a complete page while a Partial View is a reusable component in MVC.
A View represents a complete page in MVC which can include layout, content, and other views.
A Partial View is a reusable component that can be rendered within a View or another Partial View.
Partial Views are useful for creating modular and reusable components in MVC applications.
Example: A View may contain the overall layout of a website, while a Partial View may represent a sidebar or a navigation ...read more
Session interface in Hibernate is used to create, read, update, and delete persistent objects.
Session interface is used to interact with the database in Hibernate.
It represents a single-threaded unit of work.
It provides methods for CRUD operations like save, update, delete, and get.
Session is created using SessionFactory object.
Example: Session session = sessionFactory.openSession();
Standard Java pre-defined functional interfaces include Function, Consumer, Predicate, Supplier, etc.
Function: Represents a function that accepts one argument and produces a result. Example: Function<Integer, String>
Consumer: Represents an operation that accepts a single input argument and returns no result. Example: Consumer<String>
Predicate: Represents a predicate (boolean-valued function) of one argument. Example: Predicate<Integer>
Supplier: Represents a supplier of result...read more
MVC architecture in Spring separates the application into three main components: Model, View, and Controller.
Model represents the data and business logic of the application.
View is responsible for displaying the data to the user.
Controller acts as an intermediary between Model and View, handling user input and updating the Model accordingly.
Spring MVC framework provides support for implementing MVC architecture in web applications.
Annotations like @Controller, @RequestMapping...read more
Q17. What is java and what is inheritance and what is oops concepts and what is method
Java is an object-oriented programming language. Inheritance is a mechanism to create new classes based on existing ones. OOPs is a programming paradigm. Method is a block of code that performs a specific task.
Java is a high-level, class-based, and object-oriented programming language.
Inheritance is a mechanism in which one class acquires the properties and behaviors of another class.
OOPs is a programming paradigm that focuses on objects and their interactions.
Method is a blo...read more
MVC routes have properties like URL pattern, controller action, and HTTP method.
URL pattern: Defines the path that triggers the route.
Controller action: Specifies the method in the controller that handles the route.
HTTP method: Determines the type of request the route responds to, such as GET, POST, PUT, DELETE.
Example: GET request to '/users' triggers UserController's index method.
Q19. What is polymorphism in both overloading and overriding way?
Polymorphism is the ability of an object to take on multiple forms. It can be achieved through method overloading and overriding.
Method overloading is when multiple methods have the same name but different parameters. The compiler decides which method to call based on the arguments passed.
Method overriding is when a subclass provides its own implementation of a method that is already present in its parent class. The method signature remains the same.
Polymorphism allows for co...read more
Self-Join is when a table is joined with itself, while Cross-Join is when every row of one table is joined with every row of another table.
Self-Join is used to combine rows from the same table based on a related column.
Cross-Join produces a Cartesian product of the two tables involved.
Self-Join example: SELECT e1.name, e2.name FROM employees e1, employees e2 WHERE e1.manager_id = e2.employee_id;
Cross-Join example: SELECT * FROM table1 CROSS JOIN table2;
Lambda expressions are a feature introduced in Java 8 to provide a concise way to represent anonymous functions.
Lambda expressions are used to provide implementation of functional interfaces.
They enable you to treat functionality as a method argument, or code as data.
They reduce the need for anonymous inner classes.
Syntax: (parameters) -> expression or (parameters) -> { statements; }
Example: (int a, int b) -> a + b
Lazy loading is a design pattern in Hibernate where data is loaded only when it is requested.
Lazy loading helps improve performance by loading data only when needed.
It is commonly used in Hibernate to delay the loading of associated objects until they are actually accessed.
Lazy loading can be configured at the entity level or at the collection level in Hibernate.
For example, if a parent entity has a collection of child entities, lazy loading can be used to load the child enti...read more
save() method is used to save an entity to the database, while saveOrUpdate() method is used to either save a new entity or update an existing one.
save() method always saves a new entity to the database, while saveOrUpdate() method checks if the entity already exists and updates it if so.
save() method does not check if the entity already exists in the database, it always saves a new entity.
saveOrUpdate() method first checks if the entity already exists in the database, if it ...read more
ACID properties in DBMS ensure data integrity and consistency in transactions.
ACID stands for Atomicity, Consistency, Isolation, and Durability.
Atomicity ensures that either all operations in a transaction are completed successfully or none are.
Consistency ensures that the database remains in a valid state before and after the transaction.
Isolation ensures that multiple transactions can run concurrently without affecting each other.
Durability ensures that once a transaction i...read more
Q25. If you project is going to end and you found a bug in the application then what actions will you take?
Upon discovering a bug near project completion, I would assess its impact, communicate with stakeholders, and prioritize a fix.
Assess the severity of the bug: Determine if it's a critical issue that affects functionality or a minor cosmetic issue.
Communicate with the team: Inform relevant stakeholders, including project managers and team members, about the bug.
Prioritize the fix: If the bug is critical, prioritize it for immediate resolution; if not, consider documenting it f...read more
Q26. Is java object oriented language or not ?
Yes, Java is an object-oriented language.
Java supports all the features of object-oriented programming such as encapsulation, inheritance, and polymorphism.
All code in Java is written inside classes, which are objects.
Java also has interfaces, which allow for multiple inheritance.
Example: Java's String class is an object that has methods and properties.
Example: Inheritance in Java allows a subclass to inherit properties and methods from a superclass.
Q27. Actuator,what is dependency injection, how to change imbeded server in spring boot,W.A.P permutation of string
Answering questions related to Actuator, Dependency Injection, changing embedded server in Spring Boot, and permutation of string.
Actuator is a Spring Boot feature that provides endpoints for monitoring and managing the application.
Dependency Injection is a design pattern that allows objects to be created with their dependencies injected from outside.
To change the embedded server in Spring Boot, you can exclude the default server dependency and add a new one.
Permutation of st...read more
SSL is a protocol used to secure communication over the internet by encrypting data transmitted between a client and server.
SSL stands for Secure Socket Layer
It ensures data integrity, authentication, and encryption for secure communication
SSL certificates are used to establish a secure connection between a client and server
Examples of websites using SSL include banking websites, e-commerce sites, and social media platforms
The merge() method of the Hibernate session is useful when you want to update the state of an object and persist it in the database.
Merge() method is used to update the state of a detached object and synchronize it with the database.
It is useful when you have an object in a detached state and want to make it persistent again.
Merge() method returns the persistent instance of the object, so you can continue working with it.
Example: session.merge(object);
Spring Boot offers basic annotations like @SpringBootApplication, @RestController, @Autowired, @Component, @RequestMapping, @Service, @Repository.
@SpringBootApplication - Used to mark the main class of a Spring Boot application.
@RestController - Used to define RESTful web services.
@Autowired - Used for automatic dependency injection.
@Component - Used to indicate a class is a Spring component.
@RequestMapping - Used to map web requests to specific handler methods.
@Service - Use...read more
ConcurrentHashMap is a thread-safe implementation of the Map interface in Java.
Uses separate locks for different buckets to allow multiple threads to read/write concurrently.
Provides better performance than synchronized HashMap for concurrent operations.
Supports full concurrency of retrievals and high expected concurrency for updates.
Example: ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
Garbage collector in Java is a built-in mechanism that automatically manages memory by reclaiming unused objects.
Garbage collector runs in the background to identify and remove objects that are no longer needed.
It helps in preventing memory leaks and optimizing memory usage.
Examples of garbage collectors in Java include Serial, Parallel, CMS, G1, and Z Garbage Collectors.
Q33. What is java and what is oops concepts and what is inheritance and what is method
Java is an object-oriented programming language. OOPs concepts include inheritance, encapsulation, polymorphism, and abstraction.
Java is a high-level programming language that is platform-independent.
OOPs concepts are the foundation of Java programming.
Inheritance is a mechanism in which one class acquires the properties and behaviors of another class.
A method is a collection of statements that perform a specific task.
Examples of OOPs concepts in Java include encapsulation, p...read more
Q34. What is java and what is method and what is oops concepts and what is method
Java is an object-oriented programming language. Method is a block of code that performs a specific task. OOPs concepts are principles of object-oriented programming.
Java is a high-level programming language that is platform-independent.
Method is a block of code that performs a specific task and can be called multiple times.
OOPs concepts include inheritance, encapsulation, polymorphism, and abstraction.
Inheritance allows a class to inherit properties and methods from another ...read more
Exceptions propagate in the code by being thrown from a method and caught by a higher-level method or the main method.
Exceptions are thrown using the 'throw' keyword in Java.
When an exception is thrown, the program looks for a 'catch' block to handle it.
If no catch block is found in the current method, the exception is propagated to the calling method.
This process continues until a catch block is found or the exception reaches the main method.
If the exception is not caught, t...read more
To create an immutable class in Hibernate, use final keyword for class, make fields private and provide only getters.
Use the final keyword for the class to prevent subclassing
Make fields private to restrict direct access
Provide only getters for the fields to ensure read-only access
Avoid providing setters or mutable methods
Routing in MVC is the process of mapping URLs to controller actions.
Routing is typically defined in a configuration file where URLs are mapped to specific controller actions.
Routes can include placeholders for dynamic parts of the URL, such as IDs or slugs.
The routing system matches incoming URLs to the defined routes and invokes the corresponding controller action.
Example: '/products/{id}' could route to the 'show' action in the 'ProductsController' with the ID parameter pas...read more
Q38. Which is springboot default server and How to use another server in springboot?
Spring Boot's default server is Tomcat, but you can easily switch to others like Jetty or Undertow.
Spring Boot uses Tomcat as the default embedded server.
To use Jetty, add the dependency: 'spring-boot-starter-jetty' in your pom.xml.
For Undertow, include 'spring-boot-starter-undertow' in your dependencies.
You can exclude Tomcat by adding 'exclude = {Tomcat.class}' in your @SpringBootApplication annotation.
Q39. What is the default port of springboot and How to change?
Spring Boot's default port is 8080, and it can be changed via application properties or command line arguments.
Default port: 8080.
Change via application.properties: server.port=9090.
Change via command line: java -jar app.jar --server.port=9090.
Change via YAML: server: port: 9090
UNIX commands are essential for navigating and managing files in a Unix-based operating system.
ls - list directory contents
cd - change directory
pwd - print working directory
cp - copy files or directories
rm - remove files or directories
Q41. Where should use for constructor injection?
Constructor injection should be used for mandatory dependencies.
Constructor injection is used to inject mandatory dependencies into a class.
It ensures that the class cannot be instantiated without the required dependencies.
It also makes the code more testable and maintainable.
Example: A Car class requires an Engine object to function. The Engine object is injected via constructor injection.
Constructor injection is preferred over setter injection as it ensures that the depende...read more
Q42. What are aggregate and terminal operations in java8 streams
Aggregate operations perform operations on a stream of elements, while terminal operations produce a result or side-effect.
Aggregate operations include map, filter, reduce, etc.
Terminal operations include forEach, collect, reduce, etc.
Example: stream.filter(x -> x > 5).map(x -> x * 2).forEach(System.out::println);
Q43. What is java and what is method and what is oops concepts
Java is a programming language. Method is a block of code that performs a specific task. OOPs is a programming paradigm.
Java is an object-oriented programming language used to develop applications and software.
A method is a block of code that performs a specific task and can be called by other parts of the program.
OOPs is a programming paradigm that focuses on objects and their interactions to solve problems.
OOPs concepts include encapsulation, inheritance, polymorphism, and ...read more
Q44. Which method can be used to check if a service is up or not?
Q45. Can we use try and finally without catch?
Yes, try and finally can be used without catch to handle exceptions.
try block is used to enclose the code that may throw an exception
finally block is used to execute code regardless of whether an exception is thrown or not
If catch block is not present, exceptions will not be caught and handled
Q46. How one microservices authenticate another microservice with JWT?
Microservices use JWT for secure authentication, enabling them to verify each other's identity without centralized control.
Microservices issue a JWT after user authentication, containing claims about the user.
The JWT is signed with a secret key, ensuring its integrity and authenticity.
When one microservice needs to call another, it includes the JWT in the request header.
The receiving microservice verifies the JWT using the same secret key to ensure it's valid.
If the JWT is va...read more
Piping in Unix/Linux is a method of connecting the output of one command to the input of another command.
Piping is done using the '|' symbol in Unix/Linux.
It allows for the output of one command to be used as the input for another command.
Multiple commands can be connected using piping to create complex operations.
Example: 'ls | grep .txt' will list all files in the current directory and then filter out only the ones with '.txt' extension.
Q48. Code in stream api - to find all the numbers less than 10 in a given array list
Using stream api to find numbers less than 10 in an array list
Use stream() method on the array list to create a stream of elements
Use filter() method with a lambda expression to filter out numbers less than 10
Collect the filtered elements using collect() method to get the result
Q49. Give an example of a java interface which uses a functional interface.
Hibernate caching is a mechanism used to improve performance by storing frequently accessed data in memory.
Hibernate caching reduces the number of database queries by storing frequently accessed data in memory.
There are different levels of caching in Hibernate, such as first-level cache and second-level cache.
First-level cache is enabled by default in Hibernate and is associated with the Session object.
Second-level cache is optional and can be configured to cache data across ...read more
Q51. What would you rate yourself in java on the scale of 1 to 10?
I would rate myself as an 8 in Java.
I have extensive experience in Java programming and have successfully completed multiple projects using Java.
I am familiar with various Java frameworks and libraries.
I have a strong understanding of object-oriented programming principles in Java.
I am comfortable working with Java's core features and APIs.
I continuously strive to improve my Java skills through self-learning and staying updated with the latest developments in the Java ecosyst...read more
Q52. How to set up a discovery server for microservices?
Thread starvation occurs when a thread is unable to access the CPU resources it needs to complete its task.
Occurs when a thread is constantly preempted by higher priority threads, preventing it from executing
Can also happen when a thread is waiting indefinitely for a resource that is being held by another thread
Can lead to performance degradation and inefficiency in multi-threaded applications
Dependency injection is a design pattern in which the dependencies of an object are provided externally rather than created within the object itself.
Dependency injection helps in achieving loose coupling between classes.
It allows for easier testing by providing mock dependencies.
There are three types of dependency injection: constructor injection, setter injection, and interface injection.
Q55. Explain project . How encapsulation and abstraction is used in your project
The project is a web application for managing inventory and sales of a retail store.
Encapsulation is used to hide the internal implementation details of classes and only expose necessary methods and properties.
Abstraction is used to define a common interface for interacting with different types of inventory items, such as products and services.
For example, the Product class encapsulates details like name, price, and quantity, while the InventoryManager class abstracts the ope...read more
Q56. String s1=new String(null); what is the answer
The code will throw a NullPointerException.
The code tries to create a new String object with a null value, which is not allowed.
The constructor of String class does not accept null as a parameter.
The code will throw a NullPointerException at runtime.
Q57. How would you externalize a microservice?
Externalizing a microservice involves separating its configuration and dependencies from the codebase for flexibility and scalability.
Use environment variables to store configuration settings, e.g., DATABASE_URL.
Implement a configuration server (e.g., Spring Cloud Config) to manage external configurations.
Utilize Docker and Kubernetes for containerization and orchestration, allowing easy deployment and scaling.
Adopt API gateways to manage service interactions and externalize ...read more
Q58. Write a functional interface. Refer it to a Lamda Expression. Show it practically while explaining each step
A functional interface is a single abstract method interface. It can be referred to using a lambda expression.
Functional interfaces have only one abstract method
Lambda expressions can be used to implement functional interfaces
Lambda expressions provide a concise way to write anonymous functions
Functional interfaces can be used as method parameters or return types
Q59. What is HashMap? While Interating through it is it mutable?
HashMap is a data structure in Java that stores key-value pairs. It is mutable while iterating through it.
HashMap is part of the Java Collections Framework.
It allows null values and at most one null key.
It provides constant-time performance for basic operations like get and put.
While iterating through a HashMap, it is mutable and can throw ConcurrentModificationException if modified.
To avoid this, use an Iterator or ConcurrentHashMap.
Q60. what is collection and collections, what is collection framework?
Collection is a group of objects, Collections is a utility class, Collection framework is a set of interfaces and classes for handling collections.
Collection is an interface in Java that represents a group of objects known as elements.
Collections is a utility class in Java that contains static methods for operating on collections.
Collection framework is a set of interfaces and classes in Java that provides an architecture to store and manipulate groups of objects.
Examples: Li...read more
Q61. What are the various annotations used in SpringBoot (explain)
Various annotations used in SpringBoot
1. @SpringBootApplication: Marks the main class of a Spring Boot application
2. @RestController: Marks a class as a RESTful controller
3. @RequestMapping: Maps HTTP requests to handler methods
4. @Autowired: Injects dependencies automatically
5. @Component: Marks a class as a Spring component
6. @Service: Marks a class as a service component
7. @Repository: Marks a class as a repository component
8. @Configuration: Marks a class as a source of b...read more
Q62. What are Java Generics, Collections, wrapper classes?
Java Generics are used to create classes, interfaces, and methods that operate on objects of specified types. Collections are data structures to store and manipulate groups of objects. Wrapper classes provide a way to use primitive data types as objects.
Java Generics allow for type-safe operations on objects of specified types. Example: List<String> list = new ArrayList<>();
Collections provide data structures like List, Set, and Map to store and manipulate groups of objects. ...read more
Q63. How to inject a specific bean of the same object?
Q64. Explain Final,Finally,Finalize() in Java?
Final, Finally, Finalize() are keywords in Java used for different purposes.
Final is used to declare a variable as constant.
Finally is used to execute a block of code after try-catch block.
Finalize() is a method used for garbage collection.
Final can be used with classes, methods, and variables.
Finally block is always executed whether an exception is thrown or not.
Q65. Expalin the flow of a Rest API call from frontend to backend and response from backend to frontend.
Q66. what is the difference between string and stringbuffer, difference between throw and throws
String is immutable while StringBuffer is mutable. throw is used to explicitly throw an exception, throws is used in method signature to declare exceptions that can be thrown.
String is immutable, meaning its value cannot be changed once it is created. StringBuffer is mutable, meaning its value can be changed.
StringBuffer is synchronized, making it thread-safe. String is not synchronized.
throw keyword is used to explicitly throw an exception in a method. throws keyword is used...read more
Q67. What is difference between Java and C, explain features of java
Java is a high-level programming language, while C is a low-level language. Java is platform-independent and has automatic memory management.
Java is an object-oriented language, while C is a procedural language.
Java uses a virtual machine (JVM) for execution, while C directly compiles to machine code.
Java has built-in garbage collection, while C requires manual memory management.
Java supports multithreading and exception handling, while C has limited support for these feature...read more
Q68. 1.tell me about class loader in java and how it works? 2.Types of operators in java. etc
Class loader in Java is responsible for loading classes into memory at runtime. It follows a delegation hierarchy to find and load classes.
Class loader loads classes into memory dynamically at runtime
It follows a delegation hierarchy to find and load classes
Types of operators in Java include arithmetic, bitwise, logical, assignment, etc.
Q69. What is the jQuery ajax GET request syntax?
The jQuery ajax GET request syntax is used to send an HTTP GET request to a server and retrieve data.
Use the $.ajax() method with the 'type' parameter set to 'GET'
Specify the URL of the server endpoint as the 'url' parameter
Handle the response using the 'success' callback function
Optionally, pass data to the server using the 'data' parameter
Q70. Define Filters and Segmentation in Spring Security.
Filters and Segmentation in Spring Security manage request processing and user access control.
Filters are components that intercept requests and responses in the Spring Security filter chain.
Examples of filters include UsernamePasswordAuthenticationFilter and BasicAuthenticationFilter.
Segmentation refers to dividing users into roles or groups for access control.
Using @PreAuthorize or @Secured annotations allows method-level security based on user roles.
Q71. What are profiles and how to use them?
Profiles in Java are configurations that define specific settings for different environments.
Profiles allow you to customize application behavior based on the environment (e.g., development, testing, production).
You can define profiles in the application.properties or application.yml file using 'spring.profiles.active'.
Example: 'spring.profiles.active=dev' activates the 'dev' profile, loading specific configurations.
Profiles can be used to manage different database connection...read more
Q72. What is an optional class and its use?
The Optional class is a container that may or may not hold a non-null value, helping to avoid NullPointerExceptions.
Introduced in Java 8 to represent optional values.
Helps in avoiding null checks and NullPointerExceptions.
Methods include isPresent(), ifPresent(), orElse(), and orElseGet().
Example: Optional<String> name = Optional.ofNullable(getName());
Example: name.ifPresent(n -> System.out.println(n));
Q73. Find the duplicate element in a given array using Java 8 features.
Find duplicate element in array using Java 8 features.
Convert array to stream using Arrays.stream()
Use Collectors.groupingBy() to group elements by their occurrence
Filter the grouped elements to find duplicates
Q74. What is Functional Interface? What is Flat Map? What is Method Reference? What is stream API
Functional Interface is an interface with only one abstract method. Flat Map is used to flatten nested collections. Method Reference is a shorthand notation for lambda expressions. Stream API is used to process collections of objects.
Functional Interface is an interface with a single abstract method, such as Runnable or Comparator.
Flat Map is a method in Java that is used to flatten nested collections, like List<List<Integer>> to List<Integer>.
Method Reference is a shorthand ...read more
Q75. What is the use of @Primary annotation?
The @Primary annotation in Spring indicates a preferred bean when multiple candidates are available for autowiring.
@Primary is used in Spring Framework for dependency injection.
It helps resolve ambiguity when multiple beans of the same type exist.
Example: If you have two beans of type 'DataSource', marking one with @Primary will make it the default choice.
It can be combined with @Qualifier for more specific bean selection.
Q76. have you worked on spring security then explain ?
Yes, I have worked on Spring Security. It is a powerful and customizable authentication and access control framework for Java applications.
Implemented authentication and authorization using Spring Security annotations like @Secured, @PreAuthorize, @PostAuthorize
Configured security settings in XML or Java configuration files
Used Spring Security filters for protecting URLs, CSRF protection, session management, etc.
Integrated with various authentication providers like LDAP, OAut...read more
Q77. Prerequisites: Payment gateway If your order fails and payment has been deducted, how do you manage this situation.
In case of order failure with payment deducted, refund the payment and investigate the issue.
Initiate refund process for the deducted payment
Investigate the reason for the order failure
Communicate with the customer about the issue and resolution
Ensure the payment gateway is functioning correctly to prevent future occurrences
Q78. Why java is not 100% object oriented? Explain in detail?
Java is not 100% object oriented because it supports primitive data types and static methods.
Java supports primitive data types like int, float, and boolean which are not objects.
Static methods in Java belong to the class itself and not to any specific object.
Java allows procedural programming constructs like static variables and methods.
Inheritance in Java is limited to single inheritance for classes, unlike pure object-oriented languages like Smalltalk.
Q79. What are @annotations in springboot? explain about @springBootApplication
Annotations in Spring Boot are used to provide metadata about the code. @SpringBootApplication is a meta-annotation that combines @Configuration, @EnableAutoConfiguration, and @ComponentScan.
Annotations in Spring Boot are used to simplify configuration and reduce boilerplate code.
@SpringBootApplication is a meta-annotation that enables the auto-configuration feature in Spring Boot.
It combines @Configuration, @EnableAutoConfiguration, and @ComponentScan annotations.
Example: @S...read more
Q80. Write code to put all the zeroes of an array to the end
Move all zeroes in an array to the end without changing the order of other elements.
Iterate through the array and keep track of the index where non-zero elements should be placed.
After the iteration, fill the remaining positions with zeroes.
Q81. What are the different bean scopes in Spring
The different bean scopes in Spring are singleton, prototype, request, session, and application.
Singleton scope creates a single instance of a bean per Spring IoC container.
Prototype scope creates a new instance of a bean every time it is requested.
Request scope creates a new instance of a bean for each HTTP request.
Session scope creates a new instance of a bean for each HTTP session.
Application scope creates a single instance of a bean per ServletContext.
Q82. WAJP to establish a JDBC connection and fetch results from a database and print those results.
Establish a JDBC connection and fetch results from a database using Java.
Import the necessary JDBC packages
Load and register the JDBC driver
Establish a connection to the database
Create a statement object
Execute a query to fetch results
Iterate over the result set and print the results
Close the result set, statement, and connection
Q83. What is static variables?
Static variables are variables that belong to the class itself, rather than an instance of the class.
Static variables are declared using the 'static' keyword.
They are shared among all instances of the class.
They can be accessed without creating an object of the class.
Static variables are initialized only once, at the start of the program.
They are useful for storing data that is common to all instances of a class.
Q84. Coding: Sort list of student details using mark.
Sort list of student details by mark.
Create a custom class Student with attributes like name, mark.
Implement Comparator interface to sort by mark.
Use Collections.sort() method to sort the list of students.
Q85. How can you write custom exception in Java?
To write a custom exception in Java, create a new class that extends Exception or a subclass of Exception.
Create a new class that extends Exception or a subclass of Exception.
Add a constructor to the custom exception class to pass a message to the superclass constructor.
Throw the custom exception using the 'throw' keyword in your code.
Handle the custom exception using try-catch blocks or propagate it up the call stack.
Q86. What is a Functional Interface?
A Functional Interface is an interface with a single abstract method, enabling lambda expressions in Java.
Functional interfaces are used primarily with lambda expressions.
They can have multiple default or static methods but only one abstract method.
Common examples include Runnable, Callable, and Comparator.
You can create your own functional interfaces using the @FunctionalInterface annotation.
Q87. What is transient keyword in Java?
The transient keyword in Java is used to indicate that a variable should not be serialized.
Variables marked as transient are not included in the serialization process
Transient variables are not saved when an object is serialized and are set to their default values when the object is deserialized
Useful for excluding sensitive or unnecessary data from being serialized
Q88. What is agile?How it is used in your project?
Agile is a project management methodology that emphasizes flexibility, collaboration, and iterative development.
Agile involves breaking down projects into small, manageable tasks called user stories.
It promotes frequent communication and collaboration among team members.
Iterations, or sprints, are used to deliver working software incrementally.
Adaptability and responding to change are key principles of agile.
Examples of agile methodologies include Scrum, Kanban, and Extreme P...read more
Q89. Write a code to implement Runnable using lambda.
Implementing Runnable using lambda expressions simplifies thread creation in Java.
Lambda expressions provide a clear and concise way to represent a functional interface.
Runnable is a functional interface with a single abstract method: run().
Example of Runnable using lambda: Runnable task = () -> System.out.println('Running in a thread');
To start a thread: new Thread(task).start();
Q90. java code to explain exceptions using throws and throw
Using throws and throw in Java to handle exceptions
Use 'throws' to declare an exception in a method signature
Use 'throw' to manually throw an exception within a method
Example: public void divide(int a, int b) throws ArithmeticException { if(b == 0) throw new ArithmeticException(); }
Q91. what is oops conecpts and give example?
OOPs concepts refer to Object-Oriented Programming principles like inheritance, encapsulation, polymorphism, and abstraction.
Inheritance: Allows a class to inherit properties and behaviors from another class. Example: class Dog extends Animal.
Encapsulation: Bundling data and methods that operate on the data into a single unit. Example: private variables with public getter and setter methods.
Polymorphism: Ability to present the same interface for different data types. Example:...read more
Q92. What are functional Interfaces?
Functional interfaces are interfaces with only one abstract method, used for functional programming in Java.
Functional interfaces can have multiple default or static methods, but only one abstract method.
They are used in lambda expressions and method references for functional programming.
Examples include java.lang.Runnable, java.util.Comparator, and java.util.function.Function.
Q93. Write a program to find the missing element from the array.
Program to find missing element from array of strings
Iterate through the array and store elements in a HashSet
Iterate through another array and check if each element is present in the HashSet
Return the element that is not present in the HashSet
Q94. What are Java8 streams
Java8 streams are a sequence of elements that support functional-style operations.
Streams allow for processing sequences of elements in a functional way
They can be created from collections, arrays, or other sources
Operations like map, filter, reduce can be applied to streams
Streams are lazy, meaning they only process elements when needed
Example: List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); Stream<String> stream = names.stream();
Q95. What is String, collection, multithreading
String is a sequence of characters. Collection is a group of objects. Multithreading is executing multiple threads simultaneously.
String is an immutable class in Java.
Collection is an interface that provides a way to store and manipulate groups of objects.
Multithreading is used to improve the performance of an application by executing multiple threads simultaneously.
Example of collection: ArrayList, LinkedList, HashSet, TreeSet.
Example of multithreading: creating and running ...read more
Q96. How to manage during strict deadlines
Prioritize tasks, break down work into smaller chunks, communicate with team, utilize time management techniques
Prioritize tasks based on importance and urgency
Break down work into smaller, manageable chunks to make progress
Communicate with team members to ensure everyone is on the same page
Utilize time management techniques such as Pomodoro technique or Agile methodologies
Q97. Difference between list and set
List is an ordered collection that allows duplicate elements, while Set is an unordered collection that does not allow duplicates.
List maintains the insertion order of elements, while Set does not guarantee any specific order.
List allows duplicate elements, while Set does not allow duplicates.
Examples of List implementations in Java are ArrayList and LinkedList, while examples of Set implementations are HashSet and TreeSet.
Q98. Can we run Java program without main
No, a Java program cannot be run without a main method.
The main method is the entry point of a Java program, without it the program cannot be executed.
The JVM looks for the main method to start the execution of the program.
Attempting to run a Java program without a main method will result in a compilation error.
Q99. Annotations in @springbootApplication
Annotations in @SpringBootApplication are used to configure the Spring Boot application.
Annotations like @SpringBootApplication are used to enable auto-configuration and component scanning in a Spring Boot application.
Other commonly used annotations include @RestController, @Service, @Repository, and @Component for defining different types of Spring beans.
Annotations like @Autowired are used for dependency injection in Spring applications.
Annotations like @RequestMapping are ...read more
Q100. Is Java pass by value or by reference
Java is pass by value
Java is pass by value, meaning a copy of the variable is passed to a method
Changes made to the copy inside the method do not affect the original variable
However, if the variable is an object reference, the reference is passed by value
Top HR Questions asked in UNii Engineering Consultancy
Interview Process at UNii Engineering Consultancy
Top Java Developer Interview Questions from Similar Companies
Reviews
Interviews
Salaries
Users/Month