Java Developer
1500+ Java Developer Interview Questions and Answers
Popular Companies
Q101. How to create Thread in Java and What are the ways?
Threads in Java allow concurrent execution of multiple tasks. They can be created in multiple ways.
Using the Thread class
Implementing the Runnable interface
Using the Executor framework
Using the Callable interface with ExecutorService
Q102. In Tr what is exception handling.oops, difference between abstraction and encapsulation about project.
The question is about exception handling, OOPs, and the difference between abstraction and encapsulation in a project.
Exception handling is a mechanism to handle runtime errors and prevent program termination.
Abstraction is the process of hiding implementation details and showing only necessary information to the user.
Encapsulation is the process of binding data and methods together in a single unit.
In a project, abstraction can be achieved by using interfaces and abstract cl...read more
Multithreading in Java allows for concurrent execution of multiple tasks, improving performance and responsiveness.
1. Improved performance by utilizing multiple CPU cores efficiently.
2. Enhanced responsiveness as tasks can run concurrently without blocking each other.
3. Simplified coding for complex tasks by breaking them into smaller threads.
4. Facilitates better resource utilization and scalability.
5. Examples: parallel processing in data analysis, handling multiple client ...read more
Constructor injection passes dependencies through a class constructor, while setter injection uses setter methods.
Constructor injection is done by passing dependencies as parameters to the constructor.
Setter injection involves calling setter methods to set the dependencies after the object is created.
Constructor injection ensures that all required dependencies are provided at the time of object creation.
Setter injection allows for optional dependencies to be set after the obj...read more
Q105. What is an object in java ?
An object in Java is an instance of a class that encapsulates data and behavior.
Objects have state and behavior
They are created from classes
They can be used to represent real-world entities or concepts
Objects can interact with each other through method calls
Q106. 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
Share interview questions and help millions of jobseekers 🌟
Q107. 1) How do you achieve concurrency in your current job, and write code for it? 2) Write code for Rest API using Springboot, need to write Entity, Service, Repository, and Controller classes? 3)Volatile keywords,...
read moreAnswers to common Java Developer interview questions
1) Concurrency is achieved using multithreading in Java. Use threads, executors, or synchronized blocks. Example: using ExecutorService to run multiple tasks concurrently.
2) Rest API in Springboot: Entity class defines database table, Service class contains business logic, Repository class interacts with database, Controller class handles HTTP requests.
3) Volatile keyword provides visibility guarantee but does not support sy...read more
Q108. Write a Java program using multithreading to print below output: n=10 Thread-1 : 1 Thread-2 : 2 Thread-3 : 3 Thread-1 : 4 Thread-2 : 6 . . Thread-1 : 10
A Java program using multithreading to print numbers from 1 to 10 in a specific pattern.
Create three threads and assign them to print numbers in a specific pattern
Use synchronization to ensure the correct order of printing
Use a loop to iterate from 1 to 10 and assign the numbers to the threads
Print the thread name and the assigned number in the desired format
Java Developer Jobs
Q109. 5. Write a program to get the middle of the linked list in a single iteration? Ans - Two pointers , slow fast
Program to get the middle of a linked list in a single iteration using two pointers.
Use two pointers, slow and fast, to traverse the linked list
Move slow pointer one step at a time and fast pointer two steps at a time
When fast pointer reaches the end, slow pointer will be at the middle node
Q110. 8. Singleton in java . And how singleton can be broken
Singleton is a design pattern that restricts the instantiation of a class to one object.
Singleton pattern is used when we need to ensure that only one instance of a class is created and used throughout the application.
To implement Singleton, we make the constructor private and provide a static method to get the instance of the class.
Singleton can be broken by using reflection, serialization, and cloning.
Reflection can be used to access the private constructor and create a new...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.
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 a functional interface.
They enable you to treat functionality as a method argument, or code as data.
Syntax of lambda expressions is (argument) -> (body).
Example: (int a, int b) -> a + b
Q113. Difference between List and Set? which one to prefer in which requirements and why ?
List allows duplicates and maintains insertion order, Set doesn't allow duplicates and doesn't maintain order.
Use List when duplicates are allowed and order is important
Use Set when duplicates are not allowed and order is not important
List examples: ArrayList, LinkedList
Set examples: HashSet, TreeSet
Q114. how to remove duplicated form from array list?
To remove duplicates from an ArrayList of strings, use a HashSet to store unique elements.
Create a HashSet and add all elements from the ArrayList to it.
Create a new ArrayList and add all elements from the HashSet to it.
The new ArrayList will contain only unique elements.
Q115. What is the differnce between Interface and Class?
Interface defines a contract for behavior while class is an implementation of behavior.
Interface only contains method signatures while class contains method implementations.
A class can only extend one class but can implement multiple interfaces.
Interfaces are used for achieving abstraction and loose coupling.
Classes are used for encapsulation and code reusability.
Example: Comparable interface defines a contract for objects that can be compared while String class implements th...read more
To create an immutable class in Java, make the class final, make all fields private and final, provide only getters, and don't provide setters.
Make the class final to prevent inheritance.
Make all fields private and final to prevent modification.
Provide only getters to access the fields.
Don't provide setters to modify the fields.
Entity instances can be in new, managed, detached, or removed states.
New state: when an entity is first created but not yet associated with a persistence context.
Managed state: when an entity is being managed by a persistence context and any changes made to it will be tracked.
Detached state: when an entity was previously managed but is no longer associated with a persistence context.
Removed state: when an entity is marked for removal from the database.
Q118. What is the difference between Abstract class and Interface in terms of Java 8?
Abstract class can have implemented methods while interface cannot.
Abstract class can have constructors while interface cannot
Abstract class can have instance variables while interface cannot
A class can implement multiple interfaces but can only extend one abstract class
Java 8 introduced default and static methods in interfaces
MongoDB is a NoSQL database while MySQL is a relational database management system.
MongoDB is schema-less, allowing for flexible data models, while MySQL requires a predefined schema.
MongoDB uses a document-based data model, storing data in JSON-like documents, while MySQL uses tables with rows and columns.
MongoDB is better suited for handling unstructured or semi-structured data, while MySQL is ideal for structured data with complex relationships.
MongoDB is horizontally scal...read more
Q120. 14. What are different types of Access Modifiers in Java?
Access modifiers in Java are used to set the accessibility of classes, methods, and variables.
There are four types of access modifiers in Java: public, private, protected, and default.
Public: accessible from anywhere in the program.
Private: accessible only within the same class.
Protected: accessible within the same class, same package, and subclasses.
Default: accessible within the same package only.
Q121. Can we use try block without catch block?
Yes, we can use try block without catch block to handle exceptions using finally block.
Try block can be used without catch block if there is a finally block to handle exceptions.
Finally block is executed whether an exception is thrown or not.
Example: try { // code that may throw exception } finally { // code to be executed regardless of exception }
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;
Q123. 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
Q124. 1. How to connect 2 DBs from spring boot application
To connect 2 DBs from a Spring Boot application, configure multiple data sources and use JdbcTemplate or EntityManager for each DB.
Configure multiple data sources in the application.properties file
Create separate configuration classes for each data source
Use JdbcTemplate or EntityManager to interact with each DB
Specify the appropriate data source in the repository or service classes
Q125. Coding Question - Find 2nd largest element in array with least time complexity
Find the 2nd largest element in an array with the least time complexity.
Sort the array in descending order and return the element at index 1.
Initialize two variables to keep track of the largest and second largest elements.
Iterate through the array and update the variables accordingly.
Return the second largest element.
Q126. How to start spring boot application even though a class having error
To start Spring Boot app with class error, disable strict classpath checking.
Add 'spring.main.lazy-initialization=true' to application.properties.
Disable strict classpath checking by adding 'spring.main.allow-bean-definition-overriding=true'.
Use 'spring.main.banner-mode=off' to disable banner.
Use 'spring.main.web-environment=false' to disable web environment.
Use 'spring.main.headless=true' to enable headless mode.
Q127. how to use synchronization in java
Synchronization in Java is used to control access to shared resources by multiple threads.
Synchronization can be achieved using synchronized keyword or locks.
It ensures that only one thread can access the shared resource at a time.
Synchronization can be applied to methods or blocks of code.
Example: synchronized void method() { //code }
Example: synchronized(obj) { //code }
Design patterns in Java provide reusable solutions to common problems, improving code quality and maintainability.
Promotes code reusability by providing proven solutions to common design problems
Improves code maintainability by following established best practices
Enhances code readability by providing a common language for developers to communicate design ideas
Helps in creating scalable and flexible software architecture
Examples include Singleton, Factory, Observer, and Strat...read more
Q129. What is System.out.println?
System.out.println is a Java statement used to print output to the console.
System is a class in Java's core library.
out is a static member of the System class.
println is a method of the PrintStream class.
It is used to print output to the console.
It adds a newline character at the end of the output.
Q130. Creating multiple methods in a class with a same name and different arguments. The argument must be different type and length
Method overloading allows creating multiple methods with the same name but different arguments.
Method signature must differ in number, type, or order of parameters
Return type can be different but not the only difference
Example: public void print(int num), public void print(String str), public void print(int[] arr)
Overloading improves code readability and reusability
Q131. what is java? why u choose it ? what is opps? is it fully object oriented ?collections? multi threading?
Java is a popular programming language known for its portability, security, and object-oriented features.
Java is platform-independent and can run on any device with a JVM installed.
It is widely used for developing web, mobile, and enterprise applications.
Java follows the OOPS concept and supports encapsulation, inheritance, and polymorphism.
Collections in Java are used to store and manipulate groups of objects.
Multi-threading allows multiple threads to run concurrently, impro...read more
Q132. 12. How to switch from one branch to other in git?
To switch from one branch to another in git, use the 'git checkout' command.
Use 'git checkout' followed by the name of the branch you want to switch to.
Make sure to commit or stash any changes before switching branches.
Example: 'git checkout new-branch'
Q133. 2. How do you secure your APIs?
Securing APIs involves implementing authentication, authorization, encryption, and input validation.
Implement authentication mechanisms like OAuth, JWT, or API keys
Use authorization to control access to APIs based on user roles and permissions
Encrypt sensitive data transmitted over the network using HTTPS
Validate and sanitize input to prevent common security vulnerabilities like SQL injection or cross-site scripting (XSS)
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
The final keyword in Java is used to restrict the modification of variables, methods, and classes.
Final variable: Once assigned, the value of a final variable cannot be changed.
Final method: A final method cannot be overridden by subclasses.
Final class: A final class cannot be extended.
Q136. Why Java Strings are immutable in nature?
Java Strings are immutable to ensure data integrity and security.
Immutable strings prevent accidental modification of data.
String pooling optimizes memory usage by reusing existing strings.
Immutable strings are thread-safe, simplifying concurrent programming.
String immutability allows for efficient caching and hashing.
Immutable strings enable safe sharing of string references.
Q137. 7. What if i write component in place of service ?
Using component instead of service may cause confusion and errors in the code.
Components and services are two different concepts in Java development.
Components are used for UI elements while services are used for business logic.
Using component instead of service may lead to errors in the code and confusion for other developers.
For example, if a component is used instead of a service for business logic, it may not have the necessary methods or functionality.
It is important to ...read more
Q138. Stream API how to use over the collection
Stream API is used to perform operations on collections in a functional programming style.
Stream API provides a set of methods to perform operations on collections such as filtering, mapping, and reducing.
It allows for concise and readable code by using lambda expressions.
Stream API supports parallel processing for improved performance.
Examples: stream.filter(x -> x > 5), stream.map(x -> x * 2), stream.reduce(0, (x, y) -> x + y)
Java is considered object-oriented because it supports the four main principles of OOP: encapsulation, inheritance, polymorphism, and abstraction.
Java allows for the creation of classes and objects, which encapsulate data and behavior together.
Inheritance is supported in Java, allowing classes to inherit attributes and methods from other classes.
Polymorphism in Java allows objects to be treated as instances of their parent class, enabling flexibility in programming.
Abstractio...read more
Q140. 3. What is difference between Abstract class and Interface.
Abstract class can have implementation while interface cannot. A class can implement multiple interfaces but can only extend one abstract class.
Abstract class can have constructors while interface cannot.
Abstract class can have instance variables while interface cannot.
Abstract class can have non-abstract methods while interface can only have abstract methods.
A class can implement multiple interfaces but can only extend one abstract class.
Abstract classes are used when there ...read more
Q141. 5. What is difference between composition and inheritance
Composition is a way to combine objects to create complex structures, while inheritance is a way to create new classes based on existing ones.
Composition is a 'has-a' relationship, where an object contains other objects as its parts.
Inheritance is an 'is-a' relationship, where a subclass inherits properties and behaviors from its superclass.
Composition allows for greater flexibility and modularity in design, as objects can be easily swapped out or added.
Inheritance can lead t...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
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
Q144. Write a code of prime numbers 1 to 100 and write sql query.
Code for prime numbers 1 to 100 and SQL query.
Use a loop to iterate through numbers 1 to 100.
For each number, check if it is divisible by any number from 2 to itself-1.
If not divisible, it is a prime number.
SQL query: SELECT * FROM table_name WHERE number_column >= 1 AND number_column <= 100 AND is_prime = true;
The Java Executor Framework provides a way to manage and control the execution of tasks in a multithreaded environment.
Allows for easy management of thread pools, reducing overhead of creating new threads for each task.
Provides a way to schedule tasks for execution at a specific time or with a delay.
Supports task cancellation and interruption.
Facilitates handling of task dependencies and coordination between tasks.
Offers better control over thread execution, such as setting t...read more
Types of advice in Spring AOP include before, after, around, after-returning, and after-throwing.
Before advice: Executed before the method invocation.
After advice: Executed after the method invocation, regardless of its outcome.
Around advice: Wraps around the method invocation, allowing for custom behavior before and after.
After-returning advice: Executed after the method successfully returns a value.
After-throwing advice: Executed after the method throws an exception.
Dependency Injection is a design pattern in Spring framework where the objects are provided with their dependencies.
In Dependency Injection, the dependencies of an object are injected into it rather than the object creating them itself.
This helps in achieving loose coupling between classes and makes the code more maintainable and testable.
Spring framework provides various ways to implement Dependency Injection such as constructor injection, setter injection, and field injecti...read more
Q148. Will finally block execute if try and catch have return statement?
Yes, finally block will execute even if try and catch have return statement.
The finally block is always executed regardless of whether an exception is thrown or not.
The return statement in try or catch block will be executed before the finally block.
Finally block is commonly used to release resources or perform cleanup operations.
Q149. 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.
Q150. What is the difference between JDK, JRE, and JVM?
JDK is a development kit, JRE is a runtime environment, and JVM is a virtual machine for running Java programs.
JDK (Java Development Kit) is a software development kit used for developing Java applications. It includes JRE, compiler, debugger, and other tools.
JRE (Java Runtime Environment) is a software package that provides the libraries, Java Virtual Machine (JVM), and other components necessary for running Java applications.
JVM (Java Virtual Machine) is an abstract machine...read more
Interview Questions of Similar Designations
Top Interview Questions for Java Developer Related Skills
Interview experiences of popular companies
Calculate your in-hand salary
Confused about how your in-hand salary is calculated? Enter your annual salary (CTC) and get your in-hand salary
Reviews
Interviews
Salaries
Users/Month