Skip to content
thesarfo

Reference

Interview Prep: Java Backend Guide

A structured Q&A tour of Java backend fundamentals — core language skills, database management, APIs and web services, cloud computing, and DevOps practices.

views 0

Section 1: Core Skills

Programming Language Proficiency

Syntax and Semantics

Explain the differences between == and equals() in Java. == checks for reference equality — whether both references point to the same object. equals() checks for value equality — whether two objects are logically equivalent.

How do you define and use enums in Java?

public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
public class TestEnum {
public static void main(String[] args) {
Day day = Day.MONDAY;
System.out.println(day);
}
}

What is the difference between String, StringBuilder, and StringBuffer? String is immutable. StringBuilder is mutable and not thread-safe. StringBuffer is mutable and thread-safe.

How do you handle null values in your code? What strategies avoid NullPointerException? Use Optional to avoid null checks, use default values, use Objects.requireNonNull(), and perform null checks before dereferencing.

Explain the concept of generics in Java. How do you use them? Generics allow types (classes and interfaces) to be parameters when defining classes, interfaces, and methods, enabling code reuse and type safety.

public class Box<T> {
private T t;
public void set(T t) {
this.t = t;
}
public T get() {
return t;
}
}
Box<Integer> integerBox = new Box<>();
integerBox.set(10);
Integer someInteger = integerBox.get();

Data Structures and Algorithms

How would you implement a binary search algorithm in Java?

public int binarySearch(int[] arr, int key) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == key) {
return mid;
} else if (arr[mid] < key) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}

What is the difference between a List and a Set in Java? List allows duplicates and maintains insertion order. Set does not allow duplicates and does not guarantee order.

Explain how a HashMap works in Java. A HashMap uses an array plus a linked list/binary tree to store key-value pairs. It uses hashCode() to determine the bucket and equals() to resolve collisions.

How would you detect a cycle in a linked list? Use Floyd’s Cycle-Finding Algorithm (the “tortoise and hare” algorithm).

Describe the time complexity of common sorting algorithms (QuickSort, MergeSort). QuickSort: average O(n log n), worst-case O(n²). MergeSort: O(n log n).

Error Handling and Debugging

How do you handle exceptions in Java? Distinguish checked and unchecked exceptions. Use try-catch blocks. Checked exceptions must be declared in the method signature or caught (e.g., IOException). Unchecked exceptions are subclasses of RuntimeException and don’t need to be declared (e.g., NullPointerException).

What is a try-with-resources statement in Java? It automatically closes resources (like files) that implement AutoCloseable.

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
// Use the resource
} catch (IOException e) {
e.printStackTrace();
}

How do you use logging in your Java applications? Use logging frameworks like Log4j or SLF4J.

What are common debugging techniques? Use a debugger, log messages, and analyze stack traces.

How do you create custom exceptions in Java?

public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}

Standard Libraries and Commonly Used Frameworks

  • Commonly used standard librariesjava.util, java.io, java.nio, java.time, java.math.

  • Java Collections Framework — interfaces like List, Set, Map, and classes like ArrayList, HashSet, HashMap.

  • java.time — provides LocalDate, LocalTime, LocalDateTime, ZonedDateTime for date and time operations.

  • Stream API — processes sequences of elements:

    List<String> list = Arrays.asList("a", "b", "c");
    list.stream().filter(s -> s.startsWith("a")).forEach(System.out::println);
  • File I/O — use FileReader, FileWriter, BufferedReader, BufferedWriter, and Files.

Database Management

Knowledge of SQL and NoSQL Databases

  • SQL vs. NoSQL — SQL databases are relational, structured, and use SQL. NoSQL databases are non-relational, have a flexible schema, and use various data models (document, key-value, graph).

  • Connecting via JDBC:

    Connection conn = DriverManager.getConnection(url, user, password);
  • ACID properties — Atomicity, Consistency, Isolation, Durability.

  • ORM and Hibernate — an ORM maps objects to database tables; Hibernate provides annotations and configuration to automate SQL operations.

  • Choosing SQL vs. NoSQL — base the decision on data structure, scalability needs, transaction requirements, and query complexity.

Query Optimization

  • Optimize SQL queries with indexes, by avoiding unnecessary columns, and by optimizing joins.
  • Indexes speed up search operations by maintaining a sorted order of data.
  • Execution plans show how SQL queries are executed, helping identify bottlenecks.
  • Monitor and troubleshoot slow queries with query profiling tools and by analyzing execution plans and performance metrics.
  • Optimize schemas by normalizing tables, using appropriate data types, and indexing frequently queried columns.

Data Modeling and Schema Design

  • Designing a relational schema — identify entities, define relationships, normalize data, and create tables.
  • Normalization — eliminates data redundancy and ensures data integrity by organizing data into multiple related tables.
  • Many-to-many relationships — handled via a join table mapping the two entities.
  • NoSQL data modeling — denormalization, document modeling, key-value pairs.
  • Database migrations — manage with tools like Liquibase or Flyway to version and automate schema changes.

Transactions and Concurrency Control

  • A database transaction is a unit of work executed as a whole — important for data integrity and consistency.
  • In Spring, use @Transactional to manage transactions.
  • Isolation levels — Read Uncommitted, Read Committed, Repeatable Read, Serializable.
  • A deadlock occurs when two or more transactions block each other by holding locks; prevent it with a consistent locking order and timeout settings.
  • Manage concurrent access with locking mechanisms, isolation levels, and optimistic or pessimistic concurrency control.

APIs and Web Services

Understanding RESTful APIs

  • REST principles — Statelessness, Client-Server, Cacheability, Layered System, Code on Demand, Uniform Interface.
  • Designing a RESTful API — define resources, use appropriate HTTP methods and status codes, and follow REST principles.
  • HTTP methodsGET retrieves data, POST creates data, PUT updates data, DELETE removes data.
  • Status codes indicate the result of an HTTP request (e.g., 200 OK, 404 Not Found).
  • Versioning — URI versioning, query parameters, or headers.

Implementing and Consuming Web Services

Creating a RESTful web service with Spring Boot:

@RestController
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
}
  • Handle exceptions in a Spring Boot REST API with @ControllerAdvice and @ExceptionHandler.
  • Swagger is an API documentation tool; use the springfox-swagger2 and springfox-swagger-ui dependencies.
  • Consume RESTful APIs in Java with RestTemplate, WebClient, or Feign.
  • Synchronous web services wait for a response before continuing; asynchronous ones allow other processes to continue while waiting.

Authentication and Authorization

  • OAuth2 is an authorization framework letting third-party applications access user resources; common flows include Authorization Code, Implicit, Password Credentials, and Client Credentials.
  • JWT authentication in Spring Boot — use spring-boot-starter-security and jjwt, and create a filter to validate JWT tokens.
  • Common authentication mechanisms: Basic Authentication, OAuth2, JWT, API keys.
  • Secure a REST API with Spring Security by configuring security settings, using @EnableWebSecurity, and defining security rules.
  • Authentication vs. authorization — authentication verifies identity; authorization grants permissions based on identity.

Integration and Testing

Unit-testing a RESTful web service:

@WebMvcTest(MyController.class)
public class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testHello() throws Exception {
mockMvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string("Hello, World!"));
}
}
  • Postman is used for API testing, documentation, and collaboration.
  • Integration testing — use @SpringBootTest and TestRestTemplate.
  • A contract test ensures a service adheres to the agreed-upon API contract.
  • Mock external services in tests with tools like WireMock or Mockito.

Section 2: Advanced Concepts

Cloud Computing

Understanding Cloud Architecture

  • Service models — IaaS, PaaS, SaaS.
  • Public vs. private vs. hybrid cloud — public cloud is shared and managed by third parties; private cloud is dedicated to a single organization; hybrid cloud combines both.
  • Microservices vs. monolith — microservices are small, independent services communicating over APIs; a monolith is a single, unified application.
  • Scalable, resilient architecture — use autoscaling, load balancing, redundancy, and distributed systems.
  • Microservices trade-offs — advantages: scalability, flexibility, faster deployment. Challenges: complexity, inter-service communication, data consistency.

Containerization and Orchestration

Docker is a containerization platform:

FROM openjdk:11
COPY . /app
WORKDIR /app
RUN ./mvnw package
CMD ["java", "-jar", "target/app.jar"]
  • Kubernetes is an orchestration platform for managing containers, with components like Nodes, Pods, Services, and Deployments.
  • Manage secrets and configuration in Kubernetes with Secrets and ConfigMaps.
  • Helm is a package manager for Kubernetes applications.
  • Ensure high availability with replica sets, load balancers, and distributed nodes.

Cloud Services and Providers

  • Common services: Compute — EC2, Azure VMs, GCE. Storage — S3, Azure Blob Storage, GCS. Database — RDS, Azure SQL Database, Cloud SQL.
  • Setting up an AWS ECS cluster: create a cluster, define task definitions, set up services.
  • CI/CD in cloud deployment automates the build, test, and deployment process for faster, reliable releases.
  • Securing cloud applications — IAM roles, data encryption, regular audits, and applying security patches.
  • Monitor and troubleshoot cloud services with tools like CloudWatch, Azure Monitor, and Stackdriver.

Serverless Architecture

  • Serverless computing lets developers build applications without managing servers — code runs in response to events while the provider manages infrastructure.
  • Benefits: cost-efficiency, scalability, reduced operational complexity. Limitations: cold starts, execution limits, vendor lock-in.
  • Deploy a serverless app on AWS Lambda by writing a function, configuring triggers, and deploying via the console or CLI.
  • Common use cases — event-driven applications, microservices, mobile/web backends.
  • Manage state with managed services like AWS Step Functions, DynamoDB, or S3.

DevOps Practices

CI/CD Pipelines

  • Purpose — CI/CD automates the build, test, and deployment process, via tools like Jenkins, GitLab CI, or GitHub Actions.
  • Set up a Java CI/CD pipeline by defining build/test/deploy stages and automating them with a CI/CD tool.
  • Continuous testing integrates automated tests into the CI/CD pipeline to ensure code quality.
  • Common tools — Jenkins, GitLab CI, Travis CI, CircleCI — chosen based on project requirements, integration capabilities, and ease of use.
  • Manage environment configurations via environment variables, configuration files, and secret management tools.

Infrastructure as Code (IaC)

  • IaC lets you define and manage infrastructure using code, ensuring consistency, version control, and automation.
  • Tools like Terraform and CloudFormation define infrastructure resources in code and provision/manage them.
  • Benefits: consistency, repeatability, automation, and version control.
  • Best practices: modularize code, use version control, follow naming conventions.
  • Test and validate IaC templates using linting tools, syntax validation, and automated tests.

Monitoring and Logging

  • Monitoring ensures system health and performance, and helps troubleshoot issues.
  • Common tools — Prometheus, Grafana, CloudWatch, Azure Monitor, Stackdriver.
  • Set up logging for a cloud application with logging frameworks and services like the ELK Stack, Fluentd, or CloudWatch Logs.
  • Observability covers monitoring, logging, and tracing to understand system behavior.
  • Handle alerts and incident management with alerting tools, defined alert thresholds, and an incident response plan.