1.
Explain built-in objects in JavaScript
Built-in objects are predefined objects in JavaScript that provide ready-made properties and
methods for common programming tasks. They help developers work with data types,
perform calculations, and manipulate data without creating everything from scratch.
Common built-in objects:
● String – Handles and manipulates text.
● Number – Works with numeric values.
● Math – Performs mathematical operations.
● Date – Works with date and time.
● Array – Stores multiple values in a list.
● RegExp – Handles pattern matching.
Example:
javascript
CopyEdit
let today = new Date();
let piValue = Math.PI;
2. JS code to count negatives, positives, and zeros
javascript
CopyEdit
let numbers = [];
let pos = 0, neg = 0, zero = 0;
for (let i = 0; i < 10; i++) {
let num = parseInt(prompt("Enter number " + (i+1) + ":"));
numbers.push(num);
if (num > 0) pos++;
else if (num < 0) neg++;
else zero++;
}
document.write("Positive: " + pos + "<br>");
document.write("Negative: " + neg + "<br>");
document.write("Zero: " + zero);
3. Explain exception handling in JavaScript with
example
Exception handling allows you to handle runtime errors in JavaScript without stopping
execution.
It uses try...catch...finally:
● try – Code that might cause an error.
● catch – Handles the error.
● finally – Executes code regardless of errors.
Example:
javascript
CopyEdit
try {
let x = y + 10; // y is undefined
} catch (err) {
console.log("Error occurred: " + err.message);
} finally {
console.log("Execution finished.");
}
4. JS to check if password and confirm password
match
javascript
CopyEdit
let pass = prompt("Enter password:");
let cpass = prompt("Confirm password:");
if (pass === cpass) {
alert("Password matched!");
} else {
alert("Password does not match!");
}
5. Explain how JavaScript can hide an HTML element
You can hide an HTML element using JavaScript by changing its CSS display property.
Example:
html
CopyEdit
<p id="text">This is a paragraph.</p>
<button
onclick="document.getElementById('text').style.display='none'">
Hide Text
</button>
Explanation:
When the button is clicked, the paragraph's display property changes to "none", hiding it
from view.
6. Explain the Document Object Model (DOM) with
example
The DOM is a programming interface for HTML and XML documents. It represents the page
as a tree structure where elements are nodes. JavaScript can use the DOM to access,
modify, add, or delete HTML elements and attributes.
Example:
javascript
CopyEdit
document.getElementById("demo").innerHTML = "Updated text!";
Here, JavaScript accesses an element with id demo and changes its content.
7. Alumni form validation (all conditions)
html
CopyEdit
<form id="alumniForm">
Name: <input type="text" id="name"><br>
Address: <input type="text" id="address"><br>
DOB: <input type="date" id="dob"><br>
Email: <input type="text" id="email"><br>
<button type="button" onclick="validate()">Submit</button>
</form>
<script>
function validate() {
let name = document.getElementById("name").value;
let address = document.getElementById("address").value;
let dob = new Date(document.getElementById("dob").value);
let email = document.getElementById("email").value;
if (!name || !address || !dob || !email) {
alert("All fields are required!");
return;
}
if (!email.includes("@") || !email.includes(".")) {
alert("Invalid email format!");
return;
}
let age = new Date().getFullYear() - dob.getFullYear();
if (age < 22) {
alert("Age must be 22 or above!");
return;
}
alert("Form submitted successfully!");
}
</script>
8. Form field validation
html
CopyEdit
<form>
Name: <input type="text" id="name"><br>
Age: <input type="number" id="age"><br>
Email: <input type="text" id="email"><br>
Password: <input type="password" id="pass"><br>
<button type="button" onclick="validateForm()">Submit</button>
</form>
<script>
function validateForm() {
let name = /^[A-Za-z]+$/;
let passwordPattern =
/^(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*]).{8,}$/;
let n = document.getElementById("name").value;
let a = parseInt(document.getElementById("age").value);
let e = document.getElementById("email").value;
let p = document.getElementById("pass").value;
if (!name.test(n)) { alert("Name must contain only letters!");
return; }
if (a < 0 || a > 100) { alert("Age must be 0-100!"); return; }
if (!e.includes("@")) { alert("Invalid email!"); return; }
if (!passwordPattern.test(p)) { alert("Weak password!"); return;
}
alert("Form validated successfully!");
}
</script>
9. Drag & drop image into box
html
CopyEdit
<div id="box" ondrop="drop(event)" ondragover="allowDrop(event)"
style="width:300px;height:300px;border:2px dashed black;"></div>
<img src="image.jpg" draggable="true" ondragstart="drag(event)"
id="img1">
<script>
function allowDrop(ev) { ev.preventDefault(); }
function drag(ev) { ev.dataTransfer.setData("text", ev.target.id); }
function drop(ev) {
ev.preventDefault();
let data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
</script>
10. Event handling in JavaScript
Event handling is the process of responding to user actions or system-generated events in
JavaScript. Events include clicks, key presses, mouse movements, form submissions,
etc. Event handling uses event listeners or attributes to trigger functions.
Example:
html
CopyEdit
<button onclick="alert('Button Clicked!')">Click Me</button>
Here, the onclick event is handled by showing an alert when the button is clicked.
ASSIGNMENT C
a. What is a Servlet? Explain its life cycle in detail.
Servlet:
A servlet is a Java program that runs on a web server and handles
client requests, generating dynamic web content (usually HTML). It is
part of Java EE.
Servlet Life Cycle Methods:
1. init() – Called once when the servlet is first loaded; used for
initialization.
2. service() – Handles requests and sends responses. Called for
every client request.
3. destroy() – Called before the servlet is unloaded; used for
cleanup.
Life Cycle Flow:
● Load & Instantiate → Servlet class is loaded and an object is
created.
● Initialization (init()) → Executed once.
● Request Handling (service()) → Runs for each request (calls
doGet() / doPost() internally).
● Destruction (destroy()) → Cleans resources before shutdown.
b. JSP Program for Arithmetic Operations
jsp
CopyEdit
<%@ page language="java" %>
<html>
<body>
<%
int a =
Integer.parseInt(request.getParameter("num1"));
int b =
Integer.parseInt(request.getParameter("num2"));
out.println("Addition: " + (a + b) + "<br>");
out.println("Subtraction: " + (a - b) + "<br>");
out.println("Multiplication: " + (a * b) +
"<br>");
out.println("Division: " + (a / b) + "<br>");
%>
</body>
</html>
Explanation: Takes two numbers as input via request parameters and
performs basic arithmetic operations.
d. What are Cookies? How do they work in Servlets?
Cookies: Small pieces of data stored in the client’s browser, used to
remember information between requests.
Working in Servlets:
1. Server creates a cookie and sends it in HTTP response.
2. Browser stores the cookie.
3. Browser sends the cookie back to the server with every request.
Example:
java
CopyEdit
Cookie c = new Cookie("username", "John");
response.addCookie(c);
e. What is a Session in a Servlet? List different ways to
handle it.
Session: A session is a way to store user-specific information across
multiple requests in a web application.
Ways to handle sessions:
1. Cookies – Store session ID in browser.
2. URL Rewriting – Append session ID to URL.
3. Hidden Form Fields – Store session data in forms.
4. HttpSession API – Server-side session object to store data.
f. Session Tracking Techniques
Session tracking keeps track of a user’s requests during a visit to a
website.
Techniques:
1. Cookies – Store session ID on client-side.
2. URL Rewriting – Session ID added to URL as a parameter.
3. Hidden Form Fields – Hidden <input> fields pass session data.
4. HttpSession API – Server-managed session storage.
h. Steps to connect Java application to a database
using JDBC
1. Import JDBC package: import java.sql.*;
2. Load driver class:
Class.forName("com.mysql.cj.jdbc.Driver");
Establish connection:
java
CopyEdit
Connection con = DriverManager.getConnection(url,
user, password);
3.
4. Create statement: Statement stmt =
con.createStatement();
5. Execute query: ResultSet rs =
stmt.executeQuery("SELECT * FROM table");
6. Process results: Loop through rs to read data.
7. Close connection: con.close();
j. Short note on JSP
JSP (JavaServer Pages):
● A technology for creating dynamic web content using HTML, Java,
and JSP tags.
● Java code is embedded in HTML using <% %> tags.
● JSP is compiled into a servlet by the server before execution.
Advantages:
● Easy to write and maintain.
● Separation of HTML and Java code.
● Supports custom tags and JavaBeans.
k. What is Session Tracking? Using Cookies
Session Tracking:
The process of maintaining state (data) about a user across multiple
requests in a web application.
Using Cookies:
● Server sends a cookie with a unique session ID to the browser.
● Browser sends the cookie with every subsequent request.
● The server uses the session ID to retrieve stored user data.
Example:
java
CopyEdit
Cookie c = new Cookie("sessionId", "12345");
response.addCookie(c);