Java Final Doc1
Java Final Doc1
INDEX
S.No Exercise Page Mark Sign
1 Exercise 1
2 Exercise 2
3 Exercise 3
4 Exercise 4
5 Exercise 5
6 Exercise 6
7 Exercise 7
8 Exercise 8
9 Exercise 9
10 Exercise 10
11 Exercise 11
12 Exercise 12
13 Exercise 13
14 Exercise 14
2|Page
ASSIGNMENT 1: INTRODUCTION
1]
AIM: Write the program and compile the code @ command line to execute
CODE:
ERRORS IN CODE:
OUTPUT:
2]
AIM: Write the program to print current date and time
CODE:
3|Page
ERRORS IN CODE:
OUTPUT:
3]
AIM: To simulate a conversation between Java and Python using print statements.
ALGORITHM:
1. Define a class Conversation.
2. Print name and roll number.
3. Use System.out.println to alternate dialogue lines between Java and Python.
4. Compile and run the program.
CODE:
public public class JavaPythonConversation {
public static void main(String[] args) {
System.out.println("Daphny Jessica");
System.out.println("2021503010");
4|Page
SAMPLE INPUT AND OUTPUT:
4]
AIM: To determine whether a given year is a leap year.
ALGORITHM:
1. Read the year input.
2. Check if divisible by 4.
3. If divisible by 100, check if also divisible by 400.
4. If not divisible by 100, then it's a leap year.
5. Print result.
CODE:
import java.util.Scanner;
5|Page
OUTPUT:
5]
AIM: To compute the day of the week for a given date using Zeller’s congruence.
ALGORITHM:
1. Read the month, day, and year.
2. Adjust the month and year for Zeller’s formula if month < 3.
3. Apply the Zeller’s formula.
4. Compute the day code.
5. Print the corresponding day (0 for Sunday to 6 for Saturday).
CODE:
import java.util.Scanner;
System.out.println("Daphny Jessica");
System.out.println("2021503010");
if (m < 3) {
m += 12;
y -= 1;
}
int K = y % 100;
int J = y / 100;
int h = (d + (13*(m + 1))/5 + K + K/4 + J/4 + 5*J) % 7;
int day = (h + 6) % 7;
6|Page
OUTPUT:
6]
AIM: To compute wind chill based on temperature and wind speed using the given formula.
ALGORITHM:
1. Read temperature T and wind speed v.
2. Check if T <= 50 and 3 <= v <= 120.
3. If valid, apply the wind chill formula.
4. Print the result.
5. If invalid, display an error.
CODE:
import java.util.Scanner;
System.out.println("Daphny Jessica");
System.out.println("2021503010");
7|Page
OUTPUT:
7]
AIM: To model an AND gate using a linear equation and threshold condition.
ALGORITHM:
1. Define weights W0, W1 and bias.
2. Read input values X1 and X2.
3. Compute Y using formula.
4. Check if Y > 0.5, output 1; else output 0.
5. Print the result.
CODE:
import java.util.Scanner;
System.out.println("Daphny Jessica");
System.out.println("2021503010");
8|Page
OUTPUT:
8]
AIM: To print each digit in an integer with its position from left.
ALGORITHM:
1. Read the integer.
2. Convert to string.
3. Loop through characters of string.
4. Print index and corresponding digit.
CODE:
import java.util.Scanner;
System.out.println("Daphny Jessica");
System.out.println("2021503010");
9|Page
OUTPUT:
9]
AIM: To calculate future value based on principal, rate, and years using compound interest
formula.
ALGORITHM:
1. Generate random values for principal, interest rate, and years.
2. Apply compound interest formula.
3. Print the input values and result.
CODE:
import java.util.Random;
System.out.println("Daphny Jessica");
System.out.println("2021503010");
System.out.printf("Principal: Rs %.2f\n", principal);
System.out.printf("Rate: %.2f%%\n", rate);
System.out.println("Years: " + years);
System.out.printf("Future Value: Rs %.2f\n", amount);
}
}
OUTPUT:
RESULT: The required programs have been written and executed successfully.
10 | P a g e
ASSIGNMENT 2
1]
AIM: To generate random integers, sort them, and return the number of comparisons done.
ALGORITHM:
1. Generate a 1D array of random integers between 0 and 99.
2. Use a sorting algorithm (e.g., bubble sort) to sort the array.
3. Count and store the number of comparisons.
4. Print the sorted array with indices.
5. Print the total number of comparisons made.
CODE:
import java.util.Random;
int comparisons = 0;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - i - 1; j++) {
comparisons++;
if (arr[j] > arr[j + 1]) {
int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp;
char t = charArr[j]; charArr[j] = charArr[j + 1]; charArr[j + 1] =
t;
}
}
}
System.out.println("Daphny Jessica");
System.out.println("2021503010");
System.out.println("Sorted Array with Index:");
for (int i = 0; i < arr.length; i++) {
System.out.println("Index " + i + ": " + arr[i] + " - Char: " +
charArr[i]);
}
System.out.println("Number of comparisons: " + comparisons);
}
}
OUTPUT:
11 | P a g e
2]
AIM: To count how many times each element in array B appears in array A.
ALGORITHM:
1. Generate two 1D arrays A and B with random integers.
2. For each element in B, search it in A.
3. Count occurrences and display.
4. Repeat for all elements in B.
CODE:
import java.util.Random;
System.out.println("Daphny Jessica");
System.out.println("2021503010");
OUTPUT:
4]
AIM: To create an ATM simulation allowing withdraw, deposit, and balance inquiry.
ALGORITHM:
1. Create a class ATM with balance.
2. Add methods for deposit, withdraw, and checkBalance.
3. Use a menu-driven interface in main.
4. Loop until user exits.
CODE:
import java.util.Scanner;
class ATM {
private double balance;
13 | P a g e
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Insufficient balance.");
}
}
System.out.println("Daphny Jessica");
System.out.println("2021503010");
while (true) {
System.out.println("\n1. Deposit\n2. Withdraw\n3. Check Balance\n4. Exit");
System.out.print("Choose option: ");
int choice = sc.nextInt();
switch (choice) {
case 1:
System.out.print("Enter amount: ");
atm.deposit(sc.nextDouble());
break;
case 2:
System.out.print("Enter amount: ");
atm.withdraw(sc.nextDouble());
break;
case 3:
atm.checkBalance();
break;
case 4:
System.out.println("Thank you for using the ATM.");
return;
default:
System.out.println("Invalid option.");
}
}
}
}
OUTPUT
14 | P a g e
RESULT: The required programs have been written and executed successfully.
15 | P a g e
ASSIGNMENT 3
1]
AIM: Linked list implementation in Java
CODE:
public class LinkedListDemo {
static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
Node head;
list.delete(20);
list.display();
}
}
OUTPUT:
2]
AIM: Queue implementation in Java
CODE:
public class QueueDemo {
int front, rear, capacity;
int[] queue;
17 | P a g e
public void dequeue() {
if (front == rear) {
System.out.println("Queue is empty");
return;
}
for (int i = 0; i < rear - 1; i++) {
queue[i] = queue[i + 1];
}
rear--;
}
q.dequeue();
q.display();
q.enqueue(40);
q.enqueue(50);
q.enqueue(60);
q.display();
}
}
OUTPUT:
RESULT: The required programs have been written and executed successfully.
18 | P a g e
ASSIGNMENT 4
1]
AIM: Write a java program to perform string methods by considering the given string inputs
String s1=”Welcome to Java”;
String s2=s1;
String s3=new String(“Welcome to Java”);
String s4=s1.intern();
CODE:
public class StringMethodsDemo {
public static void main(String[] args) {
String s1 = "Welcome to Java";
String s2 = s1;
String s3 = new String("Welcome to Java");
String s4 = s1.intern();
System.out.println("s1 == s2: " + (s1 == s2));
System.out.println("s1 == s3: " + (s1 == s3));
System.out.println("s1 == s4: " + (s1 == s4));
OUTPUT:
19 | P a g e
2]
AIM: Write a java program to read the string and displays the reverse of the string
CODE:
import java.util.Scanner;
scanner.close();
}
}
OUTPUT:
20 | P a g e
3]
AIM: Write a java program to count the number of occurrence of the each letter in the given
string using a single array
CODE:
import java.util.Scanner;
scanner.close();
}
}
OUTPUT:
21 | P a g e
4]
AIM: Write a java program that extracts all numbers from a given string and returns them as
a new string. For example, "a1b2c3" should return "123"
CODE:
import java.util.Scanner;
scanner.close();
}
}
OUTPUT:
5]
AIM: Write a Java program that performs string compression using the counts of repeated
characters. Example string "aabcccccaaa" would become "a2b1c5a3"
CODE:
import java.util.Scanner;
int count = 1;
22 | P a g e
for (int i = 1; i <= input.length(); i++) {
if (i == input.length() || input.charAt(i) != input.charAt(i - 1)) {
compressed.append(input.charAt(i - 1));
compressed.append(count);
count = 1;
} else {
count++;
}
}
scanner.close();
}
}
OUTPUT:
6]
AIM: Write a java program to check the given string is palindrome or not
CODE:
import java.util.Scanner;
if (input.equals(reversed)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
scanner.close();
}
}
23 | P a g e
OUTPUT:
7]
AIM: Write a java program that read a two string of the given format and compares the
string
15.10.10 is greater than 14.20.50 as 15 >14
CODE:
import java.util.Scanner;
if (!compared) {
if (parts1.length > parts2.length) {
System.out.println(v1 + " is greater than " + v2);
} else if (parts1.length < parts2.length) {
System.out.println(v2 + " is greater than " + v1);
24 | P a g e
} else {
System.out.println(v1 + " is equal to " + v2);
}
}
scanner.close();
}
}
OUTPUT:
8]
AIM: Write a java program to validate the URL (“https”, "://", "/", "?",”&”) and extracts its
components protocol, domain, path, query parameters
CODE:
import java.net.URL;
import java.util.Scanner;
try {
URL url = new URL(input);
System.out.println("Protocol: " + url.getProtocol());
System.out.println("Domain: " + url.getHost());
System.out.println("Path: " + url.getPath());
System.out.println("Query: " + url.getQuery());
if (url.getQuery() != null) {
String[] params = url.getQuery().split("&");
System.out.println("Query Parameters:");
for (String param : params) {
System.out.println(" - " + param);
}
}
} catch (Exception e) {
System.out.println("Invalid URL.");
}
scanner.close();
}
}
25 | P a g e
OUTPUT:
9]
AIM: Write a java program to create an acronym from a given phrase using 2D string array.
For example, "JVM " should return "Java Virtual Machine"
CODE:
import java.util.Scanner;
public class AcronymExpander {
public static void main(String[] args) {
String[][] acronyms = {
{"JVM", "Java Virtual Machine"},
{"API", "Application Programming Interface"},
{"OOP", "Object Oriented Programming"},
{"IDE", "Integrated Development Environment"},
{"CPU", "Central Processing Unit"}
};
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an acronym: ");
String input = scanner.nextLine().toUpperCase();
boolean found = false;
for (String[] pair : acronyms) {
if (pair[0].equals(input)) {
System.out.println(input + ": " + pair[1]);
found = true;
break;
}
}
if (!found) {
System.out.println("Acronym not found.");
}
scanner.close();
}
}
OUTPUT:
RESULT: The required programs have been written and executed successfully.
26 | P a g e
ASSIGNMENT 5
1]
AIM: Write a Java program that first reads a piece of text entered by a user on one line and
then reads a key on the second line. The program displays the frequency with which the key
has occurred in the piece of text
CODE:
import java.util.Scanner;
int count = 0;
int index = 0;
System.out.println("The key \"" + key + "\" occurred " + count + " times.");
scanner.close();
}
}
SAMPLE OUTPUT:
27 | P a g e
2]
AIM: Write a Java program as per the following specification: The input to the program is a
string. The string contains substrings 'not' and 'bad' such that 'bad' comes after 'not'. There are
only single occurrences of 'not' and 'bad'. The program outputs a string such that the whole
'not...bad' substring in the input is replaced by 'good'
CODE:
import java.util.Scanner;
scanner.close();
}
}
SAMPLE OUTPUT:
3]
AIM: Write a Java program to print the frequency of characters in a string in the given
format
CODE:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
scanner.close();
}
}
SAMPLE OUTPUT:
4]
AIM: Write a Java program to check whether an input string is a pangram or not.
CODE:
import java.util.Scanner;
public class PangramChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string:");
String input = scanner.nextLine().toLowerCase();
boolean[] seen = new boolean[26];
for (char c : input.toCharArray()) {
if (c >= 'a' && c <= 'z') {
seen[c - 'a'] = true;
}
}
boolean isPangram = true;
for (boolean b : seen) {
if (!b) {
29 | P a g e
isPangram = false;
break;
}
}
if (isPangram) {
System.out.println("The string is a pangram.");
} else {
System.out.println("The string is not a pangram.");
}
scanner.close();
}
}
SAMPLE OUTPUT:
5]
AIM: Write a Java program to design an immutable singleton class representing a Person
with properties like name and age. Ensure that only a single Person object is created, its state
and behavior remain unchanged after construction
CODE:
public final class PersonSingleton {
private static final PersonSingleton instance = new PersonSingleton("John Doe", 30);
private final String name;
private final int age;
private PersonSingleton(String name, int age) {
this.name = name;
this.age = age;
}
public static PersonSingleton getInstance() {
return instance;
}
public String getName() {
return name;
}
public int getAge() {
return age;
30 | P a g e
}
}
SAMPLE OUTPUT:
6]
AIM: Write a Java program to create a Complex Number class with the following features
CODE:
class Complex {
double real, imag;
Complex(double r, double i) {
this.real = r;
this.imag = i;
}
Complex add(Complex c) {
return new Complex(this.real + c.real, this.imag + c.imag);
}
Complex add(double r, double i) {
return new Complex(this.real + r, this.imag + i);
}
void display() {
System.out.println(real + " + " + imag + "i");
}
Complex shallowCopy() {
return this;
}
Complex deepCopy() {
return new Complex(this.real, this.imag);
}
}
class ComplexChild extends Complex {
ComplexChild(double r, double i) {
super(r, i);
}
@Override
void display() {
System.out.println("ComplexChild: " + real + " + " + imag + "i");
}
}
class ComplexGrandChild extends ComplexChild {
ComplexGrandChild(double r, double i) {
super(r, i);
}
@Override
31 | P a g e
void display() {
System.out.println("ComplexGrandChild: " + real + " + " + imag + "i");
}
}
class AnotherChild extends Complex {
AnotherChild(double r, double i) {
super(r, i);
}
}
interface Printable {
void print();
}
interface Showable {
void show();
}
class MultiInterfaceClass implements Printable, Showable {
@Override
public void print() {
System.out.println("Implemented Printable interface's print method.");
}
@Override
public void show() {
System.out.println("Implemented Showable interface's show method.");
}
}
public class ComplexDemo {
public static void main(String[] args) {
System.out.println("--- Complex Number Operations ---");
Complex c1 = new Complex(2, 3);
Complex c2 = new Complex(4, 5);
System.out.print("c1: "); c1.display();
System.out.print("c2: "); c2.display();
Complex sum = c1.add(c2);
System.out.print("c1 + c2 = "); sum.display();
Complex sum2 = c1.add(1.5, -0.5);
System.out.print("c1 + (1.5 - 0.5i) = "); sum2.display();
System.out.println();
System.out.println("--- Inheritance Examples ---");
ComplexChild cc = new ComplexChild(6, 7);
System.out.print("ComplexChild object: ");
cc.display();
ComplexGrandChild cgc = new ComplexGrandChild(8, 9);
System.out.print("ComplexGrandChild object: ");
cgc.display();
AnotherChild ac = new AnotherChild(10, 11);
System.out.print("AnotherChild object: ");
ac.display();
System.out.println();
System.out.println("--- Interface Implementation Example ---");
MultiInterfaceClass mic = new MultiInterfaceClass();
mic.print();
32 | P a g e
mic.show();
System.out.println();
SAMPLE OUTPUT:
33 | P a g e
RESULT: The required programs have been written and executed successfully.
34 | P a g e
ASSIGNMENT 6
1]
AIM: Single inheritance
CODE:
class Animal {
void eat() {
System.out.println("Animal eats");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
public class SingleInheritanceDemo {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat();
myDog.bark();
}
}
SAMPLE OUTPUT:
2]
AIM: Multilevel inheritance
CODE:
class Animal {
void eat() {
System.out.println("Animal eats");
}
}
class Mammal extends Animal {
void walk() {
System.out.println("Mammal walks");
}
}
class Labrador extends Mammal {
void color() {
System.out.println("Labrador is golden");
35 | P a g e
}
}
public class MultilevelInheritanceDemo {
public static void main(String[] args) {
Labrador myLab = new Labrador();
myLab.eat();
myLab.walk();
myLab.color();
}
}
SAMPLE OUTPUT:
3]
AIM: Hierarchical inheritance
CODE:
class Animal {
void eat() {
System.out.println("Animal eats");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
void meow() {
System.out.println("Cat meows");
}
}
public class HierarchicalInheritanceDemo {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat();
myDog.bark();
36 | P a g e
SAMPLE OUTPUT:
4]
AIM: Multiple inheritance
CODE:
interface Swimmer {
void swim();
}
interface Flyer {
void fly();
}
@Override
public void fly() {
System.out.println("Duck flies");
}
}
SAMPLE OUTPUT:
37 | P a g e
5]
AIM: Runtime polymorphism
CODE:
class Shape {
void draw() {
System.out.println("Drawing shape");
}
}
shape1.draw();
shape2.draw();
shape3.draw();
}
}
SAMPLE OUTPUT:
6]
AIM: Compile time polymorphism
CODE:
class Calculator {
int add(int a, int b) {
38 | P a g e
return a + b;
}
SAMPLE OUTPUT:
7]
AIM: Super keyword
CODE:
class Vehicle {
int speed = 50;
String type;
Vehicle(String type) {
this.type = type;
}
void displaySpeed() {
System.out.println("Vehicle speed: " + speed);
}
}
class Car extends Vehicle {
int speed = 100;
Car(int speed) {
super("Four-wheeler");
this.speed = speed;
}
void displaySpeed() {
System.out.println("Car speed: " + speed);
39 | P a g e
super.displaySpeed();
System.out.println("Vehicle speed (using super): " + super.speed);
}
}
public class SuperKeywordDemo {
public static void main(String[] args) {
Car myCar = new Car(120);
myCar.displaySpeed();
}
}
SAMPLE OUTPUT:
8]
AIM: Shallow copy
CODE:
class AddressSC {
String city;
AddressSC(String city) { this.city = city; }
@Override public String toString() { return "Address[city=" + city + "]"; }
}
class PersonSC {
String name;
AddressSC address;
PersonSC(String name, AddressSC address) { this.name = name; this.address = address; }
PersonSC shallowCopy() { return new PersonSC(this.name, this.address); }
@Override public String toString() { return "Person[name=" + name + ", " + address +
"]"; }
}
40 | P a g e
System.out.println("Shallow p2: " + p2_shallow);
System.out.println("p1.address == p2.address: " + (p1.address ==
p2_shallow.address));
}
}
SAMPLE OUTPUT:
9]
AIM: Deep copy
CODE:
class AddressDC {
String city;
AddressDC(String city) { this.city = city; }
@Override public String toString() { return "Address[city=" + city + "]"; }
}
class PersonDC {
String name;
AddressDC address;
PersonDC(String name, AddressDC address) { this.name = name; this.address = address; }
PersonDC deepCopy() { AddressDC newAddress = new AddressDC(this.address.city); return
new PersonDC(this.name, newAddress); }
@Override public String toString() { return "Person[name=" + name + ", " + address +
"]"; }
}
41 | P a g e
}
}
SAMPLE OUTPUT:
10]
AIM: Shallow cloning
CODE:
import java.util.Arrays;
SAMPLE OUTPUT:
42 | P a g e
11]
AIM: Deep cloning
CODE:
import java.util.Arrays;
SAMPLE OUTPUT:
43 | P a g e
12]
AIM: Finalize method
CODE:
class Resource {
String id;
Resource(String id) { this.id = id; System.out.println("Resource " + id + "
created."); }
@Override protected void finalize() throws Throwable { try { System.out.println(">>>
Finalizing Resource " + id + " <<<"); } finally { super.finalize(); } }
}
public class FinalizeDemo {
public static void main(String[] args) {
Resource r1 = new Resource("R1");
r1 = null;
r2 = null;
System.gc();
System.out.println("GC suggested. Finalize execution not guaranteed.");
try { Thread.sleep(100); } catch (InterruptedException ignored) {}
}
}
SAMPLE OUTPUT:
RESULT: The required programs have been written and executed successfully.
44 | P a g e
ASSIGNMENT 7
1]
AIM: Write a Java program to perform unchecked exception. Use appropriate try-catch
blocks to handle these exceptions and provide meaningful error messages
CODE:
import java.util.Scanner;
try {
System.out.print("Enter a number: ");
int num = scanner.nextInt();
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Invalid array index.");
} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
} finally {
scanner.close();
System.out.println("Program finished.");
}
}
}
SAMPLE OUTPUT:
45 | P a g e
2]
AIM: Write a Java program that demonstrates different try-catch-finally block combinations
a. Try without catch block
b. Try without finally block
c. Try with catch and finally block
d. Try with multiple catch block
e. Nested try catch finally block
f. Try with resources
CODE:
import java.io.FileInputStream;
import java.io.IOException;
47 | P a g e
SAMPLE OUTPUT:
3]
AIM: Write a Java program to create a custom exception class called InvalidMarkException
that extends Exception. Then, write a Student class with a method to set marks that throws
this custom exception if the mark is out of range (e.g., less than 0 or greater than 100)
CODE:
class InvalidMarkException extends Exception {
public InvalidMarkException(String message) {
super(message);
}
}
class Student {
private int mark;
try {
student.setMark(85);
System.out.println("Mark set to: " + student.getMark());
} catch (InvalidMarkException e) {
System.out.println("Error: " + e.getMessage());
}
48 | P a g e
}
}
SAMPLE OUTPUT:
4]
AIM: Write a Java program to illustrate the propagation of checked and unchecked
exception
CODE:
import java.io.IOException;
void method2() {
System.out.println("Inside method2 - calling method1");
try {
method1();
} catch (IOException e) {
System.out.println("Caught checked exception in method2: " + e.getMessage());
}
System.out.println("method2 finished");
}
void method3() {
System.out.println("Inside method3 - calling method2");
method2();
System.out.println("method3 finished");
}
void methodA() {
System.out.println("Inside methodA - throws ArithmeticException");
int result = 10 / 0;
System.out.println("This won't be printed");
}
void methodB() {
System.out.println("Inside methodB - calling methodA");
methodA();
System.out.println("methodB finished (won't be reached if exception occurs)");
}
49 | P a g e
void methodC() {
System.out.println("Inside methodC - calling methodB");
try {
methodB();
} catch (ArithmeticException e) {
System.out.println("Caught unchecked exception in methodC: " +
e.getMessage());
}
System.out.println("methodC finished");
}
SAMPLE OUTPUT:
5]
AIM: Write a Java program to illustrate the method overloading in exception handling
mechanism for checked and unchecked exception
CODE:
import java.util.Scanner;
50 | P a g e
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
int num = scanner.nextInt();
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Invalid array index.");
} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
} finally {
scanner.close();
System.out.println("Program finished.");
}
}
}
SAMPLE OUTPUT:
51 | P a g e
6]
AIM: Write a Java program to perform unchecked exception. Use appropriate try-catch
blocks to handle these exceptions and provide meaningful error messages
CODE:
import java.io.IOException;
import java.io.FileNotFoundException;
public class OverloadingExceptionDemo {
public void processData(String data) throws IOException {
System.out.println("Processing String data: " + data);
if (data.equals("error")) {
throw new IOException("IO error processing string");
}
}
public void processData(int data) throws FileNotFoundException {
System.out.println("Processing int data: " + data);
if (data < 0) {
throw new FileNotFoundException("File not found for negative int");
}
}
public void processData(double data) {
System.out.println("Processing double data: " + data);
if (data == 0.0) {
throw new ArithmeticException("Cannot process zero double");
}
}
public static void main(String[] args) {
OverloadingExceptionDemo demo = new OverloadingExceptionDemo();
System.out.println("--- Testing Overloaded Methods with Exceptions ---");
try {
System.out.println("\nCalling processData(String):");
demo.processData("valid data");
demo.processData("error");
} catch (IOException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
try {
System.out.println("\nCalling processData(int):");
demo.processData(100);
demo.processData(-5);
} catch (FileNotFoundException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
try {
System.out.println("\nCalling processData(double):");
demo.processData(123.45);
demo.processData(0.0);
} catch (ArithmeticException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
52 | P a g e
System.out.println("\n--- End of Demonstration ---");
}
}
SAMPLE OUTPUT:
RESULT: The required programs have been written and executed successfully.
53 | P a g e
ASSIGNMENT 8
1]
AIM: Write a Java program to create an interactive quiz form
CODE:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
String[] questions = {
"Which company created Java?",
"What year was Java created?",
"What was Java originally called?",
"Who is credited with creating Java?"
};
String[][] options = {
{"Sun Microsystems", "Starbux", "Microsoft", "Alphabet"},
{"1989", "1996", "1972", "1492"},
{"Apple", "Latte", "Oak", "Koffing"},
{"Steve Jobs", "Bill Gates", "James Gosling", "Mark Zuckerburg"}
};
char[] answers = {
'A',
'B',
'C',
'C'
};
char guess;
char answer;
int index;
int correctGuesses = 0;
int totalQuestions = questions.length;
int result;
JFrame frame = new JFrame();
JTextField textField = new JTextField();
JTextArea textArea = new JTextArea();
JButton buttonA = new JButton();
JButton buttonB = new JButton();
JButton buttonC = new JButton();
JButton buttonD = new JButton();
JLabel answerLabelA = new JLabel();
JLabel answerLabelB = new JLabel();
JLabel answerLabelC = new JLabel();
JLabel answerLabelD = new JLabel();
JTextField numberRight = new JTextField();
54 | P a g e
JTextField percentage = new JTextField();
ButtonGroup group;
public QuizGUI() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(650, 650);
frame.getContentPane().setBackground(new Color(50, 50, 50));
frame.setLayout(null);
frame.setResizable(false);
SAMPLE OUTPUT:
58 | P a g e
2]
AIM: Write a Java program to design a simple calculator
CODE:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
JFrame frame;
JTextField textField;
JButton[] numberButtons = new JButton[10];
JButton[] functionButtons = new JButton[8];
JButton addButton, subButton, mulButton, divButton;
JButton decButton, equButton, delButton, clrButton;
JPanel panel;
SimpleCalculatorGUI() {
59 | P a g e
textField.setFont(myFont);
textField.setEditable(false);
textField.setHorizontalAlignment(JTextField.RIGHT);
functionButtons[0] = addButton;
functionButtons[1] = subButton;
functionButtons[2] = mulButton;
functionButtons[3] = divButton;
functionButtons[4] = decButton;
functionButtons[5] = equButton;
functionButtons[6] = delButton;
functionButtons[7] = clrButton;
panel.add(numberButtons[1]);
panel.add(numberButtons[2]);
panel.add(numberButtons[3]);
panel.add(addButton);
panel.add(numberButtons[4]);
panel.add(numberButtons[5]);
panel.add(numberButtons[6]);
panel.add(subButton);
panel.add(numberButtons[7]);
panel.add(numberButtons[8]);
60 | P a g e
panel.add(numberButtons[9]);
panel.add(mulButton);
panel.add(decButton);
panel.add(numberButtons[0]);
panel.add(equButton);
panel.add(divButton);
frame.add(panel);
frame.add(delButton);
frame.add(clrButton);
frame.add(textField);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 == 0) {
textField.setText("Error");
return;
}
result = num1 / num2;
break;
}
textField.setText(String.valueOf(result));
num1 = result;
}
if (e.getSource() == clrButton) {
textField.setText("");
num1 = 0;
num2 = 0;
operator = '\0';
}
if (e.getSource() == delButton) {
String string = textField.getText();
textField.setText("");
for (int i = 0; i < string.length() - 1; i++) {
textField.setText(textField.getText() + string.charAt(i));
}
}
}
}
SAMPLE OUTPUT:
62 | P a g e
3]
AIM: Write a Java program to create a google account
CODE:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.concurrent.TimeUnit;
public AccountCreatorGUI() {
63 | P a g e
super("Google Account Creation (Simulation)");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
createButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();
String firstName = firstNameField.getText();
String lastName = lastNameField.getText();
64 | P a g e
String password = new String(passwordField.getPassword());
String birthdate = birthdateField.getText();
String gender = genderField.getText();
createButton.setEnabled(false);
statusArea.setText("");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
66 | P a g e
boolean weakPassword = password.equalsIgnoreCase("password") || password.length()
< 8;
boolean success = !weakPassword;
if (success) {
publish("Submission Success!");
publish("Account for '" + username + "' created successfully (simulation).");
} else {
publish("Submission Failed.");
publish("Account creation failed (simulation - e.g., weak password
detected).");
}
return success;
}
@Override
protected Boolean doInBackground() throws Exception {
if (!checkUsernameSim()) {
return false;
}
if (!solveCaptchaSim()) {
return false;
}
return submitRequestSim();
}
@Override
protected void process(List<String> chunks) {
for (String message : chunks) {
statusArea.append(message + "\n");
}
}
@Override
protected void done() {
createButton.setEnabled(true);
try {
boolean result = get();
if (result) {
statusArea.append("\n--- Process complete. ---");
} else {
statusArea.append("\n--- Process failed or aborted. ---");
}
} catch (Exception e) {
statusArea.append("\n--- An error occurred during the process: " +
e.getMessage() + " ---");
e.printStackTrace();
}
}
}
67 | P a g e
SAMPLE OUTPUT:
RESULT: The required programs have been written and executed successfully.
68 | P a g e
ASSIGNMENT 9
1]
AIM: Create a program that copies a text file using both byte streams and character streams.
Compare the performance
a. Counts the occurrences of a specific character
b. Encrypt the text
CODE:
import java.io.*;
String line;
while ((line = reader.readLine()) != null) {
String[] words = line.split("\\s+|\\p{Punct}");
for (String word : words) {
if (word.equals(WORD_TO_COUNT)) {
wordCount++;
}
}
StringBuilder encryptedLine = new StringBuilder();
for (char c : line.toCharArray()) {
encryptedLine.append(encryptChar(c));
}
writer.write(encryptedLine.toString());
writer.newLine();
}
return wordCount;
} catch (IOException e) {
System.err.println("Error during buffered character stream copy: " +
e.getMessage());
return -1;
}
}
private static int encryptByte(int b) {
char c = (char) b;
if (Character.isLetter(c)) {
char base = Character.isUpperCase(c) ? 'A' : 'a';
return base + (c - base + ENCRYPTION_SHIFT) % 26;
}
return b;
}
private static char encryptChar(char c) {
if (Character.isLetter(c)) {
char base = Character.isUpperCase(c) ? 'A' : 'a';
return (char) (base + (c - base + ENCRYPTION_SHIFT) % 26);
}
return c;
71 | P a g e
}
}
SAMPLE OUTPUT:
2]
AIM: Write a Java program to enhance the previous program by using BufferedInputStream
/ BufferedOutputStream and BufferedReader / BufferedWriter. Compare the performance
with non-buffered versions
a. Counts the occurrences of a specific word
b. Encrypt the text)
CODE:
import java.io.*;
if (countByte != -1) {
System.out.println("\n--- Byte Stream Results ---");
System.out.println("File copied to: " + byteDestFile);
System.out.println("Character '" + CHAR_TO_COUNT + "' count: " + countByte);
System.out.println("Time taken: " + durationByte + " ms");
} else {
System.out.println("\nByte Stream copy failed.");
}
if (countChar != -1) {
System.out.println("\n--- Character Stream Results ---");
System.out.println("File copied to: " + charDestFile);
System.out.println("Character '" + CHAR_TO_COUNT + "' count: " + countChar);
System.out.println("Time taken: " + durationChar + " ms");
} else {
System.out.println("\nCharacter Stream copy failed.");
}
int byteRead;
while ((byteRead = fis.read()) != -1) {
char originalChar = (char) byteRead;
if (Character.toLowerCase(originalChar) == CHAR_TO_COUNT) {
charCount++;
}
int encryptedByte = encryptByte(byteRead);
fos.write(encryptedByte);
}
return charCount;
} catch (IOException e) {
System.err.println("Error during byte stream copy: " + e.getMessage());
return -1;
}
}
73 | P a g e
int charRead;
while ((charRead = reader.read()) != -1) {
char originalChar = (char) charRead;
if (Character.toLowerCase(originalChar) == CHAR_TO_COUNT) {
charCount++;
}
char encryptedChar = encryptChar(originalChar);
writer.write(encryptedChar);
}
return charCount;
} catch (IOException e) {
System.err.println("Error during character stream copy: " + e.getMessage());
return -1;
}
}
SAMPLE OUTPUT:
RESULT: The required programs have been written and executed successfully.
74 | P a g e
ASSIGNMENT 10: WRAPPERS AND COLLECTION
1]
AIM: Write a Java program to implement two sum problem
CODE:
import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;
public class TwoSum {
public static int[] findTwoSumIndices(int[] nums, int target) {
Map<Integer, Integer> numMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (numMap.containsKey(complement)) {
return new int[] { numMap.get(complement), i };}
numMap.put(nums[i], i);}
return new int[] {}; }
public static void main(String[] args) {
int[] numbers = {2, 7, 11, 15};
int targetSum = 9;
int[] result = findTwoSumIndices(numbers, targetSum);
if (result.length == 2) {
System.out.println("Input array: " + Arrays.toString(numbers));
System.out.println("Target sum: " + targetSum);
System.out.println("Indices found: " + result[0] + ", " + result[1]);
System.out.println("Numbers: " + numbers[result[0]] + ", " +
numbers[result[1]]);
} else {
System.out.println("No two numbers found that add up to the target sum " +
targetSum);}
int[] numbers2 = {3, 2, 4};
int targetSum2 = 6;
int[] result2 = findTwoSumIndices(numbers2, targetSum2);
if (result2.length == 2) {
System.out.println("\nInput array: " + Arrays.toString(numbers2));
System.out.println("Target sum: " + targetSum2);
System.out.println("Indices found: " + result2[0] + ", " + result2[1]);
System.out.println("Numbers: " + numbers2[result2[0]] + ", " +
numbers2[result2[1]]);
} else {
System.out.println("No two numbers found that add up to the target sum " +
targetSum2);}}}
SAMPLE OUTPUT:
75 | P a g e
2]
AIM: Write a Java program to convert integer to roman numericals
CODE:
public class IntegerToRoman {
private static final int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5,
4, 1};
private static final String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL",
"X", "IX", "V", "IV", "I"};
i++;
}
return roman.toString();
}
76 | P a g e
}
}
SAMPLE OUTPUT:
3]
AIM: Write a Java program to count the number of vowels and consonants in a word
CODE:
public class VowelConsonantCounter {
public static void countVowelsConsonants(String word) {
int vowels = 0;
int consonants = 0;
String lowerCaseWord = word.toLowerCase();
for (int i = 0; i < lowerCaseWord.length(); i++) {
char ch = lowerCaseWord.charAt(i);
if (ch >= 'a' && ch <= 'z') {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
} else {
consonants++;}}}
System.out.println("Word: " + word);
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);}
public static void main(String[] args) {
String word1 = "Programming";
String word2 = "AEIOU";
String word3 = "Rhythm";
String word4 = "Hello World 123";
countVowelsConsonants(word1);
System.out.println();
countVowelsConsonants(word2);
System.out.println();
countVowelsConsonants(word3);
System.out.println();
countVowelsConsonants(word4);
}
}
SAMPLE OUTPUT:
77 | P a g e
RESULT: The required programs have been written and executed successfully.
78 | P a g e
ASSIGNMENT 10
1]
AIM: Write a Java program to implement socket programming using TCP
a. Capitalizer
CODE:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
try (
Socket socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
Scanner consoleScanner = new Scanner(System.in)
) {
System.out.println("Connected to server: " + SERVER_ADDRESS + ":" +
SERVER_PORT);
String userInput;
while (true) {
System.out.print("> ");
userInput = consoleScanner.nextLine();
writer.println(userInput);
if (userInput.equalsIgnoreCase("exit")) {
System.out.println("Exiting client.");
break;
}
} catch (UnknownHostException e) {
System.err.println("Server not found: " + e.getMessage());
} catch (IOException e) {
System.err.println("I/O error connecting to server or during communication: "
+ e.getMessage());
} catch (Exception e) {
System.err.println("An unexpected error occurred: " + e.getMessage());
} finally {
System.out.println("Client finished.");
}
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
SAMPLE OUTPUT:
b. E-mail validator
CODE:
81 | P a g e
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.regex.Pattern;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
try (
Socket socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
Scanner consoleScanner = new Scanner(System.in)
) {
System.out.println("Connected to server: " + SERVER_ADDRESS + ":" +
SERVER_PORT);
String userInput;
while (true) {
System.out.print("> ");
userInput = consoleScanner.nextLine();
writer.println(userInput);
if (userInput.equalsIgnoreCase("exit")) {
83 | P a g e
System.out.println("Exiting client.");
break;
}
} catch (UnknownHostException e) {
System.err.println("Server not found: " + e.getMessage());
} catch (IOException e) {
System.err.println("I/O error connecting to server or during communication: "
+ e.getMessage());
} catch (Exception e) {
System.err.println("An unexpected error occurred: " + e.getMessage());
} finally {
System.out.println("Client finished.");
}
}
}
SAMPLE OUTPUT:
2]
AIM: Write a Java program to implement socket programming using UDP
a. Capitalizer
CODE:
84 | P a g e
import java.io.IOException;
import java.net.*;
import java.util.Scanner;
String userInput;
while (true) {
System.out.print("> ");
userInput = consoleScanner.nextLine();
if (userInput.equalsIgnoreCase("exit")) {
System.out.println("Exiting client.");
break;
}
try {
socket.receive(receivePacket);
String serverResponse = new String(receivePacket.getData(), 0,
receivePacket.getLength()).trim();
System.out.println("Server response: " + serverResponse);
} catch (SocketTimeoutException e) {
System.err.println("No response received from server within timeout
period.");
} catch (IOException e) {
System.err.println("Error receiving data from server: " +
e.getMessage());
85 | P a g e
break;
}
}
} catch (SocketException e) {
System.err.println("Error creating or binding UDP socket: " + e.getMessage());
} catch (UnknownHostException e) {
System.err.println("Server address could not be resolved: " + e.getMessage());
} catch (IOException e) {
System.err.println("I/O error sending data: " + e.getMessage());
} catch (Exception e) {
System.err.println("An unexpected error occurred: " + e.getMessage());
} finally {
System.out.println("Client finished.");
}
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
while (true) {
try {
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer,
receiveBuffer.length);
socket.receive(receivePacket);
if (receivedData.equalsIgnoreCase("exit")) {
System.out.println("Client " + clientAddress + ":" + clientPort +
" requested exit.");
continue;
86 | P a g e
}
} catch (IOException e) {
System.err.println("I/O error during datagram handling: " +
e.getMessage());
}
}
} catch (SocketException e) {
System.err.println("Could not start UDP server on port " + PORT + ": " +
e.getMessage());
}
}
}
SAMPLE OUTPUT:
b. E-mail validator
CODE:
import java.io.IOException;
import java.net.*;
import java.util.Scanner;
public class UdpEmailValidatorClient {
private static final String SERVER_ADDRESS = "localhost";
private static final int SERVER_PORT = 9093;
private static final int BUFFER_SIZE = 1024;
private static final int TIMEOUT_MS = 5000;
public static void main(String[] args) {
87 | P a g e
System.out.println("UDP Email Validator Client started...");
System.out.println("Enter email address to validate (or type 'exit' to quit):");
try (DatagramSocket socket = new DatagramSocket();
Scanner consoleScanner = new Scanner(System.in)) {
InetAddress serverInetAddress = InetAddress.getByName(SERVER_ADDRESS);
socket.setSoTimeout(TIMEOUT_MS);
String userInput;
while (true) {
System.out.print("> ");
userInput = consoleScanner.nextLine();
byte[] sendBuffer = userInput.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendBuffer,
sendBuffer.length, serverInetAddress, SERVER_PORT);
socket.send(sendPacket);
if (userInput.equalsIgnoreCase("exit")) {
System.out.println("Exiting client.");
break;
}
byte[] receiveBuffer = new byte[BUFFER_SIZE];
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer,
receiveBuffer.length);
try {
socket.receive(receivePacket);
String serverResponse = new String(receivePacket.getData(), 0,
receivePacket.getLength()).trim();
System.out.println("Server response: " + serverResponse);
} catch (SocketTimeoutException e) {
System.err.println("No response received from server within timeout
period.");
} catch (IOException e) {
System.err.println("Error receiving data from server: " +
e.getMessage());
break;
}
}
} catch (SocketException e) {
System.err.println("Error creating or binding UDP socket: " + e.getMessage());
} catch (UnknownHostException e) {
System.err.println("Server address could not be resolved: " + e.getMessage());
} catch (IOException e) {
System.err.println("I/O error sending data: " + e.getMessage());
} catch (Exception e) {
System.err.println("An unexpected error occurred: " + e.getMessage());
} finally {
System.out.println("Client finished.");
}
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
88 | P a g e
import java.net.InetAddress;
import java.net.SocketException;
import java.util.regex.Pattern;
public class UdpEmailValidatorServer {
private static final int PORT = 9093;
private static final int BUFFER_SIZE = 1024;
private static final Pattern EMAIL_PATTERN = Pattern.compile(
"^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-
Z]{2,7}$");
public static void main(String[] args) {
System.out.println("UDP Email Validator Server started...");
try (DatagramSocket socket = new DatagramSocket(PORT)) {
byte[] receiveBuffer = new byte[BUFFER_SIZE];
while (true) {
try {
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer,
receiveBuffer.length);
socket.receive(receivePacket);
InetAddress clientAddress = receivePacket.getAddress();
int clientPort = receivePacket.getPort();
String receivedData = new String(receivePacket.getData(), 0,
receivePacket.getLength()).trim();
System.out.println("Received from " + clientAddress + ":" + clientPort
+ ": " + receivedData);
if (receivedData.equalsIgnoreCase("exit")) {
System.out.println("Client " + clientAddress + ":" + clientPort +
" requested exit.");
continue;
}
boolean isValid = EMAIL_PATTERN.matcher(receivedData).matches();
String response = isValid ? "Valid" : "Invalid";
byte[] sendBuffer = response.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendBuffer,
sendBuffer.length, clientAddress, clientPort);
socket.send(sendPacket);
System.out.println("Sent to " + clientAddress + ":" + clientPort + ":
" + response);
receiveBuffer = new byte[BUFFER_SIZE];
} catch (IOException e) {
System.err.println("I/O error during datagram handling: " +
e.getMessage());
}
}
} catch (SocketException e) {
System.err.println("Could not start UDP server on port " + PORT + ": " +
e.getMessage());
}
}
}
89 | P a g e
SAMPLE OUTPUT:
RESULT: The required programs have been written and executed successfully.
90 | P a g e
ASSIGNMENT 12
1]
AIM: Write a Java program to implement a Servlet.
Define the web.xml file or use annotations to map the servlet to a specific URL. Create a
Java class that extends HttpServlet and overrides the doGet() or doPost() methods,
depending on the type of HTTP request you want to handle. Implement business logic in the
doGet() or doPost() methods (e.g., print a message or process a form). Optionally, configure
the servlet in the web.xml (for traditional web applications) or use annotations to specify the
URL pattern the servlet will handle. Retrieve parameters (e.g., form data) from the HTTP
request using request.getParameter(). Write the response using response.getWriter(), sending
output back to the client (e.g., HTML content). Deploy the servlet on a servlet container like
Tomcat. Open a browser and visit the URL mapped to the servlet to test the functionality.
(Pom.xml ; Servlet.java ; index.jsp ; Index.html ; Web.xml)
CODE:
package com.example;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
out.println("<!DOCTYPE html>");
91 | P a g e
out.println("<html>");
out.println("<head>");
out.println(" <title>Hello Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println(" <h1>Hello, " + escapeHtml(name) + "!</h1>");
out.println(" <p>This response was generated by HelloServlet.</p>");
out.println("</body>");
out.println("</html>");
}
SAMPLE OUTPUT:
RESULT: The required programs have been written and executed successfully.
92 | P a g e
ASSIGNMENT 13
1]
AIM: Write a Java program to implement JDBC [Student info].
Load the database driver. o Create a Connection object to connect to the database.
Prepare SQL queries using Statement or PreparedStatement to interact with the database. o
Use executeQuery() for retrieving data (SELECT). Use executeUpdate() for inserting,
updating, and deleting data (INSERT, UPDATE, DELETE). Retrieve the result of the query
using ResultSet for SELECT queries. Close ResultSet, Statement, and Connection to free up
resources.
CODE:
package com.example;
import java.sql.*;
public class StudentJdbcDemo {
lives.
private static final String DB_URL = "jdbc:h2:mem:studentdb;DB_CLOSE_DELAY=-1";
private static final String DB_USER = "sa";
private static final String DB_PASSWORD = "";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
System.out.println("Connected successfully.");
stmt = conn.createStatement();
String createTableSQL = "CREATE TABLE IF NOT EXISTS students (" +
" id VARCHAR(10) PRIMARY KEY, " +
" name VARCHAR(255), " +
" gpa DECIMAL(3, 2)" +
")";
System.out.println("Executing: " + createTableSQL);
stmt.executeUpdate(createTableSQL);
System.out.println("Table 'students' created or already exists.");
stmt.close();
System.out.println("\n--- Inserting Students ---");
addStudent(conn, "S101", "Alice", 3.85);
addStudent(conn, "S102", "Bob", 3.50);
addStudent(conn, "S103", "Charlie", 3.92);
System.out.println("\n--- All Students ---");
getAllStudents(conn);
System.out.println("\n--- Get Student S102 ---");
getStudentById(conn, "S102");
System.out.println("\n--- Updating Bob's GPA ---");
updateStudentGpa(conn, "S102", 3.65);
getStudentById(conn, "S102");
93 | P a g e
System.out.println("\n--- Deleting Alice ---");
deleteStudent(conn, "S101");
System.out.println("\n--- All Students After Delete ---");
getAllStudents(conn);
94 | P a g e
public static void getStudentById(Connection conn, String studentId) throws
SQLException {
String sql = "SELECT id, name, gpa FROM students WHERE id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, studentId);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
String id = rs.getString("id");
System.out.println("Found - ID: " + id + ", Name: " + name + ", GPA: "
+ gpa);
} else {
System.out.println("Student with ID " + studentId + " not found.");
}
}
}
}
public static void updateStudentGpa(Connection conn, String id, double newGpa) throws
SQLException {
String sql = "UPDATE students SET gpa = ? WHERE id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setDouble(1, newGpa);
System.out.println("Updated GPA for ID " + id + ". Rows affected: " +
rowsAffected);
if (rowsAffected == 0) {
System.out.println("Warning: Student ID " + id + " not found for
update.");
}
}
}
public static void deleteStudent(Connection conn, String id) throws SQLException {
String sql = "DELETE FROM students WHERE id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, id);
System.out.println("Deleted student with ID " + id + ". Rows affected: " +
rowsAffected);
if (rowsAffected == 0) {
System.out.println("Warning: Student ID " + id + " not found for
deletion.");
}
}
}
}
SAMPLE OUTPUT:
95 | P a g e
RESULT: The required programs have been written and executed successfully.
96 | P a g e
ASSIGNMENT 13
1]
AIM: Write a Java program to implement JSP [Calculator, HTTP sessions, cookies]
Display a form that allows the user to input two numbers and select an arithmetic operation
(add, subtract, multiply, divide). Submit the form to the servlet to perform the calculation.
Retrieve the input values (numbers and operation) from the request. Perform the selected
arithmetic operation. Store the result of the operation in the HTTP session so that it can be
accessed later. Retrieve the existing calculation history from the session and update it with
the new calculation result. Store the updated calculation history in a cookie to persist across
sessions. Forward the result and the updated history to the JSP for display. Use cookies to
store the calculation history. The history is stored as a semicolon-separated string in the
cookie. Each time the user performs a new calculation, update the cookie with the new
history. Display the result of the calculation on the page. Display the calculation history from
both the session and the cookie. The session will store history for the current session, and the
cookie will persist history even after the browser is closed. (Web.xml ; Cookie.java ;
Cookieshttp.java ; Web.xml ; Sign.xml ; Cookie.java)
CODE:
package com.example;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/calculate")
public class CalculatorServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String HISTORY_COOKIE_NAME = "calculationHistoryCookie";
private static final String HISTORY_SESSION_ATTR = "calculationHistory";
private static final String HISTORY_DELIMITER = ";";
private static final int COOKIE_MAX_AGE = 60 * 60 * 24 * 30;
97 | P a g e
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
num1 = Double.parseDouble(num1Str);
num2 = Double.parseDouble(num2Str);
} catch (NumberFormatException e) {
error = "Invalid input: Please enter valid numbers.";
request.setAttribute("error", error);
request.getRequestDispatcher("index.jsp").forward(request, response);
return;
}
switch (operation) {
case "add":
result = num1 + num2;
calculationString = num1 + " + " + num2 + " = " + result;
break;
case "subtract":
result = num1 - num2;
calculationString = num1 + " - " + num2 + " = " + result;
break;
case "multiply":
result = num1 * num2;
calculationString = num1 + " * " + num2 + " = " + result;
break;
case "divide":
if (num2 == 0) {
error = "Cannot divide by zero.";
} else {
result = num1 / num2;
calculationString = num1 + " / " + num2 + " = " + result;
}
break;
default:
error = "Invalid operation selected.";
}
if (error != null) {
request.setAttribute("error", error);
request.getRequestDispatcher("index.jsp").forward(request, response);
98 | P a g e
return;
}
request.setAttribute("result", result);
request.getRequestDispatcher("result.jsp").forward(request, response);
}
SAMPLE OUTPUT:
RESULT: The required programs have been written and executed successfully.
100 | P a g e