Assignment 2 - Full Stack Java (Mumbai
University)
Prepared: Comprehensive answers formatted for printing. Includes JavaScript (client-side),
Servlet/JSP (MVC), React (frontend), and Spring Boot (backend) examples.
Note: Answers are weightage-aware and focused on Full Stack Java context.
1. Define JavaScript. Explain conditional statements, loops, functions,
arrays, and objects (with examples).
JavaScript is a high-level, interpreted scripting language used for client-side and server-side
development ([Link]). It is dynamic, prototype-based, and supports functional and object-
oriented programming styles.
Conditional statements: if, else if, else, switch. Example:
// if-else example
let x = 10;
if (x > 10) {
[Link]("Greater than 10");
} else if (x === 10) {
[Link]("Equal to 10");
} else {
[Link]("Less than 10");
}
// ternary
[Link](x === 10 ? "ten" : "not ten");
Loops: for, while, do...while, for...of. Example:
for (let i = 0; i < 3; i++) [Link](i); // 0,1,2
let arr = [10, 20, 30];
for (const v of arr) [Link](v); // 10,20,30
Functions: declarations, expressions, arrow functions. Example:
function add(a,b){ return a+b; }
const square = x => x*x;
[Link](add(2,3), square(4)); // 5,16
Arrays: ordered collections with methods like push, pop, map, filter. Example:
let nums = [1,2,3];
[Link](4); // [1,2,3,4]
let even = [Link](n => n%2===0); // [2,4]
Objects: key-value pairs representing structured data. Example:
let person = {
name: "Priya",
age: 20,
greet: function() { return "Hi, I am " + [Link]; }
};
[Link]([Link]());
2. What is control flow in JavaScript? Demonstrate Math functions
([Link], [Link], etc.) with suitable programs.
Control flow is the order in which statements are executed: sequential, conditional, and
iterative. Key constructs: if/switch, loops, try/catch.
Math examples (random integer, dice roll):
// Random integer between 0 and 9
let r = [Link]([Link]() * 10);
// Random integer between min and max inclusive
function randInt(min, max){
return [Link]([Link]() * (max - min + 1)) + min;
}
// Usage: randInt(1,6) -> dice roll
3. Differentiate between Browser Object Model (BOM) and Document
Object Model (DOM). Explain DOM tree with a neat diagram.
BOM (Browser Object Model):
- Exposes browser-related objects like window, navigator, screen, location, history.
- Used to interact with browser features (URL, open windows, history).
DOM (Document Object Model):
- Standardized tree representation of HTML/XML documents; root is document.
- Used to inspect and modify page structure, style, and content.
Key differences: Scope (BOM=browser, DOM=document), Purpose, Root objects (window vs
document).
DOM Tree diagram (document -> html -> head/body -> elements):
4. Write JavaScript code to create and manipulate DOM nodes. Explain
attributes vs properties, and demonstrate table methods and DOM
traversal.
Creating/manipulating nodes: use [Link], appendChild, removeChild,
replaceChild.
Attributes vs Properties: Attributes reflect markup and are accessed via
getAttribute/setAttribute. Properties are live object properties ([Link], [Link]).
Table example and traversal:
const tbody = [Link]('#myTable tbody');
function addRow(name, age){
const tr = [Link]('tr');
[Link] = `<td>${name}</td><td>${age}</td>`;
[Link](tr);
}
addRow('Asha', 21);
5. Explain NodeIterator, TreeWalker, selector methods (getElementById,
querySelector). Create collapsible sections using DOM manipulation.
NodeIterator & TreeWalker provide programmatic traversal of the DOM tree with filters. They
are useful for complex filtering and traversal tasks.
Selectors: getElementById (fast), getElementsByClassName/getElementsByTagName (live
collections), querySelector/querySelectorAll (CSS selectors).
Collapsible sections example (client-side):
[Link]('.toggle').forEach(btn => {
[Link]('click', () => {
const content = [Link];
[Link]('hidden');
});
});
6. Explain event flow (capturing, target, bubbling). Differentiate between
inline handlers and addEventListener(). Handle a button click event
programmatically.
Event flow phases: Capturing (top-down), Target, Bubbling (bottom-up). Use
[Link]() to stop propagation.
Inline handlers mix markup and behavior and only allow one handler per attribute.
addEventListener allows multiple handlers and control over capture/bubble.
Button click example:
const btn = [Link]('btn');
[Link]('click', (e) => {
[Link]();
alert('Button clicked');
});
7. What is the event object? List its properties. Explain cross-browser
events. Demonstrate handling HTTP responses and working with JSON
using Fetch API and callbacks.
Event object contains details like type, target, currentTarget, bubbles, cancelable,
preventDefault(), stopPropagation(), clientX/Y, key, code, eventPhase.
Fetch API example:
fetch('/api/employees')
.then(res => { if(![Link]) throw new Error([Link]); return [Link](); })
.then(data => [Link](data))
.catch(err => [Link](err));
8. Explain MVC architecture. Roles of Model, View, Controller. Develop a
simple login application using MVC with servlets and JSP.
MVC separates concerns: Model (data & business logic), View (presentation - JSP), Controller
(servlets handling requests).
Folder structure example:
- WebContent/WEB-INF/[Link]
- WebContent/[Link]
- WebContent/[Link]
- src/com/example/[Link]
- src/com/example/[Link]
[Link] (form):
<form method="post" action="LoginServlet">
Username: <input name="username" /> <br/>
Password: <input name="password" type="password" /> <br/>
<button type="submit">Login</button>
</form>
LoginServlet (controller) pseudocode:
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
String u = [Link]("username");
String p = [Link]("password");
if([Link](u,p)) {
[Link]().setAttribute("user", u);
[Link]("[Link]").forward(req,res);
} else {
[Link]("error","Invalid credentials");
[Link]("[Link]").forward(req,res);
}
}
}
UserService (model) can use JDBC to check credentials from a database or a simple in-memory
map for demo.
9. What is React? Explain components, elements, state, and props with
examples.
React is a frontend library used to build UIs using components. In a full-stack Java setup, React
acts as the client-side front-end and communicates with Java backend (Servlets/Spring Boot) via
REST APIs.
Example component using state and props:
function Item({ name }) { return <li>{name}</li>; }
function ItemList() {
const [items, setItems] = [Link](['A','B']);
return (
<div>
<ul>{[Link]((it,i) => <Item key={i} name={it} />)}</ul>
<button => setItems([...items,'New'])}>Add</button>
</div>
);
}
10. Explain React Hooks (useState, useEffect), conditional rendering, and
events. Write a React program to display a list using map() with keys.
useState allows local state; useEffect handles side effects (data fetch). Conditional rendering
uses ternary or logical AND. Events are camelCase and passed as functions.
List example:
function NameList({ names }) {
return (<ul>{[Link]((n,i) => <li key={n + '-' + i}>{n}</li>)}</ul>);
}
11. Create a React form with input fields for name and email that displays
the values on submit. Demonstrate routing between two pages (Home
and About).
React form example:
function ContactForm() {
const [form, setForm] = [Link]({name:'', email:''});
const [submitted, setSubmitted] = [Link](null);
const handleChange = e => setForm({...form, [[Link]]: [Link]});
const handleSubmit = e => { [Link](); setSubmitted(form); };
return (
<form > <input name="name" value={[Link]} />
<input name="email" value={[Link]} />
<button type="submit">Submit</button>
{submitted && <div>{[Link]} - {[Link]}</div>}
</form>
);
}
Routing (React Router v6) example: BrowserRouter with Routes and Link components to
navigate between Home and About.
12. Explain microservices, dependency injection, inversion of control
(IoC). Spring annotations and Spring Boot REST API to return employee
details in JSON.
Microservices: small independent services communicating over lightweight protocols. Benefits:
modularity, scalability. Challenges: distributed complexity, observability, transactions across
services.
IoC & DI: Inversion of Control means the framework manages object creation; Dependency
Injection is providing dependencies from outside (constructor, setter, field). Spring uses IoC
container and supports @Autowired for DI.
Spring Boot REST API example:
// [Link] (model)
public class Employee {
private int id;
private String name;
private String dept;
// constructors, getters, setters
}
// [Link]
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
private List<Employee> employees = new ArrayList<>();
public EmployeeController() {
[Link](new Employee(1,"Asha","CS"));
[Link](new Employee(2,"Rohit","IT"));
}
@GetMapping
public List<Employee> getAll() { return employees; }
@GetMapping("/{id}")
public Employee getById(@PathVariable int id) {
return [Link]().filter(e -> [Link]()==id).findFirst().orElse(null);
}
}
Prepared for: Second Year BE - Mumbai University.
Prepared by: (Your Name)