Advanced JAVA and J2EE - PartALabPrograms
Advanced JAVA and J2EE - PartALabPrograms
PART A
1. Write a program to convert numbers into words using Enumerations with
constructors, methods and instance variables.(INPUT RANGE-0 TO 99999) EX: 36
THIRTY SIX
Code:
import java.util.*;
public class Enumeration {
private enum Units {
ZERO(""), ONE("ONE"), TWO("TWO"), THREE("THREE"), FOUR("FOUR"), FIVE("FIVE"), SIX("SIX"),
SEVEN("SEVEN"), EIGHT("EIGHT"), NINE("NINE");
Units(String word) {
this.word = word;
}
public String getWord() {
return word;
}
}
Teens(String word) {
this.word = word;
}
public String getWord() {
return word;
}
}
Tens(String word) {
this.word = word;
}
2. Find the second maximum and second minimum in a set of numbers using auto
boxing and unboxing.
Code:
import java.util.Arrays;
import java.util.Scanner;
public class SecondMinMaxFinder {
3. Write a menu driven program to create an Arraylist and perform the following
operations
I. Adding elements.
II. Sorting elements.
III. Replace an element with another.
IV. Removing an element.
V. Displaying all the elements.
VI. Adding an element between two elements.
Code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
do {
System.out.println("\n--- MENU ---");
System.out.println("1. Add elements");
System.out.println("2. Sort elements");
System.out.println("3. Replace an element");
System.out.println("4. Remove an element");
System.out.println("5. Display all elements");
System.out.println("6. Add an element between two elements");
System.out.println("7. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
addElements(arrayList, scanner);
break;
case 2:
sortElements(arrayList);
break;
case 3:
replaceElement(arrayList, scanner);
break;
case 4:
removeElement(arrayList, scanner);
break;
case 5:
displayElements(arrayList);
break;
case 6:
addBetweenElements(arrayList, scanner);
break;
case 7:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice!");
}
} while (choice != 7);
scanner.close();
}
/*
1. Setup:
● An empty ArrayList named arrayList is created to store integers.
● A Scanner object is created to read user input.
● The program enters a loop where it displays a menu of options and processes
the user's choice.
2. Menu Options:
● The menu has seven options:
1. Add elements to the ArrayList.
2. Sort the elements in the ArrayList.
3. Replace an element in the ArrayList.
4. Remove an element from the ArrayList.
5. Display all elements in the ArrayList.
6. Add an element at a specific position in the ArrayList.
7. Exit the program.
3. Loop Until Exit:
● The program keeps showing the menu and performing actions based on the
user's choice until the user selects the "Exit" option.
*/
4. Write a java program to find words with even number of characters in a string,
then swap the pair of characters in those words and also toggle the characters in a
given string
EX: Good Morning everyone
Output: oGdo vereoyen
gOOD mORNING EVERYONE
Code:
import java.util.Scanner;
public class StringManipulations {
// Method to toggle the case of each character
public static String toggleCharacters(String str) {
StringBuilder result = new StringBuilder();
// Iterating through each character in ‘str’
for (char ch : str.toCharArray()) {
if (Character.isUpperCase(ch)) {
result.append(Character.toLowerCase(ch));
} else if (Character.isLowerCase(ch)) {
result.append(Character.toUpperCase(ch));
} else {
result.append(ch);
}
}
return result.toString();
}
else {
result.append(ch);
}
● This branch handles characters that are neither uppercase nor lowercase, such as digits,
punctuation, spaces, etc.
● result.append(ch): Appends the character as it is to the result StringBuilder.
—-------------------------------------
public static String swapCharactersInEvenLengthWords(String str) {
StringBuilder result = new StringBuilder();
String[] words = str.split("\\s+");
for (String word : words) {
if (word.length() % 2 == 0) {
for (int i = 0; i < word.length() - 1; i += 2) {
result.append(word.charAt(i + 1)).append(word.charAt(i));
}
} else {
result.append(word);
}
result.append(" ");
}
return result.toString().trim();
}
1. Initialize StringBuilder:
● StringBuilder result = new StringBuilder();
● This will hold the final modified string.
2. Split the Input String into Words:
● String[] words = str.split("\\s+");
● This splits the input string into words based on one or more whitespace characters.
3. Process Each Word:
● for (String word : words) {
● Loop through each word in the words array.
4. Check for Even Length:
● if (word.length() % 2 == 0) {
● Check if the word has an even number of characters.
5. Swap Adjacent Characters in Even Length Words:
● for (int i = 0; i < word.length() - 1; i += 2) {
● Loop through the characters of the word, two at a time.
● result.append(word.charAt(i + 1)).append(word.charAt(i));
● Swap the characters at positions i and i + 1 and append them to result.
6. Handle Odd Length Words:
● If the word has an odd length, append it to result without modification.
● else { result.append(word); }
7. Append Space After Each Word:
● result.append(" ");
● Add a space after each word to separate them.
8. Trim the Final Result:
● return result.toString().trim();
● Convert StringBuilder to a string and trim any trailing spaces.
Example
Let's take the input string: "hello world abc defgh"
1. Split the String:
● words = ["hello", "world", "abc", "defgh"]
2. Process Each Word:
● "hello" (odd length):
● Append as is: "hello "
● "world" (odd length):
● Append as is: "hello world "
● "abc" (odd length):
● Append as is: "hello world abc "
● "defghi" (even length):
● Swap characters:
● First swap: 'e' and 'd' -> "ed"
● Second swap: 'g' and 'f' -> "gf"
● Third swap: 'i' and h' -> "ih"
● Append: "hello world abc edgfih "
3. Final Result:
● Trim trailing space: "hello world abc edgfih"
Output
● For the input "hello world abc defghi", the output will be "hello world abc edgfih".
*/
5. Write a Servlet program that accepts the age and name and displays if the user is
eligible for voting or not
Code:
//index.html page in Web Pages folder
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voting Eligibility Checker</title>
<style>
h2 {
color: blue;
}
label {
font-weight: bold;
}
input[type="text"],
input[type="number"] {
width: 200px;
}
input[type="submit"] {
margin: auto;
padding: 10px 20px;
cursor: pointer;
font-size: 16px;
border-radius: 5px;
}
form {
width: 400px;
padding: 10px;
background-color: lightgreen;
border: 2px solid black;
}
.message {
font-size: 18px;
font-weight: bold;
}
.message.green {
color: green;
}
.message.red {
color: red;
}
</style>
</head>
<body>
<form action="voting" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="age">Age:</label>
<input type="number" id="age" name="age" required><br><br>
<input type="submit" value="Check Voting Eligibility">
</form>
<div class="message" id="messagePlaceholder"><!-- Message will be displayed here --></div>
</body>
</html>
@WebServlet("/voting")
public class VotingServlet extends HttpServlet {
Index.html File
This is a simple HTML page with a form to input the user's name and age, and a submit button to
send the data to the servlet.
● Form: It contains input fields for the user's name and age.
● Submit Button: When clicked, it sends the form data to the servlet (VotingServlet) for
processing.
● Message Placeholder: This is an empty <div> element with the class message. The message
about voting eligibility will be displayed here dynamically.
the <form action="voting"> attribute specifies the URL or endpoint to which the form data will be
submitted when the form is submitted.
VotingServlet.java
This is a Java servlet that handles the request sent from the HTML form, processes the user's input,
and sends back a response indicating if the user is eligible to vote.
Summary:
● HTML Page (index.html): Provides a user interface to input name and age.
● Java Servlet (VotingServlet): Processes the form data, checks eligibility, and sends back a
response indicating if the user is eligible to vote.
When a user enters their name and age in the form and submits it, the servlet receives the data,
processes it, and sends back a response dynamically, informing the user about their voting eligibility.
*/
6. Write a JSP program to print the first 10 Fibonacci and 10 prime numbers.
Code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h2>Fibonacci Numbers:</h2>
<%
// Calculate and print the first 10 Fibonacci numbers
int n = 10;
int a = 0, b = 1;
out.println(a + " ");
out.println(b + " ");
for (int i = 2; i < n; i++) {
int next = a + b;
out.println(next + " c");
a = b;
b = next;
}
%>
<h2>Prime Numbers:</h2>
<%
// Calculate and print the first 10 prime numbers
int count = 0;
int num = 2;
while (count < 10) {
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
out.println(num + " ");
count++;
}
num++;
}
%>
</body>
</html>
/*
<%
// Calculate and print the first 10 Fibonacci numbers
int n = 10;
int a = 0, b = 1;
out.println(a + " ");
out.println(b + " ");
for (int i = 2; i < n; i++) {
int next = a + b;
out.println(next + " ");
a = b;
b = next;
}
%>
1. Variables Initialization:
● int n = 10;: Specifies that we want the first 10 Fibonacci numbers.
● int a = 0, b = 1;: Initializes the first two Fibonacci numbers.
2. Printing the First Two Numbers:
● out.println(a + " ");: Prints 0 followed by two non-breaking spaces.
● out.println(b + " ");: Prints 1 followed by two non-breaking spaces.
3. Loop to Generate and Print Fibonacci Numbers:
● for (int i = 2; i < n; i++) {: Starts a loop from 2 to n-1 (8 iterations).
● int next = a + b;: Calculates the next Fibonacci number.
● out.println(next + " ");: Prints the next Fibonacci number followed by
two non-breaking spaces.
● a = b;: Updates a to the previous b.
● b = next;: Updates b to the current next.
<h2>Prime Numbers:</h2>
<%
// Calculate and print the first 10 prime numbers
int count = 0;
int num = 2;
while (count < 10) {
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
out.println(num + " ");
count++;
}
num++;
}
%>
1. Variables Initialization:
● int count = 0;: Counter to keep track of how many prime numbers have been found.
● int num = 2;: Starting number to check for prime numbers.
2. While Loop to Find Prime Numbers:
● while (count < 10) {: Loops until 10 prime numbers are found.
● boolean isPrime = true;: Assumes the current number is prime.
3. Inner Loop to Check Primality:
● for (int i = 2; i <= Math.sqrt(num); i++) {: Loops from 2 to the square root of num.
● if (num % i == 0) {: Checks if num is divisible by i.
● isPrime = false;: If divisible, num is not a prime number.
● break;: Exits the loop if a divisor is found.
4. Checking and Printing Prime Numbers:
● if (isPrime) {: If num is prime.
● out.println(num + " ");: Prints the prime number followed by a space.
● count++;: Increments the prime number count.
5. Increment the Number:
● num++;: Moves to the next number to check for primality.
*/
7. Write a JSP Program to design a shopping cart to add items, remove items and to
display items from the cart using Sessions.
Code:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Shopping Cart</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
h2, h3 {
color: #333;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
table, th, td {
border: 1px solid #ddd;
}
th, td {
padding: 10px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
a{
text-decoration: none;
color: #333;
}
a:hover {
text-decoration: underline;
}
.form-container {
margin-top: 20px;
}
input[type="text"] {
width: 200px;
padding: 5px;
}
input[type="submit"] {
padding: 5px 10px;
cursor: pointer;
border: 1px solid #333;
background-color: #f2f2f2;
}
input[type="submit"]:hover {
background-color: #ddd;
}
</style>
</head>
<body>
<h2>Shopping Cart</h2>
/*
JSP tags and their purposes:
1. <% %>: Scriptlet Tags
● These tags are used to embed Java code directly into the JSP page.
● Anything written inside these tags is treated as Java code and executed on the server
side.
● Example: <% int x = 10; %>.
8. Write a Java Servlet program to Download a file and display it on the screen( A
link has to be provided in HTML, when the link is clicked the corresponding file has
to be displayed on screen).
Code:
/*This is a simple HTML file that contains a link to download a file.*/
//index.html file in Web Pages Folder
<!DOCTYPE html>
<html>
<head>
<title>File Download</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h3>Below is the link to download the File</h3>
<a href="FileDownloader?filename=myfile.txt">Download My CV</a>
</body>
</html>
/* An anchor element that creates a hyperlink to the servlet FileDownloader, with a query
parameter filename=mycv.txt.
*/
//FileDownloader.java Servlet File in Source Package Folder
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}
}
/*
response.setHeader("Content-Disposition", "attachment;filename=\"" + fname + "\"");
● Purpose: This line tells the browser how to handle the file that is being sent from the server.
● Content-Disposition: This is a header in the HTTP response that gives instructions about how
the content should be handled.
● attachment: This part of the header tells the browser that the content should be
downloaded as a file, rather than displayed directly in the browser.
● filename="fname": This part of the header suggests a name for the file when it is
downloaded. fname is a variable containing the actual name of the file. For example, if
fname is "mycv.txt", the browser will suggest saving the file as mycv.txt.
*/