Java Full Stack Developer Kit Sample
Java Full Stack Developer Kit Sample
(Sample)
Hello and welcome! I'm Parikh Jain, and I'm excited to share with you the ultimate
guide to become a java full stack developer interviews. This kit is a labor of love,
drawn from my extensive journey as an SDE at Amazon, a founding member at
Coding Ninjas, and the founder of Propeers. I’ve distilled my real-world
experience into a comprehensive resource that covers every topic you need to
excel.
This kit covers
Database Integration
Frontend Development
HTML & CSS Concepts With Interview Questions & Code Snippets
Variables & Operators: Use variables to store data; use arithmetic, relational,
and logical operators.
Example – Encapsulation:
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
2.2 Inheritance
Concept:
Inheritance lets a new class (subclass) inherit properties and methods from an
existing class (superclass), promoting code reuse.
Example – Inheritance:
// Superclass
class Animal {
String name;
Animal(String name) {
this.name = name;
}
void makeSound() {
System.out.println("Some generic sound");
}
}
// Subclass
class Dog extends Animal {
Dog(String name) {
super(name);
}
@Override
2.3 Polymorphism
Concept:
Polymorphism allows one interface to be used for a general class of actions. It can
be achieved through:
class Vehicle {
void start() {
System.out.println("Vehicle starting...");
}
}
2.4 Abstraction
Concept:
// Concrete method
void display() {
System.out.println("This is a shape.");
}
}
@Override
double area() {
return Math.PI * radius * radius;
}
}
interface Drawable {
void draw();
}
3. Exception Handling
Concept:
Handle errors and exceptional conditions using try-catch-finally blocks. You can also
throw exceptions using throw and declare them with throws .
Java Collections (e.g., List, Set, Map) are used to store groups of objects.
Example – Using an ArrayList:
import java.util.ArrayList;
import java.util.List;
Generics
Concept:
Functional Interfaces
Concept:
A functional interface is an interface with a single abstract method. They can be
used as the assignment target for lambda expressions.
@FunctionalInterface
interface MathOperation {
int operate(int a, int b);
}
Detailed explanations of core backend topics using Spring Boot for REST API
development, JPA/Hibernate for persistence, and Spring Security for
authentication and authorization—all with practical code examples.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
import org.springframework.web.bind.annotation.*;
@GetMapping("/greeting")
public String greeting(@RequestParam(value = "name", defaultValue = "Wo
rld") String name) {
return "Hello, " + name + "!";
}
}
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public String handleAllExceptions(Exception ex) {
return "Error occurred: " + ex.getMessage();
}
}
JPA Entity
Annotate classes with @Entity to map them to a database table.
import javax.persistence.*;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
Repository Layer
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
Basic Configuration
You can quickly secure endpoints using Java configuration.
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecu
rity;
import org.springframework.security.config.annotation.web.configuration.Ena
bleWebSecurity;
import org.springframework.security.config.annotation.web.configuration.We
bSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable() // For simplicity in this example
.authorizeRequests()
.antMatchers("/api/public/**").permitAll() // Public endpoints
.anyRequest().authenticated() // Secure all other endpoints
.and()
Advanced Concepts
JWT Authentication: For stateless REST APIs, you can use JSON Web Tokens
(JWT) for authentication.
@Configuration
@EnableWebSecurity
public class BasicSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RAND
OM_PORT)
public class ProductControllerIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void testGetProducts() {
String response = this.restTemplate.getForObject("/api/products", String.
class);
assertThat(response).contains("products");
}
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Welcome Page</title>
</head>
<body>
<h1 th:text="'Hello, ' + ${username} + '!'">Hello, User!</h1>
<p>Welcome to our Spring Boot Thymeleaf application.</p>
</body>
Controller:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class WelcomeController {
@GetMapping("/welcome")
public String welcome(Model model) {
model.addAttribute("username", "Integration Pro");
return "welcome"; // Thymeleaf resolves to welcome.html
}
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>User List</title>
</head>
<body>
<h1>User List</h1>
<ul>
<li th:each="user : ${users}" th:text="${user}">User Name</li>
</ul>
Controller:
import java.util.Arrays;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class UserController {
@GetMapping("/users")
public String getUsers(Model model) {
model.addAttribute("users", Arrays.asList("Alice", "Bob", "Charlie"));
return "userList";
}
}
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@GetMapping("/api/greeting")
public String greeting(@RequestParam(value = "name", defaultValue = "Gu
est") String name) {
return "Hello, " + name + "!";
}
}
In your Spring Boot application, you can serve static files (HTML, CSS, JS) placed
under src/main/resources/static .
Example File Structure:
src/main/resources/static/
├── index.html
├── css/
└── js/
index.html Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Static Page</title>
<link rel="stylesheet" href="/css/styles.css">
</head>
<body>
<h1>Welcome to the Static Page</h1>
<script src="/js/script.js"></script>
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigure
r;
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://localhost:3000", "http://example.com")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowCredentials(true);
}
};
}
}
Example:
Example:
import org.springframework.security.config.annotation.web.builders.HttpSecu
rity;
import org.springframework.security.config.annotation.web.configuration.We
bSecurityConfigurerAdapter;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.Ena
bleWebSecurity;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/public/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
}
import javax.persistence.*;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String email;
// Constructors
public User() { }
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Transactional
public User createUser(User user) {
// Additional business logic can be applied here
return userRepository.save(user);
}
}
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
Post Entity:
import javax.persistence.*;
@Entity
@Table(name = "posts")
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(length = 1000)
private String content;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private User user;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
Usage in Service:
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "customers")
public class Customer {
@Id
private String id;
private String name;
private String email;
Mongo Repository:
import org.springframework.data.mongodb.repository.MongoRepository;
java
Copy
import org.springframework.data.jpa.repository.Query;
java
Copy
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany
@JoinTable(
name = "student_course",
joinColumns = @JoinColumn(name = "student_id"),
inverseJoinColumns = @JoinColumn(name = "course_id"))
private Set<Course> courses;
// Constructors, getters, setters...
}
@Entity
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany(mappedBy = "courses")
private Set<Student> students;
// Constructors, getters, setters...
}
1. Concepts & Code Snippets – covering unit tests, integration tests, and
DevOps practices such as CI/CD pipelines and containerization.
@Test
public void testAdd() {
CalculatorTest calc = new CalculatorTest();
assertEquals(5, calc.add(2, 3), "2 + 3 should equal 5");
}
}
@Mock
private UserRepository userRepository;
@InjectMocks
private UserService userService;
public UserServiceTest() {
MockitoAnnotations.openMocks(this);
}
@Test
public void testCreateUser() {
User user = new User("john_doe", "[email protected]");
when(userRepository.save(any(User.class))).thenReturn(user);
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.beans.factory.annotation.Autowired;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RAND
OM_PORT)
public class GreetingControllerIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void testGreetingEndpoint() {
String response = restTemplate.getForObject("/api/greeting?name=Integr
ation", String.class);
assertThat(response).contains("Hello, Integration");
}
}
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.hibernate.ddl-auto=create-drop
B. DevOps Practices
version: '3.8'
services:
app:
build: .
ports:
- "8080:8080"
environment:
- SPRING_PROFILES_ACTIVE=prod
db:
image: postgres:13
environment:
POSTGRES_USER: user
<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.8</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
Example:
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.*;
get(key) : Returns the value of the key if it exists in the cache, otherwise returns
-1.
: Inserts the value if the key is not already present. When the cache
put(key, value)
reaches its capacity, it should invalidate the least recently used item before
inserting a new item.
import java.util.*;
Explanation:
Data Structures: A HashMap is used for O(1) access to values, and a LinkedList
get Method: Moves the key to the front of the list on access.
Below is a collection of minimal, sample code snippet solutions for each of the 26
machine coding round questions. These examples are intended to serve as a
starting point—you can expand and refine them based on your requirements.
import java.util.concurrent.*;
import java.util.*;
class ThreadPool {
private final BlockingQueue<Runnable> taskQueue = new LinkedBlockingQ
ueue<>();
private final List<Worker> workers = new ArrayList<>();
private volatile boolean isShutdown = false;
// For demonstration
public static void main(String[] args) {
ThreadPool pool = new ThreadPool(3);
pool.submit(() -> System.out.println("Task executed by " + Thread.curren
tThread().getName()));
pool.submit(() -> System.out.println("Another task executed by " + Threa
d.currentThread().getName()));
pool.shutdown();
}
}
Sample Question 1: How do you create a responsive navigation bar using HTML
& CSS? (Intermediate)
Answer:
A responsive navigation bar typically uses semantic <nav> elements, lists for menu
items, and media queries to adapt styles for different screen sizes. Techniques
like Flexbox are often employed to align items.
Code Example:
<nav class="navbar">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
.navbar ul {
display: flex;
list-style: none;
padding: 0;
}
.navbar li {
margin-right: 20px;
Sample Question 2: How does CSS specificity work when combining selectors,
and how can you override styles defined with high specificity, such as inline
styles? (Hard)
Answer:
CSS specificity is calculated based on the number of ID selectors, class selectors,
and element selectors used. Inline styles have the highest specificity. To override
styles with high specificity, you can use the !important flag or create a selector with
higher specificity, though this should be done sparingly.
Code Example:
Event bubbling occurs when an event propagates from the target element up
through its ancestors. Capturing is the reverse process, where events are
handled from the outer elements down to the target element.
Code Example:
// Capturing phase
document.getElementById("child").addEventListener("click", () => {
console.log("Child clicked");
}, true);
Answer:
Memoization is an optimization technique that caches the results of function
calls based on their input arguments. When the same inputs occur again, the
cached result is returned instead of re-computing the value.
Code Example:
function* numberGenerator() {
let num = 0;
while (true) {
yield num++;
}
Code Example:
const myIterable = {
data: [1, 2, 3],
[Symbol.iterator]() {
let index = 0;
const data = this.data;
return {
next() {
if (index < data.length) {
return { value: data[index++], done: false };
} else {
return { done: true };
}
}
};
}
};
for (const value of myIterable) {
console.log(value);
}
2. Sample Question: How does the React Context API work for managing
global state? (Intermediate)
Answer:
The Context API provides a way to pass data through the component tree
without having to pass props down manually at every level. It’s useful for
global data like themes, user authentication, or language settings.
2. Question: How does lazy loading work in Angular and why is it beneficial?
(Intermediate)
Answer: Lazy loading loads feature modules only when needed, reducing the
initial bundle size and improving application startup performance.
Code Example:
// Parent Component
<template>
<div>
<Greeting name="Alice" />
</div>
</template>
<script>
import Greeting from './Greeting.vue';
export default {
components: { Greeting }
}
</script>
// In a Vue component
const AsyncComponent = () => import('./components/AsyncComponent.vu
e');
export default {
components: {
AsyncComponent
},
template: `<AsyncComponent />`
}
Build Tools & Testing With Solutions & Code Snippets(10 Questions)
// .eslintrc.json
{
"env": {
// cypress/integration/sample_spec.js
describe('My First Test', () => {
it('Visits the app and checks content', () => {
cy.visit('http://localhost:3000');
cy.contains('Welcome');
});
});
Answer: Web Workers run scripts in background threads separate from the
main execution thread, preventing heavy computations from blocking the UI.
They are ideal for CPU-intensive tasks.
Code Example:
// main.js
const worker = new Worker('worker.js');
worker.postMessage('Start processing');
worker.onmessage = function(event) {
console.log('Result:', event.data);
};
// worker.js
onmessage = function(event) {
// Perform heavy computation here
postMessage('Processing complete');
};
Answer: Optimize animations by using CSS transforms and opacity (which are
GPU-accelerated), avoiding layout changes during animations, and preferring CSS
animations over JavaScript when possible.
Code Example:
@keyframes fadeIn {
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
}
.animated {
animation: fadeIn 0.5s ease-in-out;
1
. Countdown Timer
Problem:
Implement a countdown timer that counts down to a specified future date.
Solution:
HTML:
<div id="timer">
<span id="days"></span>d
<span id="hours"></span>h
<span id="minutes"></span>m
<span id="seconds"></span>s
</div>
JavaScript:
──────────────────────────────
Infinite Scrolling with Lazy Loading
Problem:
Create an infinite scroll list that dynamically loads more items as the user scrolls
down. Each item includes an image that is lazy loaded when it enters the viewport.
Plain Implementation:
HTML:
<div id="infinite-scroll-container">
<ul id="item-list"></ul>
</div>
CSS:
#infinite-scroll-container {
height: 400px;
overflow-y: auto;
border: 1px solid #ccc;
JavaScript:
let page = 1;
const loadItems = async () => {
// Simulated API call (replace with actual API)
for (let i = 0; i < 10; i++) {
const li = document.createElement('li');
li.innerHTML = `
<h4>Item ${page * 10 + i}</h4>
<img data-src="https://via.placeholder.com/400x200?text=Item+${page
* 10 + i}" alt="Item Image">
`;
list.appendChild(li);
}
lazyLoadImages();
page++;
container.addEventListener('scroll', () => {
if (container.scrollTop + container.clientHeight >= container.scrollHeight - 10)
{
loadItems();
}
});
// Initial load
loadItems();
React Implementation:
// InfiniteScroll.jsx
import React, { useState, useEffect, useRef } from 'react';
function InfiniteScroll() {
const [items, setItems] = useState([]);
useEffect(() => {
loadItems();
}, []);
return (
<divid="infinite-scroll-container"
ref={containerRef}
style={{ height: '400px', overflowY: 'auto', border: '1px solid #ccc', padding: '
onScroll={handleScroll}
>
<ul id="item-list">
{items.map(item => (
<li key={item.id} style={{ marginBottom: '20px' }}>
<h4>{item.text}</h4>
<imgdata-src={item.image}
alt={`Item ${item.id}`}
style={{ width: '100%', display: 'block', opacity: 0, transition: 'opacity 0.5
/>
</li>
))}
</ul>
</div>
);
}
Sample 1
. Closure Example
Demonstrates closure for data encapsulation.
function counter() {
let count = 0;
return function() {
count++;
return count;
};
}
const increment = counter();
console.log(increment()); // 1
console.log(increment()); // 2
Sample 2
. Mapping Over an Array in React
Generates a list from an array.
──────────────────────────────
DSA Questions For Java Full Stack Developer With Leetcode links
( 100 questions)