0% found this document useful (0 votes)
40 views17 pages

Java Programs and Web Projects Guide

The document contains a series of programming tasks and their solutions in Java, HTML, CSS, and JavaScript. It includes implementations for calculating factorials, demonstrating inheritance, method overriding, exception handling, form validation, area calculations, constructor overloading, and creating interactive web pages. Additionally, it features a JSP and JDBC example for adding two numbers and displaying the result.

Uploaded by

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

Java Programs and Web Projects Guide

The document contains a series of programming tasks and their solutions in Java, HTML, CSS, and JavaScript. It includes implementations for calculating factorials, demonstrating inheritance, method overriding, exception handling, form validation, area calculations, constructor overloading, and creating interactive web pages. Additionally, it features a JSP and JDBC example for adding two numbers and displaying the result.

Uploaded by

Riya Changan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Pehle code notepad mai likh

Save as main class [Link]


Terminal mai type Kar
1. cd (path paste kar)
2. javac [Link]
3. java filename

Q1 Write a program to implement a class that calculates and prints the


factorial of a given number.
( save file name as [Link] )

class Factorial {
public static void main(String[] args) {
[Link] sc = new [Link]([Link]);

[Link]("Enter number: ");


int n = [Link]();
int fact = 1;

for (int i = 1; i <= n; i++) {


fact *= i;
}

[Link]("Factorial = " + fact);


[Link]();
}
}

2. Write a program to demonstrate the use of a superclass


constructor being invoked by a subclass. (save as [Link])

class Animal {
Animal() {
[Link]("Animal constructor called.");
}
}

class Dog extends Animal {


Dog() {
[Link]("Dog constructor called.");
}
}

public class Main {


public static void main(String[] args) {
Dog d = new Dog();
}
}
3. Write a program to implement method overriding in a class. (save
as [Link])

class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}

class Dog extends Animal {


void sound() {
[Link]("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Animal a = new Dog();
[Link]();
}
}

Q4 Write a program that raises an exception when a number is divided


by zero.
(save file name as [Link] )

class Divide {
public static void main(String[] args) {
[Link] sc = new [Link]([Link]);

[Link]("Enter two numbers: ");


int a = [Link]();
int b = [Link]();

try {
[Link]("Result = " + (a / b));
} catch (ArithmeticException e) {
[Link]("Error: Cannot divide by zero!");
}

[Link]();
}
}

Q5 Write a program to create form validation for name, email,


password, and confirm password fields.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Minimal Form</title>
</head>
<body style="display: flex; justify-content: center; align-items: center; height:
100vh; margin: 0; font-family: sans-serif;">

<form onsubmit="return validateForm()">


<fieldset style="padding: 20px; border: 1px solid #ccc;">
<legend style="font-size: 1.2em; padding: 0 10px;">Register</legend>

<div id="error-message" style="color: red; min-height: 1.2em; margin-


bottom: 15px; font-size: 0.9em;"></div>

<label for="name" style="font-size: 1.1em;">Name:</label><br>


<input id="name" type="text" style="margin-bottom: 15px; width:
300px; padding: 8px; font-size: 1em;"><br>

<label for="email" style="font-size: 1.1em;">Email:</label><br>


<input id="email" type="email" style="margin-bottom: 15px; width:
300px; padding: 8px; font-size: 1em;"><br>

<label for="password" style="font-size:


1.1em;">Password:</label><br>
<input id="password" type="password" style="margin-bottom: 15px;
width: 300px; padding: 8px; font-size: 1em;"><br>

<label for="confirmPassword" style="font-size: 1.1em;">Confirm


Password:</label><br>
<input id="confirmPassword" type="password" style="margin-bottom:
20px; width: 300px; padding: 8px; font-size: 1em;"><br>

<button type="submit" style="width: 100%; padding: 10px; font-size:


1.1em;">Sign Up</button>
</fieldset>
</form>

<script>
function validateForm() {
const name = [Link]('name').[Link]();
const email = [Link]('email').[Link]();
const password = [Link]('password').value;
const confirmPassword =
[Link]('confirmPassword').value;
const errorDiv = [Link]('error-message');

// Check for empty fields


if (!name || !email || !password || !confirmPassword) {
[Link] = 'All fields are required.';
return false;
}

// Basic email validation


if ([Link]('@') === -1 || [Link]('.') === -1) {
[Link] = 'Please enter a valid email address.';
return false;
}

// Password match check


if (password !== confirmPassword) {
[Link] = 'Passwords do not match.';
return false;
}

// If all validations pass


[Link] = '';
alert('Form submitted successfully!');
return true; // allow form submission
}
</script>

</body>
</html>

Q6 Write a program to demonstrate method overloading to find the


area of a circle, rectangle, and triangle. (save file name as [Link])

class Area {

void area(double r) {
[Link]("Circle area = " + (3.14 * r * r));
}

void area(int l, int b) {


[Link]("Rectangle area = " + (l * b));
}

void area(int b, double h) {


[Link]("Triangle area = " + (0.5 * b * h));
}

public static void main(String[] args) {


Area a = new Area();
[Link](5);
[Link](4, 6);
[Link](3, 5.0);
}
}

Q7 Write a program to demonstrate constructor overloading using a


Student class and display the details of the student. (save file name as
[Link] )

class Student {

String name;
int age;

Student(String name) {
[Link] = name;
[Link] = 18; // default age
}

Student(String name, int age) {


[Link] = name;
[Link] = age;
}

// Method to display student details


void display() {
[Link]("Name: " + name + ", Age: " + age);
}

public static void main(String[] args) {


Student s1 = new Student("Alice");
Student s2 = new Student("Bob", 20);

[Link]();
[Link]();
}
}

Q8 Design a web page using HTML, CSS, and JavaScript that changes
the background color of the page when a button is pressed.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Background Color Changer</title>

<style>
body {
height: 100vh;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
font-family: sans-serif;
transition: background-color 0.5s;
}

button {
padding: 12px 25px;
font-size: 1rem;
cursor: pointer;
border-radius: 8px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<button id="changeColorBtn">Change Background Color</button>

<script>
const changeColorBtn = [Link]('changeColorBtn');

[Link]('click', () => {

const randomColor = '#' + [Link]([Link]() * 16777215)


.toString(16)
.padStart(6, '0');

[Link] = randomColor;
});
</script>
</body>
</html>

9. Design a React web application that changes the background color


of the page when a button is clicked.

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

export default function App() {


const [color, setColor] = useState('#ffffff');

useEffect(() => {
[Link] = color;
}, [color]);
const rand = () =>
'#' + ('000000' + [Link]([Link]() * 0xffffff).toString(16)).slice(-6);

return (
<main style={{ height: '100vh', display: 'grid', placeItems: 'center' }}>
<button
onClick={() => setColor(rand())}
style={{
padding: '0.6rem 1.2rem',
fontSize: '1rem',
borderRadius: '8px',
cursor: 'pointer',
border: '1px solid #ccc'
}}
>
Change background
</button>
</main>
);
}

Q10 Write a program to display a real-time digital clock on a web page.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Clock</title>
<style>
body {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background: #222;
}

#clock {
font: 5rem 'Courier New', monospace;
color: #0f0;
background: #111;
padding: 20px 40px;
border-radius: 10px;
}
</style>
</head>
<body>
<div id="clock"></div>
<script>
(function update() {
[Link]('clock').textContent = new Date()
.toTimeString()
.slice(0, 8);
setTimeout(update, 1000);
})();
</script>
</body>
</html>

Q 11 Write a program to implement a simple image slider using


JavaScript.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Slider</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
font-family: sans-serif;
background-color: #f0f0f0;
}

.slider-container {
text-align: center;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
border-radius: 8px;
padding: 20px;
background-color: white;
}

img {
max-width: 500px;
height: auto;
border-radius: 8px;
margin-bottom: 15px;
}

button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
border: 1px solid #ccc;
border-radius: 5px;
margin: 0 10px;
}

button:hover {
background-color: #e2e2e2;
}
</style>
</head>
<body>
<div class="slider-container">
<img
id="slider-image"
src="[Link]
alt="Slider Image"
>
<div>
<button id="prev-btn">Previous</button>
<button id="next-btn">Next</button>
</div>
</div>

<script>
const images = [
"[Link]
"[Link]
"[Link]
"[Link]
];

let currentIndex = 0;
const sliderImage = [Link]('slider-image');
const prevBtn = [Link]('prev-btn');
const nextBtn = [Link]('next-btn');

function showImage(index) {
[Link] = images[index];
}

[Link]('click', () => {
currentIndex = (currentIndex + 1) % [Link];
showImage(currentIndex);
});

[Link]('click', () => {
currentIndex = (currentIndex - 1 + [Link]) % [Link];
showImage(currentIndex);
});
</script>
</body>
</html>

12. Write a program using JSP and JDBC to add two numbers and
display the output.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Numbers</title>
<style>
body {
font-family: Arial, sans-serif;
display: grid;
place-items: center;
min-height: 100vh;
background-color: #f4f4f9;
}
form {
background: #fff;
border-radius: 8px;
padding: 2rem;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
div {
margin-bottom: 1rem;
}
label {
display: block;
margin-bottom: 0.5rem;
font-weight: bold;
}
input[type="number"] {
width: 100%;
padding: 0.5rem;
border: 1px solid #ccc;
border-radius: 4px;
}
input[type="submit"] {
width: 100%;
padding: 0.75rem;
border: none;
border-radius: 4px;
background-color: #007bff;
color: white;
font-size: 1rem;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<form action="[Link]" method="POST">
<h2>JSP + JDBC Adder</h2>
<div>
<label for="num1">First Number:</label>
<input type="number" id="num1" name="num1" required>
</div>
<div>
<label for="num2">Second Number:</label>
<input type="number" id="num2" name="num2" required>
</div>
<input type="submit" value="Add and Save">
</form>
</body>
</html>

[Link]
<%@ page import="[Link].*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Addition Result</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
.result-box {
background: #fff;
border-radius: 8px;
padding: 2rem;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
display: inline-block;
}
.error {
color: red;
font-weight: bold;
}
a{
display: inline-block;
margin-top: 20px;
text-decoration: none;
padding: 10px 15px;
background-color: #007bff;
color: white;
border-radius: 4px;
}
a:hover {
background-color: #0056b3;
}
</style>
</head>
<body>

<div class="result-box">
<%
String dbDriver = "[Link]";
String dbUrl = "jdbc:mysql://localhost:3306/Krushna";
String dbUser = "root";
String dbPass = "Pass@123";

Connection conn = null;


PreparedStatement stmt = null;

int num1 = 0;
int num2 = 0;
int result = 0;

try {
String strNum1 = [Link]("num1");
String strNum2 = [Link]("num2");

num1 = [Link](strNum1);
num2 = [Link](strNum2);
result = num1 + num2;

[Link](dbDriver);
conn = [Link](dbUrl, dbUser, dbPass);

String sql = "INSERT INTO calculations (num1, num2, result) VALUES (?, ?, ?)";
stmt = [Link](sql);
[Link](1, num1);
[Link](2, num2);
[Link](3, result);

int rowsAffected = [Link]();

if (rowsAffected > 0) {
[Link]("<h2>Calculation Successful!</h2>");
[Link]("<h3>" + num1 + " + " + num2 + " = " + result + "</h3>");
[Link]("<p>This result has been saved to the database.</p>");
} else {
[Link]("<h2 class='error'>Error</h2>");
[Link]("<p>The calculation was performed, but failed to save to the
database.</p>");
}

} catch (NumberFormatException e) {
[Link]("<h2 class='error'>Input Error</h2>");
[Link]("<p>Please enter valid numbers.</p>");
[Link]([Link]());
} catch (SQLException se) {
[Link]("<h2 class='error'>Database Error</h2>");
[Link]("<p>A database error occurred.</p>");
[Link]([Link]());
} catch (Exception e) {
[Link]("<h2 class='error'>General Error</h2>");
[Link]("<p>An unexpected error occurred.</p>");
[Link]([Link]());
} finally {
try {
if (stmt != null) [Link]();
} catch (SQLException se2) {}
try {
if (conn != null) [Link]();
} catch (SQLException se) {
[Link]([Link]());
}
}
%>

<a href="[Link]">Try Again</a>


</div>

</body>
</html>
Q13 Write a JavaScript function to find the highest marks and the
student who scored them.

<!DOCTYPE html>
<html lang="en">
<body>
<script>
const studentMarks = [
{ name: "Alice", marks: 85 },
{ name: "Bob", marks: 92 },
{ name: "Charlie", marks: 78 },
{ name: "David", marks: 95 },
{ name: "Eve", marks: 88 }
];

function findTopStudent(students) {
if (![Link]) {
return "No student data.";
}
const topStudent = [Link]((best, current) => {
return ([Link] > [Link]) ? current : best;
});
return `Highest marks: ${[Link]} (${[Link]})`;
}

[Link](findTopStudent(studentMarks));
</script>
</body>
</html>

14. Write a program to implement HTTP servlets.

// File name: [Link]

import [Link].*;
import [Link].*;
import [Link].*;

public class HelloServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

[Link]("text/html");

PrintWriter out = [Link]();

[Link]("<html>");
[Link]("<head><title>HTTP Servlet Example</title></head>");
[Link]("<body style='font-family: Arial; text-align: center;'>");
[Link]("<h2>Welcome to Java HTTP Servlet Example!</h2>");
[Link]("<p>This servlet is executed using the doGet() method.</p>");
[Link]("</body>");
[Link]("</html>");
}
}

15. Create a “View Student” page that fetches student details from
MySQL and displays them in a table on the webpage.

<%@ page import="[Link].*" %>


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Student Details</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
text-align: center;
padding: 2rem;
}

h2 {
color: #333;
}

table {
width: 80%;
margin: 2rem auto;
border-collapse: collapse;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
background: #fff;
border-radius: 8px;
overflow: hidden; /* Keeps rounded corners */
}

th, td {
padding: 1rem;
border-bottom: 1px solid #ddd;
text-align: left;
}

th {
background-color: #007bff;
color: white;
text-transform: uppercase;
font-size: 0.9rem;
}

tr:nth-child(even) {
background-color: #f9f9f9;
}

tr:hover {
background-color: #f1f1f1;
}
</style>
</head>

<body>
<h2>Student List</h2>

<table>
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Major</th>
</tr>
</thead>

<tbody>
<%
String dbDriver = "[Link]";
String dbUrl = "jdbc:mysql://localhost:3006/Krushna";
String dbUser = "root";
String dbPass = "Pass@123";

Connection conn = null;


Statement stmt = null;
ResultSet rs = null;

try {
[Link](dbDriver);
conn = [Link](dbUrl, dbUser, dbPass);
stmt = [Link]();
String sql = "SELECT id, first_name, last_name, email, major FROM
students";
rs = [Link](sql);

while ([Link]()) {
[Link]("<tr>");
[Link]("<td>" + [Link]("id") + "</td>");
[Link]("<td>" + [Link]("first_name") + "</td>");
[Link]("<td>" + [Link]("last_name") + "</td>");
[Link]("<td>" + [Link]("email") + "</td>");
[Link]("<td>" + [Link]("major") + "</td>");
[Link]("</tr>");
}
} catch (Exception e) {
[Link]("<tr><td colspan='5' style='color:red;'>Error: " +
[Link]() + "</td></tr>");
} finally {
if (rs != null) [Link]();
if (stmt != null) [Link]();
if (conn != null) [Link]();
}
%>
</tbody>
</table>
</body>
</html>

You might also like