0% found this document useful (0 votes)
5 views66 pages

Java Full Stack Developer Kit Sample

The Java Full Stack Developer Kit is a comprehensive resource designed to prepare individuals for Java full stack developer interviews, covering essential topics in backend and frontend development, including Java fundamentals, Spring Boot, and various JavaScript frameworks. It includes practical code examples, interview questions, and challenges to enhance understanding and skills. The kit is based on the author's extensive experience in software development and aims to provide a thorough understanding of the necessary concepts and practices in the field.

Uploaded by

dateko8319
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views66 pages

Java Full Stack Developer Kit Sample

The Java Full Stack Developer Kit is a comprehensive resource designed to prepare individuals for Java full stack developer interviews, covering essential topics in backend and frontend development, including Java fundamentals, Spring Boot, and various JavaScript frameworks. It includes practical code examples, interview questions, and challenges to enhance understanding and skills. The kit is based on the author's extensive experience in software development and aims to provide a thorough understanding of the necessary concepts and practices in the field.

Uploaded by

dateko8319
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Java Full Stack Developer Kit

(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

Backend Development (Java)

Java Fundamentals & OOPS

Backend Development (Spring Boot, JPA/Hibernate, Security)

Frontend Integration (Thymeleaf & JavaScript Frameworks)

Database Integration

Testing & DevOps

Machine Coding Round Questions

Data Structures & Algorithms (DSA) Interview Questions

Frontend Development

HTML & CSS Concepts With Interview Questions & Code Snippets

Javascript Concepts With Interview Questions & Code Snippets

Advanced Javascript Concepts With Interview Questions & Code


Snippets

React Concepts With Interview Questions & Code Snippets

Angular Concepts With Interview Questions & Code Snippets

Vue Js Concepts With Interview Questions & Code Snippets

Java Full Stack Developer Kit (Sample) 1


Performance Optimization With Best Practices Concepts With Interview
Questions & Code Snippets

Machine Coding Round Questions - Frontend

DSA Interview Questions Along With Leetcode Links

Backend Development (Java)

1. Java Fundamentals & OOPS


Data Types, Variables, and Control Structures
Primitive Types: byte , short , int , long , float , double , char , and boolean .

Variables & Operators: Use variables to store data; use arithmetic, relational,
and logical operators.

Control Structures: if-else , switch-case , loops ( for , while , do-while ).

Example – HelloWorld with a Loop and Conditional:

public class HelloWorld {


public static void main(String[] args) {
int count = 5;
for (int i = 1; i <= count; i++) {
if (i % 2 == 0) {
System.out.println(i + " is even");
} else {
System.out.println(i + " is odd");
}
}
}
}

Java Full Stack Developer Kit (Sample) 2


2. Object-Oriented Programming (OOP) Concepts
2.1 Encapsulation
Concept:
Encapsulation bundles data (fields) and methods into a class while restricting
direct access to some of its components using access modifiers.

Example – Encapsulation:

public class Person {


// Private fields
private String name;
private int age;

// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}

// Getter and Setter for name


public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

// Getter and Setter for age with validation


public int getAge() {
return age;
}
public void setAge(int age) {

Java Full Stack Developer Kit (Sample) 3


if(age > 0) {
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

Java Full Stack Developer Kit (Sample) 4


void makeSound() {
System.out.println("Bark!");
}
}

public class TestInheritance {


public static void main(String[] args) {
Animal myDog = new Dog("Buddy");
myDog.makeSound(); // Output: Bark!
}
}

2.3 Polymorphism
Concept:

Polymorphism allows one interface to be used for a general class of actions. It can
be achieved through:

Method Overloading (Compile-time): Same method name with different


parameters in the same class.

Method Overriding (Runtime): Subclass provides its specific implementation


of a method declared in the superclass.

Example – Method Overloading:

public class Calculator {


// Overloaded methods
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}

Java Full Stack Developer Kit (Sample) 5


public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("Integer addition: " + calc.add(2, 3));
System.out.println("Double addition: " + calc.add(2.5, 3.5));
}
}

Example – Method Overriding:

class Vehicle {
void start() {
System.out.println("Vehicle starting...");
}
}

class Car extends Vehicle {


@Override
void start() {
System.out.println("Car starting with a keyless system!");
}
}

public class TestPolymorphism {


public static void main(String[] args) {
Vehicle vehicle = new Car();
vehicle.start(); // Output: Car starting with a keyless system!
}
}

2.4 Abstraction
Concept:

Java Full Stack Developer Kit (Sample) 6


Abstraction hides the complex implementation details and exposes only the
necessary features. It is implemented using abstract classes and interfaces.

Example – Abstract Class:

abstract class Shape {


// Abstract method (no implementation)
abstract double area();

// Concrete method
void display() {
System.out.println("This is a shape.");
}
}

class Circle extends Shape {


double radius;
Circle(double radius) {
this.radius = radius;
}

@Override
double area() {
return Math.PI * radius * radius;
}
}

public class TestAbstraction {


public static void main(String[] args) {
Shape circle = new Circle(5.0);
circle.display();
System.out.println("Area: " + circle.area());
}
}

Java Full Stack Developer Kit (Sample) 7


Example – Interface:

interface Drawable {
void draw();
}

class Rectangle implements Drawable {


@Override
public void draw() {
System.out.println("Drawing a rectangle.");
}
}

public class TestInterface {


public static void main(String[] args) {
Drawable d = new Rectangle();
d.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 .

Example – Exception Handling:

public class ExceptionDemo {


public static void main(String[] args) {
try {
int result = divide(10, 0);

Java Full Stack Developer Kit (Sample) 8


System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero!");
} finally {
System.out.println("Execution completed.");
}
}

public static int divide(int a, int b) throws ArithmeticException {


return a / b;
}
}

4. Collections & Generics


Collections
Concept:

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;

public class CollectionExample {


public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");

// Iterate using enhanced for-loop

Java Full Stack Developer Kit (Sample) 9


for (String fruit : fruits) {
System.out.println(fruit);
}
}
}

Generics
Concept:

Generics enable types (classes and methods) to operate on objects of various


types while providing compile-time type safety.
Example – Generic Method:

public class GenericExample {


public static <T> void printArray(T[] array) {
for (T element : array) {
System.out.println(element);
}
}

public static void main(String[] args) {


Integer[] intArray = {1, 2, 3, 4};
String[] strArray = {"Hello", "World"};
printArray(intArray);
printArray(strArray);
}
}

5. Lambda Expressions & Functional Interfaces


Lambda Expressions

Java Full Stack Developer Kit (Sample) 10


Concept:
Lambda expressions provide a clear and concise way to represent a method
interface using an expression.
Example – Lambda with Runnable:

public class LambdaExample {


public static void main(String[] args) {
Runnable task = () -> System.out.println("Running in a thread!");
new Thread(task).start();
}
}

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.

Example – Custom Functional Interface:

@FunctionalInterface
interface MathOperation {
int operate(int a, int b);
}

public class FunctionalInterfaceExample {


public static void main(String[] args) {
MathOperation addition = (a, b) -> a + b;
System.out.println("Addition: " + addition.operate(5, 3));
}
}

Java Full Stack Developer Kit (Sample) 11


Part 2: Interview Questions & Code
Challenges (20+)
Below are over 20 common interview questions, each paired with a concise code
snippet or explanation.

Sample Question 1. Demonstrate method overloading using a


Calculator class.
Code:

public class Calculator {


public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(2, 3));
System.out.println(calc.add(2.5, 3.5));
}
}

Sample Question 2. Provide an example of a lambda expression


using Runnable.
Code:

Java Full Stack Developer Kit (Sample) 12


public class LambdaRunnable {
public static void main(String[] args) {
Runnable task = () -> System.out.println("Lambda running in a thread");
new Thread(task).start();
}
}

Backend Development (Spring Boot,


JPA/Hibernate, Security)
Code:

Below is a comprehensive guide for the Backend Development (Spring Boot,


JPA/Hibernate, Security) section. Like the previous module, this section is
divided into two parts:

1. Concepts & Code Snippets:

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.

2. Interview Questions & Code Challenges (20+):

A set of common backend interview questions paired with code snippets to


help you understand and demonstrate your backend development skills.

Part 1: Concepts & Code Snippets


1. Spring Boot Fundamentals
Overview

Java Full Stack Developer Kit (Sample) 13


Spring Boot is a framework that simplifies Java backend development by
providing:

Auto-Configuration: Automatically configures Spring components based on


the dependencies in your project.

Standalone Applications: Run your application with an embedded server


(Tomcat, Jetty, etc.).

Starter Dependencies: Quickly add libraries and reduce boilerplate


configuration.

Example – Basic Spring Boot Application

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);
}
}

2. Building REST APIs with Spring Boot


REST Controllers
Use the @RestController annotation to define RESTful endpoints.

Example – Simple REST API

import org.springframework.web.bind.annotation.*;

Java Full Stack Developer Kit (Sample) 14


@RestController
@RequestMapping("/api")
public class GreetingController {

@GetMapping("/greeting")
public String greeting(@RequestParam(value = "name", defaultValue = "Wo
rld") String name) {
return "Hello, " + name + "!";
}
}

Exception Handling in REST APIs


You can use @ControllerAdvice to centralize exception handling.

Example – Global Exception Handler

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();
}
}

3. Persistence with JPA/Hibernate

Java Full Stack Developer Kit (Sample) 15


Overview
JPA (Java Persistence API) with Hibernate is used for object-relational mapping
(ORM) and simplifies database interactions.

JPA Entity
Annotate classes with @Entity to map them to a database table.

Example – JPA Entity for a User

import javax.persistence.*;

@Entity
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String username;


private String email;

// Constructors, Getters, and Setters


public User() { }

public User(String username, String email) {


this.username = username;
this.email = email;
}

// Getters and setters...


}

Repository Layer

Java Full Stack Developer Kit (Sample) 16


Spring Data JPA provides repository interfaces to simplify data access.

Example – UserRepository Interface

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {


// Custom query methods can be added here if needed
}

Service Layer (Optional)


Encapsulate business logic in service classes.

Example – User Service

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class UserService {

@Autowired
private UserRepository userRepository;

public List<User> getAllUsers() {


return userRepository.findAll();
}

public User createUser(User user) {


return userRepository.save(user);
}

Java Full Stack Developer Kit (Sample) 17


}

4. Securing Applications with Spring Security


Overview
Spring Security provides authentication and authorization features. It helps
protect applications from common threats like CSRF, session fixation, and more.

Basic Configuration
You can quickly secure endpoints using Java configuration.

Example – Basic Security 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()

Java Full Stack Developer Kit (Sample) 18


.httpBasic(); // Basic authentication
}
}

Advanced Concepts
JWT Authentication: For stateless REST APIs, you can use JSON Web Tokens
(JWT) for authentication.

Method-Level Security: Use annotations like @PreAuthorize and @Secured to


protect specific methods.

Part 2: Interview Questions & Code


Challenges (20+)
Sample Question 1. What is Spring Security and how do you
implement basic authentication?
Answer:
Spring Security is a framework that provides robust authentication and
authorization features. Basic authentication can be implemented via HTTP basic
by configuring HttpSecurity .
Code:

@Configuration
@EnableWebSecurity
public class BasicSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()

Java Full Stack Developer Kit (Sample) 19


.antMatchers("/api/public/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
}

Sample Question 2. How do you perform integration testing in a


Spring Boot application?
Code:

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");
}
}

Java Full Stack Developer Kit (Sample) 20


Frontend Integration (Thymeleaf &
JavaScript Frameworks)
Below is a revised, comprehensive guide for Frontend Integration – Focusing on
Backend Framework Integration. This guide is structured into two parts:

1. Concepts & Code Snippets:


Covers how to integrate your frontend with your backend framework (using
Spring Boot) via Thymeleaf templates and RESTful endpoints, including topics
such as data passing, CORS configuration, and static resource management.

2. Practical Interview Questions & Code Challenges (25+):


A set of questions that focus solely on integration aspects between the
backend (Spring Boot) and the frontend. These questions cover topics such as
server-side rendering with Thymeleaf, REST API integration, CORS, static
content serving, and more—without diving into purely frontend-specific issues
like React-controlled components or client-side routing.

Part 1: Concepts & Code Snippets


1. Thymeleaf Integration with Spring Boot
a. Basic Thymeleaf Template & Controller
Template: welcome.html

<!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>

Java Full Stack Developer Kit (Sample) 21


</html>

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
}
}

b. Passing Data from Backend to Thymeleaf


Template: userList.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>

Java Full Stack Developer Kit (Sample) 22


<div th:if="${#lists.isEmpty(users)}">
<p>No users available.</p>
</div>
</body>
</html>

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";
}
}

2. REST API Integration for Frontend Consumption


a. Creating a REST API Endpoint
Controller:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController

Java Full Stack Developer Kit (Sample) 23


public class GreetingRestController {

@GetMapping("/api/greeting")
public String greeting(@RequestParam(value = "name", defaultValue = "Gu
est") String name) {
return "Hello, " + name + "!";
}
}

b. Serving Static Resources

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>

Java Full Stack Developer Kit (Sample) 24


</body>
</html>

3. Configuring CORS for Frontend Integration


To allow your frontend (which might run on a different origin) to consume backend
APIs:
Configuration Class:

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);
}
};
}
}

Java Full Stack Developer Kit (Sample) 25


Part 2: Practical Interview Questions & Code
Challenges (Integration Focus)
The following 25+ interview questions focus exclusively on how backend
frameworks (Spring Boot) integrate with frontend technologies. They include code
examples to demonstrate your ability to connect backend endpoints with frontend
requirements.

Sample Question 1. Describe how to integrate a REST API call with


a Thymeleaf page (e.g., using AJAX).
Answer: Use JavaScript (AJAX/fetch) in your Thymeleaf template to call a REST
API and update the DOM.

Example:

<!-- index.html placed in static folder -->


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AJAX Integration</title>
</head>
<body>
<h1 id="greeting">Loading...</h1>
<script>
fetch('/api/greeting?name=AJAXUser')
.then(response => response.text())
.then(text => {
document.getElementById('greeting').innerText = text;
})
.catch(error => console.error('Error:', error));
</script>
</body>

Java Full Stack Developer Kit (Sample) 26


</html>

Sample Question 2. How would you secure your REST API


endpoints that are consumed by a frontend application?
Answer: Use Spring Security to protect endpoints via HTTP Basic, JWT, or
OAuth2. Configure endpoint access rules.

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();
}
}

Java Full Stack Developer Kit (Sample) 27


Database Integration
Below is a comprehensive guide for Database Integration in a full stack Java
application. This guide is divided into two parts:

1. Concepts & Code Snippets:


Detailed explanations on integrating relational and NoSQL databases with Java
using JPA/Hibernate (and a brief mention of NoSQL options). You’ll find code
examples for entity mapping, repository creation, JPQL queries, transaction
management, and advanced mapping scenarios.

2. Practical Interview Questions & Code Challenges (20+):


A set of real-world interview questions focused on database integration
topics. Each question includes a code snippet or practical example that
demonstrates key concepts, such as entity relationships, query optimizations,
transaction management, and more.

Part 1: Concepts & Code Snippets


1. Relational Database Integration Using JPA/Hibernate

a. Basic JPA Entity Mapping


User Entity Example:

import javax.persistence.*;

@Entity
@Table(name = "users")
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

Java Full Stack Developer Kit (Sample) 28


@Column(nullable = false, unique = true)
private String username;

@Column(nullable = false)
private String email;

// Constructors
public User() { }

public User(String username, String email) {


this.username = username;
this.email = email;
}

// Getters and Setters


public Long getId() { return id; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}

b. Repository Layer with Spring Data JPA


UserRepository Interface:

import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;

public interface UserRepository extends JpaRepository<User, Long> {


// Custom query method to find a user by username
Optional<User> findByUsername(String username);

Java Full Stack Developer Kit (Sample) 29


}

c. Service Layer and Transaction Management


UserService Example:

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;

public List<User> getAllUsers() {


return userRepository.findAll();
}

@Transactional
public User createUser(User user) {
// Additional business logic can be applied here
return userRepository.save(user);
}
}

d. Advanced Mapping: One-to-Many Relationship


Example – User and Post Entities:
User Entity with One-to-Many Mapping:

Java Full Stack Developer Kit (Sample) 30


import javax.persistence.*;
import java.util.Set;

@Entity
@Table(name = "users")
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(nullable = false, unique = true)


private String username;

@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = Fe


tchType.LAZY)
private Set<Post> posts;

// Constructors, getters, setters omitted for brevity


}

Post Entity:

import javax.persistence.*;

@Entity
@Table(name = "posts")
public class Post {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

Java Full Stack Developer Kit (Sample) 31


@Column(nullable = false)
private String title;

@Column(length = 1000)
private String content;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private User user;

// Constructors, getters, setters omitted for brevity


}

e. Pagination and Sorting


Repository Method for Pagination:

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

public interface UserRepository extends JpaRepository<User, Long> {


Page<User> findAll(Pageable pageable);
}

Usage in Service:

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

public Page<User> getUsersByPage(int page, int size) {


return userRepository.findAll(PageRequest.of(page, size));

Java Full Stack Developer Kit (Sample) 32


}

f. NoSQL Integration (Brief Overview)


While JPA/Hibernate are used for relational databases, Spring Data also supports
NoSQL databases like MongoDB. For example:
MongoDB Document Example:

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;

// Constructors, getters, and setters...


}

Mongo Repository:

import org.springframework.data.mongodb.repository.MongoRepository;

public interface CustomerRepository extends MongoRepository<Customer, St


ring> {
Customer findByName(String name);
}

Java Full Stack Developer Kit (Sample) 33


Part 2: Practical Interview Questions & Code
Challenges (25+)
Below are over 25 interview questions focused on database integration. Each
question includes an explanation and a code snippet to illustrate the concept.

Sample Question 1. Describe how to write a custom query in


Spring Data JPA using JPQL.
Example Code:

java
Copy
import org.springframework.data.jpa.repository.Query;

public interface UserRepository extends JpaRepository<User, Long> {


@Query("SELECT u FROM User u WHERE u.username = ?1")
User findUserByUsername(String username);
}

Sample Question 2. How do you implement a many-to-many


relationship in JPA?
Example Code:

java
Copy
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

Java Full Stack Developer Kit (Sample) 34


private String name;

@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;

private String title;

@ManyToMany(mappedBy = "courses")
private Set<Student> students;
// Constructors, getters, setters...
}

Testing & Devops


Below is an in‐depth guide for Testing & DevOps tailored for full‐stack Java
development. This section is organized into two parts:

1. Concepts & Code Snippets – covering unit tests, integration tests, and
DevOps practices such as CI/CD pipelines and containerization.

2. Practical Interview Questions & Code Challenges (25+) – focusing on testing


frameworks, best practices, and DevOps integrations, with ample code

Java Full Stack Developer Kit (Sample) 35


examples to illustrate each concept.

Part 1: Concepts & Code Snippets


A. Testing in Java

1. Unit Testing with JUnit 5


Example – Simple Unit Test:

import static org.junit.jupiter.api.Assertions.*;


import org.junit.jupiter.api.Test;

public class CalculatorTest {

// A simple method to add two numbers


public int add(int a, int b) {
return a + b;
}

@Test
public void testAdd() {
CalculatorTest calc = new CalculatorTest();
assertEquals(5, calc.add(2, 3), "2 + 3 should equal 5");
}
}

2. Mocking with Mockito


Example – Mocking a Service Dependency:

import static org.mockito.Mockito.*;


import static org.junit.jupiter.api.Assertions.*;

Java Full Stack Developer Kit (Sample) 36


import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

public class UserServiceTest {

@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);

User created = userService.createUser(user);


assertEquals("john_doe", created.getUsername());
verify(userRepository, times(1)).save(user);
}
}

3. Integration Testing with Spring Boot


Example – Integration Test Using @SpringBootTest:

import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.beans.factory.annotation.Autowired;

Java Full Stack Developer Kit (Sample) 37


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 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");
}
}

4. Using an In-Memory Database for Testing


Example – Configuring H2 for Tests (application-test.properties):

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.hibernate.ddl-auto=create-drop

This enables rapid test cycles with an in-memory database.

B. DevOps Practices

1. Continuous Integration/Continuous Deployment (CI/CD)


Jenkins Pipeline Example (Jenkinsfile):

Java Full Stack Developer Kit (Sample) 38


pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'mvn clean install'
}
}
stage('Test') {
steps {
sh 'mvn test'
}
}
stage('Package') {
steps {
sh 'mvn package'
}
}
stage('Deploy') {
steps {
// Deploy to a staging server (this is a placeholder)
sh 'scp target/myapp.jar user@staging-server:/deployments/'
}
}
}
post {
always {
junit '**/target/surefire-reports/*.xml'
}
}
}

Java Full Stack Developer Kit (Sample) 39


2. Containerization with Docker
Example – Dockerfile for a Spring Boot Application:

# Use an OpenJDK runtime as a parent image


FROM openjdk:17-jdk-alpine

# Set the working directory inside the container


WORKDIR /app

# Copy the packaged jar file into the container


COPY target/myapp.jar myapp.jar

# Expose the port the app runs on


EXPOSE 8080

# Run the jar file


ENTRYPOINT ["java", "-jar", "myapp.jar"]

Example – Docker Compose for Multi-Service Setup:

version: '3.8'
services:
app:
build: .
ports:
- "8080:8080"
environment:
- SPRING_PROFILES_ACTIVE=prod
db:
image: postgres:13
environment:
POSTGRES_USER: user

Java Full Stack Developer Kit (Sample) 40


POSTGRES_PASSWORD: pass
POSTGRES_DB: mydb
ports:
- "5432:5432"

3. Code Coverage with JaCoCo


Maven Configuration (pom.xml snippet):

<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>

Java Full Stack Developer Kit (Sample) 41


Part 2: Practical Interview Questions & Code
Challenges (25+)
Below are over 25 interview questions focused on testing and DevOps integration
for backend Java applications. Each question is paired with a brief explanation
and code snippet where applicable.

1. Sample Question : How do you write parameterized tests in JUnit 5?


Answer: Use @ParameterizedTest along with a source annotation (e.g.,
@ValueSource ).

Example:

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.*;

public class ParameterizedExampleTest {


@ParameterizedTest
@ValueSource(ints = {1, 2, 3, 4})
void testIsPositive(int number) {
assertTrue(number > 0);
}
}

Machine Coding Rounds


Machine coding rounds require you to design and code a complete, working
solution for a system or a component. Unlike algorithmic challenges (like DSA
problems), these questions focus on creating a small, well-architected system that
may involve data structures, multi-threading, or integration of various
components.

Java Full Stack Developer Kit (Sample) 42


Selected Sample Question with Detailed Code Example
Example: Implement an LRU (Least Recently Used) Cache
Problem Statement:
Design and implement an LRU cache with the following operations:

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.

Sample Code Implementation:

import java.util.*;

public class LRUCache {


private final int capacity;
private Map<Integer, Integer> cache;
private LinkedList<Integer> order;

public LRUCache(int capacity) {


this.capacity = capacity;
this.cache = new HashMap<>();
this.order = new LinkedList<>();
}

public int get(int key) {


if (!cache.containsKey(key)) {
return -1;
}
// Move key to front (most recently used)
order.remove((Integer) key);
order.addFirst(key);

Java Full Stack Developer Kit (Sample) 43


return cache.get(key);
}

public void put(int key, int value) {


if (cache.containsKey(key)) {
order.remove((Integer) key);
} else if (cache.size() == capacity) {
int leastUsed = order.removeLast();
cache.remove(leastUsed);
}
cache.put(key, value);
order.addFirst(key);
}

// For testing purposes


public static void main(String[] args) {
LRUCache cache = new LRUCache(2);
cache.put(1, 1);
cache.put(2, 2);
System.out.println(cache.get(1)); // returns 1
cache.put(3, 3); // evicts key 2
System.out.println(cache.get(2)); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
System.out.println(cache.get(1)); // returns -1 (not found)
System.out.println(cache.get(3)); // returns 3
System.out.println(cache.get(4)); // returns 4
}
}

Explanation:

Data Structures: A HashMap is used for O(1) access to values, and a LinkedList

maintains the usage order.

get Method: Moves the key to the front of the list on access.

Java Full Stack Developer Kit (Sample) 44


put Method: Checks if the key already exists (updates the order) or if the
capacity is full (removes the least recently used element).

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.

Sample Question 2. Implement a Thread Pool

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;

public ThreadPool(int numThreads) {


for (int i = 0; i < numThreads; i++) {
Worker worker = new Worker();
workers.add(worker);
new Thread(worker, "Worker-" + i).start();
}
}

public void submit(Runnable task) {


if (!isShutdown) {
taskQueue.offer(task);
}
}

Java Full Stack Developer Kit (Sample) 45


public void shutdown() {
isShutdown = true;
for (Worker worker : workers) {
worker.stop();
}
}

private class Worker implements Runnable {


private volatile boolean running = true;
public void run() {
while (running) {
try {
Runnable task = taskQueue.poll(100, TimeUnit.MILLISECONDS);
if (task != null) {
task.run();
}
} catch (InterruptedException e) { Thread.currentThread().interrupt
(); }
}
}
public void stop() { running = 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();
}
}

Java Full Stack Developer Kit (Sample) 46


Frontend Development
HTML & CSS Interview Questions With Solutions &
Code Snippets (25 Questions)

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;

Java Full Stack Developer Kit (Sample) 47


}
@media (max-width: 600px) {
.navbar ul {
flex-direction: column;
}
.navbar li {
margin: 10px 0;
}
}

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:

<!-- Inline style example -->


<div style="color: blue;">Text</div>
<!-- Override with !important -->
<style>
div {
color: red !important;
}
</style>

Java Full Stack Developer Kit (Sample) 48


More questions in full version. Checkout here : https://parikh.club/3RbL5D7

JavaScript Fundamentals With Solutions & Code Snippets (20


Questions)

1. Sample Question: What is event bubbling and capturing in JavaScript?


(Intermediate)
Answer:

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:

// Bubbling phase (default)


document.getElementById("child").addEventListener("click", () => {
console.log("Child clicked");
}, false);

// Capturing phase
document.getElementById("child").addEventListener("click", () => {
console.log("Child clicked");
}, true);

2. Sample Question: What is memoization in JavaScript and how can it be


implemented? (Advanced)

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:

Java Full Stack Developer Kit (Sample) 49


function memoize(fn) {
const cache = {};
return function(...args) {
const key = JSON.stringify(args);
if (cache[key]) {
return cache[key];
}
const result = fn(...args);
cache[key] = result;
return result;
}
}
const factorial = memoize(function(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
});
console.log(factorial(5)); // 120

More questions in full version. Checkout here : https://parikh.club/3RbL5D7

Advanced JavaScript & ES6+ (20 Questions)


1. Sample Question: What are generator functions in JavaScript and how do
they differ from regular functions? (Advanced)
Answer: Generator functions can pause and resume execution using the yield
keyword. They return an iterator that produces a sequence of values on
demand.
Code Example:

function* numberGenerator() {
let num = 0;
while (true) {
yield num++;
}

Java Full Stack Developer Kit (Sample) 50


}
const gen = numberGenerator();
console.log(gen.next().value); // 0
console.log(gen.next().value); // 1

2. Sample Question: Explain the concept of iterators and the Symbol.iterator


property. (Advanced)
Answer: Iterators are objects with a next() method that returns { value, done }.
An object is iterable if it implements the Symbol.iterator method, which returns
such an iterator.

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);
}

Java Full Stack Developer Kit (Sample) 51


More questions in full version. Checkout here : https://parikh.club/3RbL5D7

React Interview Questions With Solutions & Code Snippets (20


questions)
1. Sample Question: How do you implement lazy loading of components using
React.lazy and Suspense? (Intermediate)
Answer:
Lazy loading delays loading a component until it is needed. React.lazy and
Suspense work together to load components asynchronously with a fallback
UI while loading.
Code Example:

import React, { Suspense } from 'react';


const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
export default App;

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.

Java Full Stack Developer Kit (Sample) 52


Code Example:

import React, { createContext, useState } from 'react';


const ThemeContext = createContext();
function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
export { ThemeContext, ThemeProvider };

More questions in full version. Checkout here : https://parikh.club/3RbL5D7

Angular Interview Questions With Solutions & Code Snippets (20


questions)

1. Sample Question: How do you share data between Angular components


using services? (Intermediate)
Answer: Angular services are singleton objects that can be injected into
multiple components to share data and logic.
Code Example:

import { Injectable } from '@angular/core';


@Injectable({
providedIn: 'root'
})

Java Full Stack Developer Kit (Sample) 53


export class SharedService {
data: string = 'Shared Data';
}
// In a component:
import { Component } from '@angular/core';
import { SharedService } from './shared.service';
@Component({
selector: 'app-shared',
template: `<p>{{ sharedService.data }}</p>`
})
export class SharedComponent {
constructor(public sharedService: SharedService) { }
}

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:

const routes: Routes = [


{
path: 'feature',
loadChildren: () => import('./feature/feature.module').then(m => m.Featur
eModule)
}
];

More questions in full version. Checkout here : https://parikh.club/3RbL5D7

Vue JS Interview Questions With Solutions & Code Snippets ( 20


questions)

Java Full Stack Developer Kit (Sample) 54


1. Sample Question: How do you pass data from a parent component to a child
component in Vue? (Intermediate)
Answer:
Data is passed from a parent to a child using props. The child component
declares the props it expects, and the parent binds data to those props.
Code Example:

// Child Component (Greeting.vue)


<template>
<h2>Hello, {{ name }}!</h2>
</template>
<script>
export default {
props: ['name']
}
</script>

// Parent Component
<template>
<div>
<Greeting name="Alice" />
</div>
</template>
<script>
import Greeting from './Greeting.vue';
export default {
components: { Greeting }
}
</script>

2. Sample Question: How do you implement lazy loading of Vue components,


and what are the benefits? (Advanced)

Java Full Stack Developer Kit (Sample) 55


Answer:
Lazy loading in Vue is achieved using dynamic imports and asynchronous
components. It helps reduce the initial bundle size and improves application
load times by loading components only when needed.
Code Example:

// In a Vue component
const AsyncComponent = () => import('./components/AsyncComponent.vu
e');
export default {
components: {
AsyncComponent
},
template: `<AsyncComponent />`
}

More questions in full version. Checkout here : https://parikh.club/3RbL5D7

Build Tools & Testing With Solutions & Code Snippets(10 Questions)

1. Sample Question: What is ESLint and how do you configure it in a project?


Answer:
ESLint is a static code analysis tool that helps enforce coding standards and
catch potential errors. It is configured via a configuration file (e.g.,
.eslintrc.json) where you specify rules and environments.
Code Example:

// .eslintrc.json
{
"env": {

Java Full Stack Developer Kit (Sample) 56


"browser": true,
"node": true,
"es6": true},
"extends": "eslint:recommended",
"rules": {
"semi": ["error", "always"],
"quotes": ["error", "single"]
}
}

2. Sample Question: How do you set up end-to-end testing with Cypress?


Answer:
Cypress is an end-to-end testing framework that runs tests directly in the
browser. It provides an interactive interface for writing tests that simulate real
user interactions.
Code Example:

// cypress/integration/sample_spec.js
describe('My First Test', () => {
it('Visits the app and checks content', () => {
cy.visit('http://localhost:3000');
cy.contains('Welcome');
});
});

More questions in full version. Checkout here : https://parikh.club/3RbL5D7

Performance Optimization & Best Practices With Solutions &


Code Snippets(20 Questions)

Java Full Stack Developer Kit (Sample) 57


1. Sample Question: How can Web Workers improve JavaScript performance?

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');
};

2. Sample Question: How can you optimize animations for smoother


performance?

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;

Java Full Stack Developer Kit (Sample) 58


}

More questions in full version. Checkout here : https://parikh.club/3RbL5D7

Machine Coding Round Questions With Solutions And Code


Snippets - Frontend (20 questions)

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:

const countdownDate = new Date("Dec 31, 2025 23:59:59").getTime();


const timerInterval = setInterval(() => {
const now = new Date().getTime();
const distance = countdownDate - now;
if (distance < 0) {
clearInterval(timerInterval);
document.getElementById("timer").innerHTML = "EXPIRED";

Java Full Stack Developer Kit (Sample) 59


return;
}
document.getElementById("days").innerText = Math.floor(distance / (1000 *
60 * 60 * 24));
document.getElementById("hours").innerText = Math.floor((distance % (100
0 * 60 * 60 * 24)) / (1000 * 60 * 60));
document.getElementById("minutes").innerText = Math.floor((distance % (10
00 * 60 * 60)) / (1000 * 60));
document.getElementById("seconds").innerText = Math.floor((distance % (1
000 * 60)) / 1000);
}, 1000);

──────────────────────────────
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;

Java Full Stack Developer Kit (Sample) 60


padding: 10px;
}
#item-list li {
margin-bottom: 20px;
}
#item-list img {
width: 100%;
display: block;
opacity: 0;
transition: opacity 0.5s ease-in;
}
#item-list img.visible {
opacity: 1;
}

JavaScript:

const container = document.getElementById('infinite-scroll-container');


const list = document.getElementById('item-list');

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++;

Java Full Stack Developer Kit (Sample) 61


};

const lazyLoadImages = () => {


const images = document.querySelectorAll('img[data-src]');
const observer = new IntersectionObserver((entries, obs) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
img.classList.add('visible');
obs.unobserve(img);
}
});
}, { threshold: 0.1 });
images.forEach(img => observer.observe(img));
};

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([]);

Java Full Stack Developer Kit (Sample) 62


const [page, setPage] = useState(1);
const containerRef = useRef(null);

const loadItems = () => {


const newItems = [];
for (let i = 0; i < 10; i++) {
newItems.push({
id: page * 10 + i,
text: `Item ${page * 10 + i}`,
image: `https://via.placeholder.com/400x200?text=Item+${page * 10 + i}`,
});
}
setItems(prev => [...prev, ...newItems]);
setPage(prev => prev + 1);
};

// Lazy load images using Intersection Observer


useEffect(() => {
const images = document.querySelectorAll('img[data-src]');
const observer = new IntersectionObserver((entries, obs) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
img.classList.add('visible');
obs.unobserve(img);
}
});
}, { threshold: 0.1 });
images.forEach(img => observer.observe(img));
return () => observer.disconnect();
}, [items]);

const handleScroll = () => {


if (containerRef.current) {
const { scrollTop, clientHeight, scrollHeight } = containerRef.current;

Java Full Stack Developer Kit (Sample) 63


if (scrollTop + clientHeight >= scrollHeight - 10) {
loadItems();
}
}
};

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>
);
}

export default InfiniteScroll;

More questions in full version. Checkout here : https://parikh.club/3RbL5D7

Java Full Stack Developer Kit (Sample) 64


50+ Important Code snippets for Frontend Developer (HTML,
CSS, Javascript, React, Angular, Vue)
──────────────────────────────

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.

function FruitList({ fruits }) {


return (
<ul>
{fruits.map((fruit, index) => <li key={index}>{fruit}</li>)}
</ul>
);

Java Full Stack Developer Kit (Sample) 65


}

──────────────────────────────

More snippets in full version. Checkout here : https://parikh.club/3RbL5D7

DSA Questions For Java Full Stack Developer With Leetcode links
( 100 questions)

Available in full version. Checkout here : https://parikh.club/3RbL5D7

Java Full Stack Developer Kit (Sample) 66

You might also like