0% found this document useful (0 votes)
7 views100 pages

Java Final Doc1

The document outlines a series of programming exercises and assignments primarily focused on Java, including tasks such as simulating conversations, determining leap years, calculating wind chill, and implementing data structures like linked lists and queues. Each exercise includes an aim, algorithm, and code snippets, along with sample outputs. The document concludes with a note that all required programs have been successfully written and executed.

Uploaded by

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

Java Final Doc1

The document outlines a series of programming exercises and assignments primarily focused on Java, including tasks such as simulating conversations, determining leap years, calculating wind chill, and implementing data structures like linked lists and queues. Each exercise includes an aim, algorithm, and code snippets, along with sample outputs. The document concludes with a note that all required programs have been successfully written and executed.

Uploaded by

Daphny Jessica
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 100

1|Page

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");

System.out.println("Java: Hello Python!");


System.out.println("Python: Hello Java!");
System.out.println("Java: How's it going with machine learning?");
System.out.println("Python: Pretty well! How’s JVM life?");
System.out.println("Java: Still fast and reliable.");
System.out.println("Python: Let's collaborate sometime.");
System.out.println("Java: Absolutely!");
}
}

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;

public class LeapYear {


public static void main(String[] args) {
System.out.println("Daphny Jessica");
System.out.println("2021503010");

Scanner sc = new Scanner(System.in);


System.out.print("Enter year: ");
int year = sc.nextInt();

if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {


System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
}
}

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;

public class DayOfWeek {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter month (1-12): ");
int m = sc.nextInt();
System.out.print("Enter day: ");
int d = sc.nextInt();
System.out.print("Enter year: ");
int y = sc.nextInt();

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;

System.out.println("Day of the week: " + day);


}
}

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;

public class WindChill {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter temperature (°F): ");
double T = sc.nextDouble();
System.out.print("Enter wind speed (mph): ");
double v = sc.nextDouble();

System.out.println("Daphny Jessica");
System.out.println("2021503010");

if (T <= 50 && v >= 3 && v <= 120) {


double chill = 35.74 + 0.6215 * T - 35.75 * Math.pow(v, 0.16) + 0.4275 * T
* Math.pow(v, 0.16);
System.out.printf("Wind Chill: %.2f°F\n", chill);
} else {
System.out.println("Invalid input. T must be <= 50°F and v between 3 and
120 mph.");
}
}
}

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;

public class AndGateModel {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter X1 (0 or 1): ");
int X1 = sc.nextInt();
System.out.print("Enter X2 (0 or 1): ");
int X2 = sc.nextInt();

double W0 = 0.6, W1 = 0.6, Bias = -0.9;


double Y = Bias + W0 * X1 + W1 * X2;

System.out.println("Daphny Jessica");
System.out.println("2021503010");

int output = Y > 0.5 ? 1 : 0;


System.out.println("AND Gate Output: " + output);
}
}

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;

public class DigitPosition {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter an integer: ");
String num = sc.next();

System.out.println("Daphny Jessica");
System.out.println("2021503010");

for (int i = 0; i < num.length(); i++) {


System.out.println("Position " + (i + 1) + ": " + num.charAt(i));
}
}
}

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;

public class InvestmentValue {


public static void main(String[] args) {
Random random = new Random();
double principal = 10000 + random.nextInt(90001); // 10,000 to 100,000
double rate = 1.0 + (10.0 - 1.0) * random.nextDouble(); // 1% to 10%
int years = 1 + random.nextInt(30); // 1 to 30 years

double amount = principal * Math.pow((1 + rate / 100), years);

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;

public class SortWithComparisons {


public static void main(String[] args) {
int[] arr = new int[10];
char[] charArr = new char[10];
Random rand = new Random();

for (int i = 0; i < arr.length; i++) {


arr[i] = rand.nextInt(100); // range 0-99
charArr[i] = (char) (rand.nextInt(26) + 'A');
}

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;

public class SearchOccurrences {


public static void main(String[] args) {
int n = 10;
int[] A = new int[n];
int[] B = new int[n];
Random rand = new Random();

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


A[i] = rand.nextInt(20);
B[i] = rand.nextInt(20);
}

System.out.println("Daphny Jessica");
System.out.println("2021503010");

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


int count = 0;
for (int j = 0; j < n; j++) {
12 | P a g e
if (A[j] == B[i]) {
count++;
}
}
System.out.println("Element " + B[i] + " appears " + count + " times in
A.");
}
}
}

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;

public ATM(double initialBalance) {


balance = initialBalance;
}

public void deposit(double amount) {


balance += amount;
System.out.println("Deposited: " + amount);
}

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.");
}
}

public void checkBalance() {


System.out.println("Current Balance: " + balance);
}
}

public class ATMSimulation {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ATM atm = new ATM(1000); // Starting 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;

public void insert(int data) {


Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
}

public void delete(int data) {


if (head == null) return;
if (head.data == data) {
head = head.next;
return;
}
Node temp = head;
while (temp.next != null) {
if (temp.next.data == data) {
temp.next = temp.next.next;
return;
}
temp = temp.next;
}
}

public void display() {


16 | P a g e
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " -> ");
temp = temp.next;
}
System.out.println("null");
}

public static void main(String[] args) {


LinkedListDemo list = new LinkedListDemo();
list.insert(10);
list.insert(20);
list.insert(30);
list.display();

list.delete(20);
list.display();
}
}

OUTPUT:

2]
AIM: Queue implementation in Java
CODE:
public class QueueDemo {
int front, rear, capacity;
int[] queue;

public QueueDemo(int size) {


capacity = size;
front = rear = 0;
queue = new int[capacity];
}

public void enqueue(int data) {


if (rear == capacity) {
System.out.println("Queue is full");
return;
}
queue[rear] = data;
rear++;
}

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--;
}

public void display() {


if (front == rear) {
System.out.println("Queue is empty");
return;
}
for (int i = front; i < rear; i++) {
System.out.print(queue[i] + " ");
}
System.out.println();
}

public static void main(String[] args) {


QueueDemo q = new QueueDemo(5);
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.display();

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));

System.out.println("s1.equals(s3): " + s1.equals(s3));

System.out.println("s1 length: " + s1.length());


System.out.println("s1 uppercase: " + s1.toUpperCase());
System.out.println("s1 lowercase: " + s1.toLowerCase());
System.out.println("s1 contains 'Java': " + s1.contains("Java"));
System.out.println("s1 starts with 'Welcome': " + s1.startsWith("Welcome"));
System.out.println("s1 ends with 'Java': " + s1.endsWith("Java"));
System.out.println("s1 substring(0,7): " + s1.substring(0,7));
System.out.println("s1 replace 'Java' with 'World': " + s1.replace("Java",
"World"));
}
}

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;

public class ReverseString {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();

String reversed = "";


for (int i = input.length() - 1; i >= 0; i--) {
reversed += input.charAt(i);
}

System.out.println("Reversed string: " + reversed);

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;

public class LetterFrequency {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine().toLowerCase();

int[] counts = new int[26];

for (char c : input.toCharArray()) {


if (c >= 'a' && c <= 'z') {
counts[c - 'a']++;
}
}

for (int i = 0; i < 26; i++) {


if (counts[i] > 0) {
System.out.println((char) ('a' + i) + ": " + counts[i]);
}
}

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;

public class ExtractNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();

StringBuilder numbers = new StringBuilder();


for (char c : input.toCharArray()) {
if (Character.isDigit(c)) {
numbers.append(c);
}
}

System.out.println("Extracted numbers: " + numbers.toString());

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;

public class StringCompression {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();

StringBuilder compressed = new StringBuilder();

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++;
}
}

System.out.println("Compressed string: " + compressed.toString());

scanner.close();
}
}

OUTPUT:

6]
AIM: Write a java program to check the given string is palindrome or not
CODE:
import java.util.Scanner;

public class PalindromeChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine().toLowerCase();

String reversed = new StringBuilder(input).reverse().toString();

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;

public class VersionComparator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first version string (e.g., 15.10.10): ");
String v1 = scanner.nextLine();

System.out.print("Enter second version string (e.g., 14.20.50): ");


String v2 = scanner.nextLine();

String[] parts1 = v1.split("\\.");


String[] parts2 = v2.split("\\.");

int len = Math.min(parts1.length, parts2.length);


boolean compared = false;

for (int i = 0; i < len; i++) {


int num1 = Integer.parseInt(parts1[i]);
int num2 = Integer.parseInt(parts2[i]);

if (num1 > num2) {


System.out.println(v1 + " is greater than " + v2);
compared = true;
break;
} else if (num1 < num2) {
System.out.println(v2 + " is greater than " + v1);
compared = true;
break;
}
}

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;

public class URLParser {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a URL: ");
String input = scanner.nextLine();

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;

public class KeyFrequencyInText {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter the text:");


String text = scanner.nextLine();

System.out.println("Enter the key to search:");


String key = scanner.nextLine();

int count = 0;
int index = 0;

while ((index = text.indexOf(key, index)) != -1) {


count++;
index += key.length();
}

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;

public class NotBadReplace {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string:");
String input = scanner.nextLine();

int notIndex = input.indexOf("not");


int badIndex = input.indexOf("bad");

if (notIndex != -1 && badIndex != -1 && badIndex > notIndex) {


String result = input.substring(0, notIndex) + "good" +
input.substring(badIndex + 3);
System.out.println("Modified string: " + result);
} else {
System.out.println("No change: " + input);
}

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;

public class CharacterFrequency {


public static void main(String[] args) {
28 | P a g e
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string:");
String input = scanner.nextLine();

Map<Character, Integer> freqMap = new HashMap<>();

for (char c : input.toCharArray()) {


freqMap.put(c, freqMap.getOrDefault(c, 0) + 1);
}

for (Map.Entry<Character, Integer> entry : freqMap.entrySet()) {


System.out.println("'" + entry.getKey() + "' : " + entry.getValue());
}

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;

public static void main(String[] args) {


PersonSingleton person = PersonSingleton.getInstance();
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());

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();

System.out.println("--- Shallow vs Deep Copy ---");


Complex original = new Complex(20, 30);
System.out.print("Original object: "); original.display();
Complex shallow = original.shallowCopy();
Complex deep = original.deepCopy();
System.out.print("Shallow copy object: "); shallow.display();
System.out.print("Deep copy object: "); deep.display();
original.real = 25;
original.imag = 35;
System.out.println("\nAfter modifying original object (original.real = 25):");
System.out.print("Original object: "); original.display();
System.out.print("Shallow copy object: "); shallow.display();
System.out.print("Deep copy object: "); deep.display();
System.out.println("\nAre original and shallow the same object? " + (original ==
shallow));
System.out.println("Are original and deep the same object? " + (original ==
deep));
}
}

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();

Cat myCat = new Cat();


myCat.eat();
myCat.meow();
}
}

36 | P a g e
SAMPLE OUTPUT:

4]
AIM: Multiple inheritance
CODE:
interface Swimmer {
void swim();
}

interface Flyer {
void fly();
}

class Duck implements Swimmer, Flyer {


@Override
public void swim() {
System.out.println("Duck swims");
}

@Override
public void fly() {
System.out.println("Duck flies");
}
}

public class MultipleInterfaceDemo {


public static void main(String[] args) {
Duck myDuck = new Duck();
myDuck.swim();
myDuck.fly();
}
}

SAMPLE OUTPUT:

37 | P a g e
5]
AIM: Runtime polymorphism
CODE:
class Shape {
void draw() {
System.out.println("Drawing shape");
}
}

class Circle extends Shape {


@Override
void draw() {
System.out.println("Drawing circle");
}
}

class Square extends Shape {


@Override
void draw() {
System.out.println("Drawing square");
}
}

public class RuntimePolymorphismDemo {


public static void main(String[] args) {
Shape shape1 = new Circle();
Shape shape2 = new Square();
Shape shape3 = new 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;
}

double add(double a, double b) {


return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
}
}

public class CompileTimePolymorphismDemo {


public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(5, 10));
System.out.println(calc.add(3.5, 2.1));
System.out.println(calc.add(1, 2, 3));
}
}

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 +
"]"; }
}

public class ShallowCopyDemo {


public static void main(String[] args) {
AddressSC addr1 = new AddressSC("New York");
PersonSC p1 = new PersonSC("Alice", addr1);
PersonSC p2_shallow = p1.shallowCopy();
System.out.println("Original p1: " + p1);
System.out.println("Shallow p2: " + p2_shallow);
p1.address.city = "Los Angeles";
System.out.println("After modifying p1 address:");
System.out.println("Original p1: " + p1);

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 +
"]"; }
}

public class DeepCopyDemo {


public static void main(String[] args) {
AddressDC addr1 = new AddressDC("New York");
PersonDC p1 = new PersonDC("Alice", addr1);
PersonDC p3_deep = p1.deepCopy();
System.out.println("Original p1: " + p1);
System.out.println("Deep p3: " + p3_deep);
p1.address.city = "Los Angeles";
System.out.println("After modifying p1 address:");
System.out.println("Original p1: " + p1);
System.out.println("Deep p3: " + p3_deep);
System.out.println("p1.address == p3.address: " + (p1.address ==
p3_deep.address));

41 | P a g e
}
}

SAMPLE OUTPUT:

10]
AIM: Shallow cloning
CODE:
import java.util.Arrays;

class DepartmentSClo implements Cloneable {


String name;
String[] employees;
DepartmentSClo(String name, String[] employees) { this.name = name; this.employees =
employees; }
@Override public Object clone() throws CloneNotSupportedException { return
super.clone(); }
@Override public String toString() { return "Dept[name=" + name + ", emp=" +
Arrays.toString(employees) + "]"; }
}

public class ShallowCloningDemo {


public static void main(String[] args) throws CloneNotSupportedException {
String[] staff1 = {"Bob", "Charlie"};
DepartmentSClo d1 = new DepartmentSClo("Sales", staff1);
DepartmentSClo d2_shallow = (DepartmentSClo) d1.clone();
System.out.println("Original d1: " + d1);
System.out.println("Shallow d2: " + d2_shallow);
d1.employees[0] = "Robert";
System.out.println("After modifying d1 employees:");
System.out.println("Original d1: " + d1);
System.out.println("Shallow d2: " + d2_shallow);
System.out.println("d1.employees == d2.employees: " + (d1.employees ==
d2_shallow.employees));
}
}

SAMPLE OUTPUT:

42 | P a g e
11]
AIM: Deep cloning
CODE:
import java.util.Arrays;

class DepartmentDClo implements Cloneable {


String name;
String[] employees;
DepartmentDClo(String name, String[] employees) { this.name = name; this.employees =
employees; }
@Override public Object clone() throws CloneNotSupportedException { DepartmentDClo
cloned = (DepartmentDClo) super.clone(); cloned.employees = Arrays.copyOf(this.employees,
this.employees.length); return cloned; }
@Override public String toString() { return "Dept[name=" + name + ", emp=" +
Arrays.toString(employees) + "]"; }
}

public class DeepCloningDemo {


public static void main(String[] args) throws CloneNotSupportedException {
String[] staff1 = {"Bob", "Charlie"};
DepartmentDClo d1 = new DepartmentDClo("Sales", staff1);
DepartmentDClo d3_deep = (DepartmentDClo) d1.clone();
System.out.println("Original d1: " + d1);
System.out.println("Deep d3: " + d3_deep);
d1.employees[0] = "Robert";
System.out.println("After modifying d1 employees:");
System.out.println("Original d1: " + d1);
System.out.println("Deep d3: " + d3_deep);
System.out.println("d1.employees == d3.employees: " + (d1.employees ==
d3_deep.employees));
}
}

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;

public class UncheckedExceptionDemo {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

try {
System.out.print("Enter a number: ");
int num = scanner.nextInt();

int result = 100 / num;


System.out.println("Result: " + result);

int[] arr = {1, 2, 3};


System.out.print("Enter array index: ");
int index = scanner.nextInt();

System.out.println("Array element: " + arr[index]);


ArrayIndexOutOfBoundsException

} 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;

public class TryCatchFinallyDemo {


public static void main(String[] args) {
tryWithoutCatch();
tryWithoutFinally();
tryWithCatchAndFinally();
tryWithMultipleCatch();
nestedTryCatchFinally();
tryWithResources();
}

static void tryWithoutCatch() {


System.out.println("\nTry without catch block:");
try {
int a = 5 / 0;
} finally {
System.out.println("Finally block executed");
}
}

static void tryWithoutFinally() {


System.out.println("\nTry without finally block:");
try {
int a = 5 / 0;
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException");
}
}

static void tryWithCatchAndFinally() {


System.out.println("\nTry with catch and finally block:");
try {
int a = 5 / 0;
} catch (ArithmeticException e) {
46 | P a g e
System.out.println("Caught ArithmeticException");
} finally {
System.out.println("Finally block executed");
}
}

static void tryWithMultipleCatch() {


System.out.println("\nTry with multiple catch blocks:");
try {
int[] arr = new int[2];
System.out.println(arr[5]);
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException");
} catch (Exception e) {
System.out.println("Caught general Exception");
}
}

static void nestedTryCatchFinally() {


System.out.println("\nNested try-catch-finally:");
try {
try {
int a = 5 / 0;
} catch (ArithmeticException e) {
System.out.println("Inner catch: ArithmeticException");
} finally {
System.out.println("Inner finally");
}
} catch (Exception e) {
System.out.println("Outer catch");
} finally {
System.out.println("Outer finally");
}
}

static void tryWithResources() {


System.out.println("\nTry with resources:");
try (FileInputStream fis = new FileInputStream("nonexistent.txt")) {
fis.read();
} catch (IOException e) {
System.out.println("Caught IOException: " + e.getMessage());
}
}
}

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;

public void setMark(int mark) throws InvalidMarkException {


if (mark < 0 || mark > 100) {
throw new InvalidMarkException("Mark must be between 0 and 100.");
}
this.mark = mark;
}

public int getMark() {


return mark;
}
}

public class StudentWithCustomException {


public static void main(String[] args) {
Student student = new Student();
try {
student.setMark(105);
} catch (InvalidMarkException e) {
System.out.println("Error: " + e.getMessage());
}

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;

public class ExceptionPropagation {

void method1() throws IOException {


System.out.println("Inside method1 - throws IOException");
throw new IOException("Device error (Checked Exception)");
}

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");
}

public static void main(String[] args) {


ExceptionPropagation obj = new ExceptionPropagation();

System.out.println("--- Demonstrating Checked Exception Propagation (Handled) ---


");
obj.method3();

System.out.println("\n--- Demonstrating Unchecked Exception Propagation ---");


obj.methodC();
}
}

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;

public class UncheckedExceptionDemo {


public static void main(String[] args) {

50 | P a g e
Scanner scanner = new Scanner(System.in);

try {
System.out.print("Enter a number: ");
int num = scanner.nextInt();

int result = 100 / num;


System.out.println("Result: " + result);

int[] arr = {1, 2, 3};


System.out.print("Enter array index: ");
int index = scanner.nextInt();

System.out.println("Array element: " + arr[index]);


ArrayIndexOutOfBoundsException

} 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.*;

public class QuizGUI implements ActionListener {

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);

textField.setBounds(0, 0, 650, 50);


textField.setBackground(new Color(25, 25, 25));
textField.setForeground(new Color(25, 255, 0));
textField.setFont(new Font("Ink Free", Font.BOLD, 30));
textField.setBorder(BorderFactory.createBevelBorder(1));
textField.setHorizontalAlignment(JTextField.CENTER);
textField.setEditable(false);

textArea.setBounds(0, 50, 650, 50);


textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setBackground(new Color(25, 25, 25));
textArea.setForeground(new Color(25, 255, 0));
textArea.setFont(new Font("MV Boli", Font.BOLD, 25));
textArea.setBorder(BorderFactory.createBevelBorder(1));
textArea.setEditable(false);

buttonA.setBounds(0, 100, 100, 100);


buttonA.setFont(new Font("MV Boli", Font.BOLD, 35));
buttonA.setFocusable(false);
buttonA.addActionListener(this);
buttonA.setText("A");

buttonB.setBounds(0, 200, 100, 100);


buttonB.setFont(new Font("MV Boli", Font.BOLD, 35));
buttonB.setFocusable(false);
buttonB.addActionListener(this);
buttonB.setText("B");

buttonC.setBounds(0, 300, 100, 100);


buttonC.setFont(new Font("MV Boli", Font.BOLD, 35));
buttonC.setFocusable(false);
buttonC.addActionListener(this);
buttonC.setText("C");

buttonD.setBounds(0, 400, 100, 100);


buttonD.setFont(new Font("MV Boli", Font.BOLD, 35));
buttonD.setFocusable(false);
buttonD.addActionListener(this);
buttonD.setText("D");

answerLabelA.setBounds(125, 100, 500, 100);


55 | P a g e
answerLabelA.setBackground(new Color(50, 50, 50));
answerLabelA.setForeground(new Color(25, 255, 0));
answerLabelA.setFont(new Font("MV Boli", Font.PLAIN, 35));
answerLabelB.setBounds(125, 200, 500, 100);
answerLabelB.setBackground(new Color(50, 50, 50));
answerLabelB.setForeground(new Color(25, 255, 0));
answerLabelB.setFont(new Font("MV Boli", Font.PLAIN, 35));
answerLabelC.setBounds(125, 300, 500, 100);
answerLabelC.setBackground(new Color(50, 50, 50));
answerLabelC.setForeground(new Color(25, 255, 0));
answerLabelC.setFont(new Font("MV Boli", Font.PLAIN, 35));
answerLabelD.setBounds(125, 400, 500, 100);
answerLabelD.setBackground(new Color(50, 50, 50));
answerLabelD.setForeground(new Color(25, 255, 0));
answerLabelD.setFont(new Font("MV Boli", Font.PLAIN, 35));
numberRight.setBounds(225, 225, 200, 100);
numberRight.setBackground(new Color(25, 25, 25));
numberRight.setForeground(new Color(25, 255, 0));
numberRight.setFont(new Font("Ink Free", Font.BOLD, 50));
numberRight.setBorder(BorderFactory.createBevelBorder(1));
numberRight.setHorizontalAlignment(JTextField.CENTER);
numberRight.setEditable(false);
percentage.setBounds(225, 325, 200, 100);
percentage.setBackground(new Color(25, 25, 25));
percentage.setForeground(new Color(25, 255, 0));
percentage.setFont(new Font("Ink Free", Font.BOLD, 50));
percentage.setBorder(BorderFactory.createBevelBorder(1));
percentage.setHorizontalAlignment(JTextField.CENTER);
percentage.setEditable(false);
frame.add(textField);
frame.add(textArea);
frame.add(buttonA);
frame.add(buttonB);
frame.add(buttonC);
frame.add(buttonD);
frame.add(answerLabelA);
frame.add(answerLabelB);
frame.add(answerLabelC);
frame.add(answerLabelD);
frame.setVisible(true);
nextQuestion();
}
public void nextQuestion() {
if (index >= totalQuestions) {
results();
} else {
textField.setText("Question " + (index + 1));
textArea.setText(questions[index]);
answerLabelA.setText(options[index][0]);
answerLabelB.setText(options[index][1]);
answerLabelC.setText(options[index][2]);
answerLabelD.setText(options[index][3]);
56 | P a g e
}
}
@Override
public void actionPerformed(ActionEvent e) {
buttonA.setEnabled(false);
buttonB.setEnabled(false);
buttonC.setEnabled(false);
buttonD.setEnabled(false);
if (e.getSource() == buttonA) {
answer = 'A';
if (answer == answers[index]) {
correctGuesses++;
}
}
if (e.getSource() == buttonB) {
answer = 'B';
if (answer == answers[index]) {
correctGuesses++;
}
}
if (e.getSource() == buttonC) {
answer = 'C';
if (answer == answers[index]) {
correctGuesses++;
}
}
if (e.getSource() == buttonD) {
answer = 'D';
if (answer == answers[index]) {
correctGuesses++;
}
}
displayAnswer();
}
public void displayAnswer() {
buttonA.setEnabled(false);
buttonB.setEnabled(false);
buttonC.setEnabled(false);
buttonD.setEnabled(false);
if (answers[index] != 'A')
answerLabelA.setForeground(new Color(255, 0, 0));
if (answers[index] != 'B')
answerLabelB.setForeground(new Color(255, 0, 0));
if (answers[index] != 'C')
answerLabelC.setForeground(new Color(255, 0, 0));
if (answers[index] != 'D')
answerLabelD.setForeground(new Color(255, 0, 0));
Timer pause = new Timer(2000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
answerLabelA.setForeground(new Color(25, 255, 0));
answerLabelB.setForeground(new Color(25, 255, 0));
57 | P a g e
answerLabelC.setForeground(new Color(25, 255, 0));
answerLabelD.setForeground(new Color(25, 255, 0));
answer = ' ';
buttonA.setEnabled(true);
buttonB.setEnabled(true);
buttonC.setEnabled(true);
buttonD.setEnabled(true);
index++;
nextQuestion();
}
});
pause.setRepeats(false);
pause.start();
}
public void results() {
buttonA.setEnabled(false);
buttonB.setEnabled(false);
buttonC.setEnabled(false);
buttonD.setEnabled(false);
result = (int) (((double) correctGuesses / totalQuestions) * 100);
textField.setText("RESULTS!");
textArea.setText("");
answerLabelA.setText("");
answerLabelB.setText("");
answerLabelC.setText("");
answerLabelD.setText("");
numberRight.setText("(" + correctGuesses + "/" + totalQuestions + ")");
percentage.setText(result + "%");
frame.add(numberRight);
frame.add(percentage);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(QuizGUI::new);
}
}

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.*;

public class SimpleCalculatorGUI implements ActionListener {

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;

Font myFont = new Font("SansSerif", Font.BOLD, 30);

double num1 = 0, num2 = 0, result = 0;


char operator;

SimpleCalculatorGUI() {

frame = new JFrame("Simple Calculator");


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(420, 550);
frame.setLayout(null);

textField = new JTextField();


textField.setBounds(50, 25, 300, 50);

59 | P a g e
textField.setFont(myFont);
textField.setEditable(false);
textField.setHorizontalAlignment(JTextField.RIGHT);

addButton = new JButton("+");


subButton = new JButton("-");
mulButton = new JButton("*");
divButton = new JButton("/");
decButton = new JButton(".");
equButton = new JButton("=");
delButton = new JButton("Del");
clrButton = new JButton("Clr");

functionButtons[0] = addButton;
functionButtons[1] = subButton;
functionButtons[2] = mulButton;
functionButtons[3] = divButton;
functionButtons[4] = decButton;
functionButtons[5] = equButton;
functionButtons[6] = delButton;
functionButtons[7] = clrButton;

for (int i = 0; i < 8; i++) {


functionButtons[i].addActionListener(this);
functionButtons[i].setFont(myFont);
functionButtons[i].setFocusable(false);
}

for (int i = 0; i < 10; i++) {


numberButtons[i] = new JButton(String.valueOf(i));
numberButtons[i].addActionListener(this);
numberButtons[i].setFont(myFont);
numberButtons[i].setFocusable(false);
}

delButton.setBounds(50, 430, 145, 50);


clrButton.setBounds(205, 430, 145, 50);

panel = new JPanel();


panel.setBounds(50, 100, 300, 300);
panel.setLayout(new GridLayout(4, 4, 10, 10));

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);
}

public static void main(String[] args) {


SwingUtilities.invokeLater(SimpleCalculatorGUI::new);
}

@Override
public void actionPerformed(ActionEvent e) {

for (int i = 0; i < 10; i++) {


if (e.getSource() == numberButtons[i]) {
textField.setText(textField.getText().concat(String.valueOf(i)));
}
}
if (e.getSource() == decButton) {
if (!textField.getText().contains(".")) {
textField.setText(textField.getText().concat("."));
}
}
if (e.getSource() == addButton) {
num1 = Double.parseDouble(textField.getText());
operator = '+';
textField.setText("");
}
if (e.getSource() == subButton) {
num1 = Double.parseDouble(textField.getText());
operator = '-';
textField.setText("");
}
if (e.getSource() == mulButton) {
num1 = Double.parseDouble(textField.getText());
operator = '*';
textField.setText("");
}
if (e.getSource() == divButton) {
num1 = Double.parseDouble(textField.getText());
operator = '/';
textField.setText("");
}
61 | P a g e
if (e.getSource() == equButton) {
num2 = Double.parseDouble(textField.getText());

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 class AccountCreatorGUI extends JFrame {

private JTextField usernameField;


private JTextField firstNameField;
private JTextField lastNameField;
private JPasswordField passwordField;
private JTextField birthdateField;
private JTextField genderField;
private JButton createButton;
private JTextArea statusArea;
private JScrollPane scrollPane;

public AccountCreatorGUI() {

63 | P a g e
super("Google Account Creation (Simulation)");

usernameField = new JTextField(20);


firstNameField = new JTextField(20);
lastNameField = new JTextField(20);
passwordField = new JPasswordField(20);
birthdateField = new JTextField(20);
genderField = new JTextField(20);
createButton = new JButton("Create Account");
statusArea = new JTextArea(10, 30);
statusArea.setEditable(false);
statusArea.setLineWrap(true);
statusArea.setWrapStyleWord(true);
scrollPane = new JScrollPane(statusArea);

setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.WEST;

gbc.gridx = 0; gbc.gridy = 0; add(new JLabel("Username:"), gbc);


gbc.gridx = 1; gbc.gridy = 0; add(usernameField, gbc);

gbc.gridx = 0; gbc.gridy = 1; add(new JLabel("First Name:"), gbc);


gbc.gridx = 1; gbc.gridy = 1; add(firstNameField, gbc);

gbc.gridx = 0; gbc.gridy = 2; add(new JLabel("Last Name:"), gbc);


gbc.gridx = 1; gbc.gridy = 2; add(lastNameField, gbc);

gbc.gridx = 0; gbc.gridy = 3; add(new JLabel("Password:"), gbc);


gbc.gridx = 1; gbc.gridy = 3; add(passwordField, gbc);

gbc.gridx = 0; gbc.gridy = 4; add(new JLabel("Birthdate (YYYY-MM-DD):"), gbc);


gbc.gridx = 1; gbc.gridy = 4; add(birthdateField, gbc);

gbc.gridx = 0; gbc.gridy = 5; add(new JLabel("Gender:"), gbc);


gbc.gridx = 1; gbc.gridy = 5; add(genderField, gbc);

gbc.gridx = 0; gbc.gridy = 6; gbc.gridwidth = 2; gbc.anchor =


GridBagConstraints.CENTER;
add(createButton, gbc);

gbc.gridx = 0; gbc.gridy = 7; gbc.gridwidth = 2; gbc.fill =


GridBagConstraints.BOTH; gbc.weightx = 1.0; gbc.weighty = 1.0;
add(scrollPane, gbc);

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();

if (username.isEmpty() || password.isEmpty() || firstName.isEmpty()) {


statusArea.setText("Please fill in required fields (Username, First
Name, Password).");
return;
}

createButton.setEnabled(false);
statusArea.setText("");

AccountCreationWorker worker = new AccountCreationWorker(


username, firstName, lastName, password, birthdate, gender,
statusArea, createButton
);
worker.execute();
}
});

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new AccountCreatorGUI();
}
});
}
}

class AccountCreationWorker extends SwingWorker<Boolean, String> {

private final String username;


private final String firstName;
private final String lastName;
private final String password;
private final String birthdate;
private final String gender;
private final JTextArea statusArea;
private final JButton createButton;

public AccountCreationWorker(String username, String firstName, String lastName,


String password, String birthdate, String gender, JTextArea statusArea, JButton
createButton) {
this.username = username;
65 | P a g e
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.birthdate = birthdate;
this.gender = gender;
this.statusArea = statusArea;
this.createButton = createButton;
}

private void delay(int seconds) {


try {
TimeUnit.SECONDS.sleep(seconds);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
publish("Delay interrupted");
}
}

private boolean checkUsernameSim() {


publish("Connecting to Google servers to check username availability...");
delay(2);
publish("Connected.");
publish("Checking username '" + username + "'...");
delay(1);

boolean available = !(username.equalsIgnoreCase("admin") ||


username.equalsIgnoreCase("test") || username.length() < 6);
if (available) {
publish("Username Available.");
} else {
publish("Username Not available.");
}
return available;
}

private boolean solveCaptchaSim() {


publish("Security check required. Loading CAPTCHA...");
delay(2);
publish("CAPTCHA loaded.");
publish("Analyzing CAPTCHA challenge...");
delay(3);
publish("CAPTCHA verification passed (simulation).");
return true;
}

private boolean submitRequestSim() {


publish("\nEncrypting user data...");
delay(1);
publish("Submitting account creation request for '" + username + "' to
Google...");
delay(3);

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.*;

public class BufferedFileCopyPerformance {

private static final String WORD_TO_COUNT = "Java";


private static final int ENCRYPTION_SHIFT = 3;
private static final int BUFFER_SIZE = 8192;

public static void main(String[] args) {


String sourceFile = "sample.txt";
String byteDestFile = "sample.txt";
String charDestFile = "sample.txt";

System.out.println("Starting buffered file copy operations...");

long startTimeByte = System.nanoTime();


int countByte = copyUsingBufferedByteStreams(sourceFile, byteDestFile);
long endTimeByte = System.nanoTime();
long durationByte = (endTimeByte - startTimeByte) / 1_000_000;
if (countByte != -1) {
System.out.println("\n--- Buffered Byte Stream Results ---");
System.out.println("File copied to: " + byteDestFile);
System.out.println("Word '" + WORD_TO_COUNT + "' count: " + countByte);
System.out.println("Time taken: " + durationByte + " ms");
} else {
System.out.println("\nBuffered Byte Stream copy failed.");
}
long startTimeChar = System.nanoTime();
int countChar = copyUsingBufferedCharacterStreams(sourceFile, charDestFile);
long endTimeChar = System.nanoTime();
long durationChar = (endTimeChar - startTimeChar) / 1_000_000;
if (countChar != -1) {
System.out.println("\n--- Buffered Character Stream Results ---");
System.out.println("File copied to: " + charDestFile);
System.out.println("Word '" + WORD_TO_COUNT + "' count: " + countChar);
System.out.println("Time taken: " + durationChar + " ms");
} else {
System.out.println("\nBuffered Character Stream copy failed.");
69 | P a g e
}

System.out.println("\n--- Performance Comparison (Buffered) ---");


if (countByte != -1 && countChar != -1) {
if (durationByte < durationChar) {
System.out.println("Buffered byte stream was faster.");
} else if (durationChar < durationByte) {
System.out.println("Buffered character stream was faster.");
} else {
System.out.println("Both buffered streams took similar time.");
}
System.out.println("(Note: Buffered streams are generally significantly faster
than non-buffered streams for file I/O due to reduced disk access frequency.)");
} else {
System.out.println("Comparison not possible due to copy failure.");
}
System.out.println("\nOperations complete.");
}
private static int copyUsingBufferedByteStreams(String sourcePath, String destPath) {
int wordCount = 0;
StringBuilder currentWord = new StringBuilder();
try (BufferedInputStream bis = new BufferedInputStream(new
FileInputStream(sourcePath), BUFFER_SIZE);
BufferedOutputStream bos = new BufferedOutputStream(new
FileOutputStream(destPath), BUFFER_SIZE)) {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
byte[] encryptedBuffer = new byte[bytesRead];
for (int i = 0; i < bytesRead; i++) {
char c = (char) buffer[i];
if (Character.isLetterOrDigit(c)) {
currentWord.append(c);
} else {
if (currentWord.toString().equals(WORD_TO_COUNT)) {
wordCount++;
}
currentWord.setLength(0);
}
encryptedBuffer[i] = (byte) encryptByte(buffer[i]);
}
if (currentWord.length() > 0 &&
!Character.isLetterOrDigit((char)buffer[bytesRead-1])) {
if (currentWord.toString().equals(WORD_TO_COUNT)) {
wordCount++;
}
currentWord.setLength(0);
}
bos.write(encryptedBuffer, 0, bytesRead);
}
if (currentWord.toString().equals(WORD_TO_COUNT)) {
wordCount++;
70 | P a g e
}
return wordCount;
} catch (IOException e) {
System.err.println("Error during buffered byte stream copy: " +
e.getMessage());
return -1;
}
}
private static int copyUsingBufferedCharacterStreams(String sourcePath, String
destPath) {
int wordCount = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(sourcePath),
BUFFER_SIZE);
BufferedWriter writer = new BufferedWriter(new FileWriter(destPath),
BUFFER_SIZE)) {

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.*;

public class FileCopyPerformance {

private static final char CHAR_TO_COUNT = 'a';


private static final int ENCRYPTION_SHIFT = 3;

public static void main(String[] args) {


String sourceFile = "IOExamples/sample.txt";
String byteDestFile = "IOExamples/sample_byte_copy_encrypted.txt";
String charDestFile = "IOExamples/sample_char_copy_encrypted.txt";

System.out.println("Starting file copy operations...");

long startTimeByte = System.nanoTime();


int countByte = copyUsingByteStreams(sourceFile, byteDestFile);
long endTimeByte = System.nanoTime();
long durationByte = (endTimeByte - startTimeByte) / 1_000_000;

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.");
}

long startTimeChar = System.nanoTime();


int countChar = copyUsingCharacterStreams(sourceFile, charDestFile);
long endTimeChar = System.nanoTime();
72 | P a g e
long durationChar = (endTimeChar - startTimeChar) / 1_000_000;

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.");
}

System.out.println("\n--- Performance Comparison ---");


if (countByte != -1 && countChar != -1) {
if (durationByte < durationChar) {
System.out.println("Byte stream was faster.");
} else if (durationChar < durationByte) {
System.out.println("Character stream was faster.");
} else {
System.out.println("Both streams took similar time.");
}
} else {
System.out.println("Comparison not possible due to copy failure.");
}
System.out.println("\nOperations complete.");
}

private static int copyUsingByteStreams(String sourcePath, String destPath) {


int charCount = 0;
try (FileInputStream fis = new FileInputStream(sourcePath);
FileOutputStream fos = new FileOutputStream(destPath)) {

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;
}
}

private static int copyUsingCharacterStreams(String sourcePath, String destPath) {


int charCount = 0;
try (FileReader reader = new FileReader(sourcePath);
FileWriter writer = new FileWriter(destPath)) {

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;
}
}

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;
}
}

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"};

public static String intToRoman(int num) {


if (num < 1 || num > 3999) {
return "Input must be between 1 and 3999";
}

StringBuilder roman = new StringBuilder();


int i = 0;
while (num > 0) {
while (num >= values[i]) {
num -= values[i];
roman.append(symbols[i]);
}

i++;
}

return roman.toString();
}

public static void main(String[] args) {


int num1 = 3;
int num2 = 58;
int num3 = 1994;
int num4 = 4000;
System.out.println(num1 + " -> " + intToRoman(num1));
System.out.println(num2 + " -> " + intToRoman(num2));
System.out.println(num3 + " -> " + intToRoman(num3));
System.out.println(num4 + " -> " + intToRoman(num4));

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;

public class TcpCapitalizerClient {

private static final String SERVER_ADDRESS = "localhost";


private static final int SERVER_PORT = 9090;

public static void main(String[] args) {


System.out.println("TCP Capitalizer Client started...");
System.out.println("Enter text to capitalize (or type 'exit' to quit):");

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;
}

String serverResponse = reader.readLine();


if (serverResponse != null) {
79 | P a g e
System.out.println("Server response: " + serverResponse);
} else {
System.out.println("Server closed the connection unexpectedly.");
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;

public class TcpCapitalizerServer {

private static final int PORT = 9090;

public static void main(String[] args) {


System.out.println("TCP Capitalizer Server started...");
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
while (true) {
try {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " +
clientSocket.getInetAddress());
handleClient(clientSocket);
} catch (IOException e) {
System.err.println("Error accepting client connection: " +
e.getMessage());
}
}
} catch (IOException e) {
System.err.println("Could not start server on port " + PORT + ": " +
e.getMessage());
}
}

private static void handleClient(Socket clientSocket) {


80 | P a g e
try (
BufferedReader reader = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true)
) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Received from client: " + line);
if (line.equalsIgnoreCase("exit")) {
System.out.println("Client requested exit.");
break;
}
String capitalizedLine = line.toUpperCase();
writer.println(capitalizedLine);
System.out.println("Sent to client: " + capitalizedLine);
}
} catch (IOException e) {
System.err.println("Error handling client " + clientSocket.getInetAddress() +
": " + e.getMessage());
} finally {
try {
clientSocket.close();
System.out.println("Client disconnected: " +
clientSocket.getInetAddress());
} catch (IOException e) {
System.err.println("Error closing client socket: " + e.getMessage());
}
}
}
}

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;

public class TcpEmailValidatorServer {

private static final int PORT = 9091;


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("TCP Email Validator Server started...");
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
while (true) {
try {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " +
clientSocket.getInetAddress());
handleClient(clientSocket);
} catch (IOException e) {
System.err.println("Error accepting client connection: " +
e.getMessage());
}
}
} catch (IOException e) {
System.err.println("Could not start server on port " + PORT + ": " +
e.getMessage());
}
}

private static void handleClient(Socket clientSocket) {


try (
BufferedReader reader = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true)
) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Received from client: " + line);
if (line.equalsIgnoreCase("exit")) {
System.out.println("Client requested exit.");
break;
}

boolean isValid = EMAIL_PATTERN.matcher(line).matches();


String response = isValid ? "Valid" : "Invalid";
writer.println(response);
82 | P a g e
System.out.println("Sent to client: " + response);
}
} catch (IOException e) {
System.err.println("Error handling client " + clientSocket.getInetAddress() +
": " + e.getMessage());
} finally {
try {
clientSocket.close();
System.out.println("Client disconnected: " +
clientSocket.getInetAddress());
} catch (IOException e) {
System.err.println("Error closing client socket: " + e.getMessage());
}
}
}
}

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;

public class TcpEmailValidatorClient {

private static final String SERVER_ADDRESS = "localhost";


private static final int SERVER_PORT = 9091;

public static void main(String[] args) {


System.out.println("TCP Email Validator Client started...");
System.out.println("Enter email address to validate (or type 'exit' to quit):");

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;
}

String serverResponse = reader.readLine();


if (serverResponse != null) {
System.out.println("Server response: " + serverResponse);
} else {
System.out.println("Server closed the connection unexpectedly.");
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;

public class UdpCapitalizerClient {

private static final String SERVER_ADDRESS = "localhost";


private static final int SERVER_PORT = 9092;
private static final int BUFFER_SIZE = 1024;
private static final int TIMEOUT_MS = 5000;

public static void main(String[] args) {


System.out.println("UDP Capitalizer Client started...");
System.out.println("Enter text to capitalize (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());
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;

public class UdpCapitalizerServer {

private static final int PORT = 9092;


private static final int BUFFER_SIZE = 1024;

public static void main(String[] args) {


System.out.println("UDP Capitalizer 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;
86 | P a g e
}

String capitalizedData = receivedData.toUpperCase();


byte[] sendBuffer = capitalizedData.getBytes();

DatagramPacket sendPacket = new DatagramPacket(sendBuffer,


sendBuffer.length, clientAddress, clientPort);
socket.send(sendPacket);
System.out.println("Sent to " + clientAddress + ":" + clientPort + ":
" + capitalizedData);

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());
}
}
}

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 {

private static final long serialVersionUID = 1L;

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String name = request.getParameter("name");


if (name == null || name.trim().isEmpty()) {
name = "World";
}

response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");

PrintWriter out = response.getWriter();

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>");
}

private String escapeHtml(String input) {


if (input == null) {
return "";
}
return input.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace("\"", "&quot;")
.replace("'", "&#x27;")
.replace("/", "&#x2F;");
}

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);

} catch (SQLException se) {


System.err.println("Database Error:");
se.printStackTrace();
} catch (Exception e) {
System.err.println("General Error:");
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
System.out.println("\nDatabase connection closed.");
}
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Program finished.");
}
public static void addStudent(Connection conn, String id, String name, double gpa)
throws SQLException {
String sql = "INSERT INTO students (id, name, gpa) VALUES (?, ?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, id);
pstmt.setString(2, name);
pstmt.setDouble(3, gpa);
int rowsAffected = pstmt.executeUpdate();
System.out.println("Inserted " + name + ". Rows affected: " + rowsAffected);
}
}
public static void getAllStudents(Connection conn) throws SQLException {
String sql = "SELECT id, name, gpa FROM students";
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {

boolean found = false;


while (rs.next()) {
found = true;
String id = rs.getString("id");
System.out.println("ID: " + id + ", Name: " + name + ", GPA: " + gpa);
}
if (!found) {
System.out.println("No students found in the table.");
}
}
}

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 {

String num1Str = request.getParameter("num1");


String num2Str = request.getParameter("num2");
String operation = request.getParameter("operation");

double num1, num2;


double result = 0;
String error = null;
String calculationString = null;

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;
}

HttpSession session = request.getSession();


@SuppressWarnings("unchecked")
List<String> sessionHistory = (List<String>)
session.getAttribute(HISTORY_SESSION_ATTR);
if (sessionHistory == null) {
sessionHistory = new ArrayList<>();
}
sessionHistory.add(calculationString);
session.setAttribute(HISTORY_SESSION_ATTR, sessionHistory);

String cookieHistoryStr = getCookieValue(request, HISTORY_COOKIE_NAME);


if (cookieHistoryStr == null || cookieHistoryStr.isEmpty()) {
cookieHistoryStr = calculationString;
} else {
cookieHistoryStr += HISTORY_DELIMITER + calculationString;
}
setCookieValue(response, HISTORY_COOKIE_NAME, cookieHistoryStr, COOKIE_MAX_AGE);

request.setAttribute("result", result);
request.getRequestDispatcher("result.jsp").forward(request, response);
}

private String getCookieValue(HttpServletRequest request, String cookieName) {


Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookieName.equals(cookie.getName())) {
try {
return URLDecoder.decode(cookie.getValue(), "UTF-8");
} catch (UnsupportedEncodingException e) {
System.err.println("Error decoding cookie: " + e.getMessage());
return null;
}
}
}
}
return null;
}

private void setCookieValue(HttpServletResponse response, String cookieName, String


value, int maxAge) {
try {
String encodedValue = URLEncoder.encode(value, "UTF-8");
Cookie cookie = new Cookie(cookieName, encodedValue);
cookie.setMaxAge(maxAge);
cookie.setPath("/");
response.addCookie(cookie);
} catch (UnsupportedEncodingException e) {
99 | P a g e
System.err.println("Error encoding cookie: " + e.getMessage());
}
}
}

SAMPLE OUTPUT:

RESULT: The required programs have been written and executed successfully.

100 | P a g e

You might also like