Experiencia de Java en Entrevistas
Experiencia de Java en Entrevistas
11. What is the difference between shallow copy and deep copy?
Shallow Copy: Copies only the reference to the object, not the actual object.
Deep Copy: Copies the object and its nested objects.
Practical Implementation
Lambda Expressions
Example:
Example:
@FunctionalInterface
interface Calculator {
int add(int a, int b);
}
Stream API
6. What is the Stream API?
A powerful feature to process collections of data in a functional style.
Example:
8. How can you filter a list of numbers to get only even numbers using
Stream?
Example:
Optional Class
9. What is the Optional class in Java 8?
A container object to handle null values gracefully and avoid
NullPointerException .
11. What improvements were made to the Date and Time API in Java 8?
Introduced java.time package for immutable and thread-safe date/time handling.
Classes include LocalDate , LocalTime , LocalDateTime , ZonedDateTime .
12. How do you get the current date and time in Java 8?
Example:
Example:
interface MyInterface {
default void display() {
System.out.println("Default Method");
}
}
Example:
interface MyInterface {
static void print() {
System.out.println("Static Method");
}
}
MyInterface.print();
Miscellaneous
15. What is the difference between Collection API and Stream API?
Collection API: Stores data and allows operations on stored data.
Stream API: Focuses on processing data, not storing it.
Example:
Sealed Classes
2. What are Sealed Classes in Java 17?
Sealed classes allow the developer to restrict which classes can extend or
implement them.
Use the sealed , non-sealed , and permits keywords.
Example:
Example:
Stronger Encapsulation
Example:
12. What improvements were made to random number generation in Java 17?
Introduced new interfaces ( RandomGenerator , RandomGeneratorFactory ).
Added methods for stream-based generation.
Example:
Example:
Miscellaneous
16. How does Java 17 support sealed and non-sealed keywords?
sealed : Restricts the inheritance of a class.
non-sealed : Allows unrestricted inheritance for a subclass of a sealed class.
17. What is the lifecycle of a long-term support (LTS) release like Java
17?
Java 17 will receive updates and security patches for several years (typically
8 years as an LTS version).
java -XX:StartFlightRecording=name=MyRecording,duration=60s,filename=recording.jfr -
jar MyApp.jar
5. What is HQL?
Hibernate Query Language is an object-oriented query language similar to SQL
but works with objects instead of tables.
Example:
Example:
@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "name")
private String name;
}
JPA Questions
11. What is JPA?
Java Persistence API is a specification for ORM tools. Hibernate is one of its
implementations.
Example (persistence.xml):
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence">
<persistence-unit name="myPersistenceUnit">
<class>com.example.Employee</class>
<properties>
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/test" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="password" />
</properties>
</persistence-unit>
</persistence>
Example:
Example:
@Entity
public class Employee {
@PrePersist
public void prePersist() {
System.out.println("Before persisting the entity");
}
}
Example:
20. What are the strategies for primary key generation in JPA?
AUTO: JPA chooses the strategy based on the database.
IDENTITY: Uses database identity column.
SEQUENCE: Uses a database sequence.
TABLE: Uses a table to simulate a sequence.
Example:
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
Example:
@Component
public class Service {
private Repository repository;
@Autowired
public Service(Repository repository) {
this.repository = repository;
}
}
Example:
@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
Example:
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example..*(..))")
public void logBefore() {
System.out.println("Method execution started");
}
}
Example:
@Transactional
public void transferMoney(Account from, Account to, double amount) {
from.debit(amount);
to.credit(amount);
}
Example:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
http://localhost:8080/actuator/health
Example (application.properties):
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
Example:
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
}
Example:
server.port=8081
Example:
@Profile("dev")
@Configuration
public class DevConfig {
// Development-specific beans
}
Example:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleNotFound(ResourceNotFoundException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
}
@Configuration
@EnableBatchProcessing
public class BatchConfig {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Bean
public Job job(Step step) {
return jobBuilderFactory.get("myJob")
.start(step)
.build();
}
@Bean
public Step step(ItemReader<String> reader, ItemProcessor<String, String>
processor, ItemWriter<String> writer) {
return stepBuilderFactory.get("myStep")
.<String, String>chunk(10)
.reader(reader)
.processor(processor)
.writer(writer)
.build();
}
}
@Bean
public ItemReader<String> reader() {
return new FlatFileItemReaderBuilder<String>()
.name("fileReader")
.resource(new FileSystemResource("input.txt"))
.lineMapper((line, lineNumber) -> line)
.build();
}
Example:
@Bean
public ItemProcessor<String, String> processor() {
return item -> item.toUpperCase();
}
Example:
@Bean
public ItemWriter<String> writer() {
return items -> items.forEach(System.out::println);
}
Advanced Concepts
11. What is chunk processing in Spring Batch?
Divides the processing into chunks where a fixed number of items are read,
processed, and written as a unit.
Example:
stepBuilderFactory.get("step")
.<String, String>chunk(10)
.reader(reader())
.processor(processor())
.writer(writer())
.build();
Example:
@Bean
public Step partitionedStep(Step step) {
return stepBuilderFactory.get("partitionedStep")
.partitioner("step", new SimplePartitioner())
.step(step)
.build();
}
Example:
stepBuilderFactory.get("step")
.<String, String>chunk(10)
.reader(reader())
.processor(processor())
.writer(writer())
.faultTolerant()
.skip(Exception.class)
.skipLimit(5)
.build();
Example:
stepBuilderFactory.get("step")
.<String, String>chunk(10)
.reader(reader())
.processor(processor())
.writer(writer())
.faultTolerant()
.retry(Exception.class)
.retryLimit(3)
.build();
Spring Batch Integration
15. How do you integrate Spring Batch with Spring Boot?
Add the spring-boot-starter-batch dependency.
Use @EnableBatchProcessing in your configuration.
Maven Dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
Example:
Example:
jobBuilderFactory.get("job")
.start(step())
.preventRestart()
.build();
From an Array:
From a Builder:
Example:
Syntax:
Example:
@FunctionalInterface
interface Calculator {
int add(int a, int b);
}
Example:
Accessing Values
5. How do you retrieve the value from an Optional object?
Using get() :
if (optional.isPresent()) {
System.out.println(optional.get());
}
Using ifPresent() :
Using orElseGet() :
Best Practices
17. When should you avoid using Optional?
Avoid using Optional for method parameters.
Avoid Optional in fields of a class.
18. How do you chain Optional methods for complex operations?
Example:
Miscellaneous
List-Specific Questions
5. How does ArrayList grow dynamically?
When the capacity is exceeded, ArrayList increases its size by 50%
(approximately).
Set-Specific Questions
8. How does HashSet ensure uniqueness?
Uses the hashCode() and equals() methods.
Map-Specific Questions
11. What is the difference between HashMap and TreeMap ?
Advanced Topics
17. What is CopyOnWriteArrayList ?
A thread-safe variant of ArrayList where modifications create a new copy of
the list.
CopyOnWriteArrayList,
Examples ArrayList, HashMap
ConcurrentHashMap
Java Threads - Common Interview Questions
Core Concepts
1. What is a thread in Java?
A thread is a lightweight process that allows a program to perform multiple
tasks concurrently.
Example:
Example:
Advanced Topics
10. What is the difference between wait() and sleep() ?
wait() : Causes the thread to wait until it is notified, releases the lock.
sleep() : Pauses the thread for a specific time, does not release the lock.
Example:
Example:
Callable<Integer> task = () -> 42;
Future<Integer> result = executor.submit(task);
System.out.println(result.get());
Example:
Common Scenarios
14. How do you handle thread safety in Java?
Use synchronization, volatile , Locks , or thread-safe collections like
ConcurrentHashMap .
Example:
synchronized (obj) {
obj.wait();
obj.notify();
}
Example:
Example:
Exception Handling
4. How do you handle exceptions in Java?
Example:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
} finally {
System.out.println("Execution completed.");
}
Example:
Custom Exceptions
8. How do you create a custom exception in Java?
Example:
Advanced Topics
10. What is exception chaining?
Linking one exception with another using the Throwable constructor.
Example:
try {
throw new IOException("IO error");
} catch (IOException e) {
throw new RuntimeException("Runtime error", e);
}
11. What is the Error class in Java?
Represents serious issues that the application should not handle (e.g.,
OutOfMemoryError , StackOverflowError ).
Example:
try {
throw new IOException("File not found");
} catch (IOException e) {
System.out.println("Handling exception");
throw e;
}
Keyword Description
Best Practices
16. What are the best practices for exception handling in Java?
Catch specific exceptions rather than generic ones.
Avoid using exceptions for control flow.
Use meaningful exception messages.
Clean up resources in a finally block or use try-with-resources.
Log exceptions instead of suppressing them.
Method Description
Idempotent Yes No
Idempotent Yes No
20. What is the difference between 401 Unauthorized and 403 Forbidden?
401 Unauthorized: Client must authenticate to access the resource.
403 Forbidden: Client is authenticated but does not have permission to access
the resource.
7. What are the key differences between Kafka and traditional message
queues?
Consumer
Multiple consumers can read. One consumer per message.
Model
Kibana Questions
11. What is Kibana?
Kibana is an open-source visualization and analytics tool designed to work with
Elasticsearch.
OpenShift Questions
21. What is OpenShift?
OpenShift is a Kubernetes-based container orchestration platform for deploying,
managing, and scaling applications.
User Interface Integrated GUI and CLI. CLI with limited GUI.
9. What is CloudFront?
A content delivery network (CDN) service to distribute content with low
latency.
Azure Questions
11. What is Microsoft Azure?
Azure is a cloud computing platform by Microsoft offering services for
application management and hosting.
15. What is the difference between Blob Storage and File Storage in
Azure?
Blob Storage: For unstructured data (e.g., images, videos).
File Storage: Managed file shares accessible via SMB protocol.
20. What is the difference between Azure SQL Database and Cosmos DB?
SQL Database: Relational database with SQL.
Cosmos DB: Globally distributed NoSQL database.
25. What is the difference between Cloud Storage and Persistent Disks in
GCP?
Cloud Storage: Object storage for unstructured data.
Persistent Disks: Block storage for virtual machines.
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>my-app</artifactId>
<version>1.0-SNAPSHOT</version>
</project>
Example:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.8</version>
</dependency>
</dependencies>
Gradle Questions
11. What is Gradle?
Gradle is a flexible build automation tool that uses a domain-specific language
(DSL) based on Groovy or Kotlin.
Example:
task hello {
doLast {
println 'Hello, Gradle!'
}
}
Example:
plugins {
id 'java'
}
dependencies {
implementation 'org.springframework:spring-core:5.3.8'
}
Example:
rootProject.name = 'my-app'
include 'module1', 'module2'
gradle wrapper
Example:
private Singleton() {}
Example:
Example:
Example:
Example:
Fix:
5. What is normalization?
The process of organizing data to reduce redundancy and improve data integrity.
7. What is denormalization?
The process of adding redundancy to improve read performance.
8. What is an index?
A data structure that improves query performance by providing quick access to
rows in a table.
18. How do you write a SQL query to fetch data from a table?
Example:
Example:
SELECT name FROM employees WHERE salary > (SELECT AVG(salary) FROM employees);
Example:
Example:
5. What is a Dockerfile?
A text file that contains instructions for building a Docker image.
Example:
FROM openjdk:11
COPY . /app
WORKDIR /app
RUN javac Main.java
CMD ["java", "Main"]
Example:
version: "3.8"
services:
web:
image: nginx
ports:
- "80:80"
app:
build: ./app
depends_on:
- web
Example:
Kubernetes Questions
11. What is Kubernetes?
An open-source platform for automating deployment, scaling, and management of
containerized applications.
Example:
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 3
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: app
image: my-image
15. What is the difference between ReplicaSet and StatefulSet?
ReplicaSet: Ensures a specified number of identical Pods are running.
StatefulSet: Manages stateful applications with unique identities for each Pod.
Types:
Example:
apiVersion: v1
kind: ConfigMap
metadata:
name: my-config
namespace: default
data:
config.json: |
{
"key": "value"
}
CI/CD Questions
21. What is CI/CD?
CI (Continuous Integration): Automates the integration of code changes into a
shared repository.
CD (Continuous Delivery/Deployment): Automates the delivery of applications to
production or staging environments.
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'mvn clean package'
}
}
stage('Test') {
steps {
sh 'mvn test'
}
}
stage('Deploy') {
steps {
sh 'kubectl apply -f deployment.yaml'
}
}
}
}
Memory Management
10. What tools can be used to monitor and troubleshoot memory issues?
JVisualVM, JConsole, Eclipse MAT, YourKit, and Garbage Collection Logs.
Exception Handling
11. What are the types of exceptions in Java?
Checked Exceptions: Checked at compile-time (e.g., IOException).
Unchecked Exceptions: Checked at runtime (e.g., NullPointerException).
Best Practices
24. What are Java coding best practices?
Follow naming conventions.
Write unit tests for all methods.
Avoid hardcoding values; use constants or configuration files.
Use meaningful variable and method names.
Handle exceptions properly.
INSERT INTO employees (name, age, department) VALUES ('John', 30, 'HR');
Read:
Update:
Delete:
@PostMapping
public ResponseEntity<Employee> createEmployee(@RequestBody Employee employee) {
// Logic to save employee
}
@GetMapping("/{id}")
public ResponseEntity<Employee> getEmployee(@PathVariable Long id) {
// Logic to retrieve employee
}
@PutMapping("/{id}")
public ResponseEntity<Employee> updateEmployee(@PathVariable Long id, @RequestBody
Employee employee) {
// Logic to update employee
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteEmployee(@PathVariable Long id) {
// Logic to delete employee
}
}
CRUD in Frameworks
8. How is CRUD implemented in Django?
Model: Define the database schema.
Views: Map CRUD operations to request handlers.
URLs: Define endpoints for CRUD operations.
Example (Django):
def create_employee(request):
# Logic to create employee
Example:
Advanced Questions
10. What are soft deletes, and how are they implemented?
Soft Deletes: Instead of removing data, mark it as deleted (e.g., using an
is_deleted column).
Example:
Example:
BEGIN TRANSACTION;
INSERT INTO employees (name, age) VALUES ('Alice', 28);
UPDATE employees SET age = 29 WHERE name = 'Alice';
COMMIT;
Example:
Example:
2. Reverse a String
Write a method to reverse a string.
Solution:
3. Palindrome Checker
Write a program to check if a string is a palindrome.
Solution:
Solution:
5. Factorial of a Number
Write a program to calculate the factorial of a number using recursion.
Solution:
6. Fibonacci Sequence
Write a method to print the first n Fibonacci numbers.
Solution:
7. Anagram Checker
Write a method to check if two strings are anagrams of each other.
Example: Input: "listen", "silent" Output: true
Solution:
Solution:
Solution:
Solution:
File Management
5. How do you view the contents of a file in Linux?
cat file.txt
less file.txt
more file.txt
tail -n 10 file.txt
head -n 10 file.txt
Using locate :
locate filename
kill -9 PID
Kill by name:
pkill process_name
Networking
16. How do you check the network configuration?
ifconfig
ip addr
ping google.com
Traceroute:
traceroute google.com
Using rsync :
#!/bin/bash
# Simple script to print Hello World
echo "Hello, World!"
crontab -e
0 5 * * * /path/to/script.sh
Common Commands
5. How do you initialize a Git repository?
Command:
git init
git status
Committing changes:
git commit
Advanced Topics
16. What is the difference between git stash and git reset ?
git stash : Temporarily saves changes without committing.
git reset : Moves the branch pointer to a previous commit and optionally
modifies the working directory and index.
Command:
git rebase <branch-name>
20. How do you remove untracked files from your working directory?
Command:
git clean -f
git log
Requirement Analysis
5. What happens during the requirement analysis phase?
Answer: Gathering and documenting user needs, analyzing feasibility, and
defining functional and non-functional requirements.
Design Phase
7. What are the key deliverables of the design phase?
Answer:
High-Level Design (HLD): System architecture and modules.
Low-Level Design (LLD): Detailed component designs and logic.
Development Phase
9. How do you ensure code quality during the development phase?
Answer: Use code reviews, automated testing, adherence to coding standards, and
static code analysis tools.
Testing Phase
11. What are the different levels of testing in SDLC?
Answer:
Unit Testing: Testing individual components.
Integration Testing: Testing interactions between modules.
System Testing: Testing the complete application.
Acceptance Testing: Ensuring the software meets user requirements.
18. What are user stories, and why are they important in Agile SDLC?
Answer: User stories describe features from the end-user perspective. They help
developers understand user needs and ensure the software delivers value.
Multiple
Supported Not supported
Inheritance
Any type of
Variables public static final by default
variable
Example:
public interface A {
void methodA();
}
Example:
Example:
@FunctionalInterface
public interface MyFunctionalInterface {
void execute();
}
Abstract Classes
6. What is an abstract class in Java?
Answer: An abstract class is a class that cannot be instantiated and can have
both abstract and concrete methods.
7. What is the difference between an abstract class and a concrete class?
Answer: An abstract class cannot be instantiated and may have abstract methods,
while a concrete class can be instantiated and must implement all abstract
methods from its parent class (if any).
Example:
18. What are exceptions in Java, and how are they handled?
Answer:
Exceptions are events that disrupt the normal flow of execution.
They are handled using try , catch , finally , and throw .
Thread
Not thread-safe Thread-safe
Safety
Null Allows 1 null key and multiple Does not allow null keys
Keys/Values null values or values
5. Implement JOIN
Exercise: Write a query to retrieve a list of employees and their respective
manager names from the employees and managers tables.
Solution:
6. Use Subqueries
Exercise: Write a query to find the employees whose salary is higher than the
average salary.
Solution:
SELECT name
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
7. Update Data
Exercise: Write a query to increase the salary of employees in the 'IT'
department by 10%.
Solution:
UPDATE employees
SET salary = salary * 1.10
WHERE department = 'IT';
8. Delete Data
Exercise: Write a query to delete all employees who have not updated their
profiles since 2020.
Solution:
9. Create a Table
Exercise: Write a query to create a departments table with columns id , name ,
and location .
Solution:
SELECT name,
CASE
WHEN salary > 100000 THEN 'High'
WHEN salary BETWEEN 50000 AND 100000 THEN 'Medium'
ELSE 'Low'
END AS salary_level
FROM employees;
BEGIN;
UPDATE employees SET department = 'Finance' WHERE id = 101;
INSERT INTO department_changes (employee_id, old_department, new_department)
VALUES (101, 'HR', 'Finance');
COMMIT;
7. What is HATEOAS?
Answer: HATEOAS (Hypermedia as the Engine of Application State) is a constraint
of REST that allows clients to dynamically navigate APIs using hypermedia links
provided in responses.
Advanced Topics
11. What is the difference between REST and GraphQL?
Answer:
REST: Uses fixed endpoints and relies on HTTP methods.
GraphQL: Uses a single endpoint and allows clients to specify the
structure of the response.
Example:
{
"error_code": 400,
"message": "Invalid input"
}
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type
Practical Exercises
16. Create a RESTful API to manage a list of books.
Requirements:
GET /books : Retrieve all books.
POST /books : Add a new book.
PUT /books/{id} : Update book details.
DELETE /books/{id} : Delete a book.
CSS3 Questions
6. What are some new features introduced in CSS3?
Answer:
Media queries for responsive design.
Transitions, transforms, and animations.
Grid and Flexbox layouts.
Custom properties (CSS variables).
New selectors (e.g., :nth-child , :not ).
JavaScript Questions
Example:
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2
Lifecycle Hooks
5. What are Angular lifecycle hooks?
Answer: Lifecycle hooks are methods invoked at specific points in a component’s
lifecycle. Examples include:
ngOnInit : Called after the component is initialized.
ngOnChanges : Called when input properties change.
ngOnDestroy : Called before the component is destroyed.
Data Binding
7. What are the types of data binding in Angular?
Answer:
Interpolation: Binding data from the component to the view (e.g.,
{{property}} ).
Property Binding: Binding a property in the view (e.g.,
[src]="imageUrl" ).
Event Binding: Binding events to methods (e.g.,
(click)="handleClick()" ).
Two-Way Binding: Syncing data between the component and the view using
[(ngModel)] .
8. How does two-way data binding work in Angular?
Answer: Two-way binding combines property binding and event binding using the
[(ngModel)] directive to sync data between the component and the view.
Dependency Injection
9. What is Dependency Injection (DI) in Angular?
Answer: DI is a design pattern in which a class receives its dependencies from
an external source rather than creating them itself. Angular uses DI to provide
services to components.
Routing
11. How does Angular handle routing?
Answer: Angular uses the RouterModule to configure routes and navigate between
different components.
Example:
{
path: 'feature',
loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule)
}
Advanced Topics
14. What is Angular’s change detection mechanism?
Answer: Angular uses a unidirectional data flow and a change detection
mechanism to track changes and update the DOM. The Zone.js library triggers
change detection whenever an event occurs.