0% found this document useful (0 votes)
4 views168 pages

Recordjava 1 Merged

The document outlines various Java programming exercises, including algorithms and code snippets for tasks such as greeting users, error handling, calculating leap years, determining the day of the week, and managing bank account operations. Each exercise includes an algorithm, a program, and expected outputs. The document serves as a comprehensive guide for practicing Java programming concepts and error identification.

Uploaded by

esupmet2426
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)
4 views168 pages

Recordjava 1 Merged

The document outlines various Java programming exercises, including algorithms and code snippets for tasks such as greeting users, error handling, calculating leap years, determining the day of the week, and managing bank account operations. Each exercise includes an algorithm, a program, and expected outputs. The document serves as a comprehensive guide for practicing Java programming concepts and error identification.

Uploaded by

esupmet2426
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/ 168

Ex.No.

:01

Date:
Aim:

1.a)Algorithm:

1. Import java.util.* for potential utility use.


2. Define the main method: public static void main(String[] args).
3. Check if args.length> 0:
 If true: print "Hello, ", then loop through each element in args to print each argument
followed by a space, and finally print "Good morning!".
 If false: print "There is no argument passed".
Program:

importjava.util.Scanner;

public class Hello1

publicstaticvoidmain(Stringargs[]){

System.out.print(“2022503060");

if(args.length>0) {
for (int i = 0; i < args.length; i++) {

System.out.print("hello"+",");

System.out.print(args[i]+","+"goodmorning");

}
}else

System.out.println("hello,mithun,goodmorning");

}
}

}
Output:

1.b) Algorithm:
1. Identify Errors by Modification: Modify the code in different ways to trigger compile-
time and run-time errors:
 Remove a semicolon to cause a compile-time error.
 Swap or omit keywords like public, static, void, main to cause a compile-time error.
 Remove the array subscript from String[] to cause a compile-time error.
 Change String to int or float to trigger a compile-time error (type mismatch).
 Replace String[] with String to cause a compile-time error.
2. Test and Observe Errors: After each modification, attempt to compile and run the
program to observe the errors generated.
3. Document the Errors: Note the type (compile-time or run-time) and message of the
error generated for each change.
i) Delete Semicolons:
Program:
public class ErrorMessage3060{
public static void main(String[] args) {
System.out.println("kathirvel M 20225032060");
}
}
Output:

ii) Swap the word public ,static ,void , main


Program:
public class ErrorMessage3060{
static public void main(String[] args) {
System.out.println(“KATHIRVEL M 2022503060");
}
}
Program:
public class ErrorMessage3060{
static void public main(String[] args) {
System.out.println("KATHIRVEL M 2022503060");
}
}
Output:

Program:
public class ErrorMessage3060{
static void main public (String[] args) {
System.out.println("KATHIRVEL M 2022503060");
}
}
Output:
iii) Omit the word public ,static ,void,main
Program:
public class ErrorMessage3060{
static void main (String[] args) {
System.out.println("KATHIRVEL M 2022503060");
}
}
Output:

Program:
public class ErrorMessage3060{
public void main (String[] args) {
System.out.println("KATHIRVEL M 2022503060");
}
}
Output:

Program:
public class ErrorMessage3060{
public static main (String[] args) {
System.out.println("KATHIRVEL M 2022503060");
}
}
Output:

Program:
public class ErrorMessage3060{
public static void (String[] args) {
System.out.println("KATHIRVEL M 2022503060");
}
}
Output:

iv) Omit the array subscript around string


Program:
public class ErrorMessage3060{
public static void main (String args) {
System.out.println("KATHIRVEL M 2022503060");
}
}
Output:
v) Replace the String[] with int[]
Program:
public class ErrorMessage3060{
public static void main (int[] args) {
System.out.println("KATHIRVEL M 2022503060");
}
}
Output:

vi)Replace the String[] with float[]


Program:
public class ErrorMessage3060{
public static void main (float[] args) {
System.out.println("KATHIRVEL M 2022503060");}}
Output:

vii) Replace the String[] with String…


Program:
public class ErrorMessage3060{
public static void main (String... args) {
System.out.println("KATHIRVEL M 2022503060");
}
}
Output:

1.c) Algorithm:
1. Import necessary classes: ArrayList, List, and Scanner.
2. Print user details.
3. Initialize lists java and python to store user inputs.
4. In a loop, get Java and Python strings from the user, add to respective lists, and
ask if they want to continue.
5. After the loop, print all entries from both lists in sequence.
Program:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class conversation_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 202203060");
List<String> java = new ArrayList<>();
List<String> python = new ArrayList<>();
int i=0;
boolean c=true;
do{
Scanner in=new Scanner(System.in);
System.out.print("Java: ");
java.add(in.nextLine());
System.out.print("Python: ");
python.add(in.nextLine());
System.out.print("Do you want to continue:");
c=in.nextBoolean();
in.nextLine();
}while(c);
for(int j=0;j<java.size() && j<python.size();j++){
System.out.println("Java:" + java.get(j));
System.out.println("Python:"+python.get(j)); }
}}
Output:
1.d) Algorithm:
1. Import the Scanner class for user input.
2. Define the main method: public static void main(String[] args).
3. Create a Scanner object and prompt the user to enter a year.
4. Read the year as a long value.
5. Check if the year is a leap year using the condition:
6. A year is a leap year if:
 It is divisible by 400, or
 It is divisible by 4 but not by 100.
7. If the condition is true, print "True"; otherwise, print "False".
Program:
import java.util.Scanner;
public class Leap_year3060 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.print("Enter the year:");
long year=in.nextLong();
boolean check =((year%100==0 && year % 400 ==0) || (year %100 !=0 && year% 4==0)) ?
true :false;
if(check)
System.out.println("True");
else
System.out.println( "False");
}}
Output:
1.e) Algorithm:
1. Import the Scanner class for user input.
2. Define the main method: public static void main(String[] args).
3. Create a Scanner object and prompt the user to enter the day, month, and year as
integers.
4. Calculate an intermediate year value y0 using the formula: y0 = y - (14 - m) / 12.
5. Calculate an offset value x using the formula: x = y0 + y0 / 4 - y0 / 100 + y0 / 400.
6. Calculate an adjusted month value m0 using the formula: m0 = m + 12 * ((14 - m) /
12) - 2.
7. Determine the day of the week d0 using the formula: d0 = (d + x + (31 * m0) / 12) %
7.
8. Use a switch statement to print the corresponding day of the week based on the
value of d0.
Program:
import java.util.Scanner;
public class Day_of_the_week3060 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.print("Enter the date:");
int d=in.nextInt();
System.out.print("Enter the month:");
int m=in.nextInt();
System.out.print("Enter the year:");
int y=in.nextInt();
int y0=y- (14-m) / 12;
int x=y0 + y0/4 -y0/100 + y0/400;
int m0=m +12 * ((14-m)/12) - 2;
int d0=(d + x +(31 * m0) / 12) % 7;
switch(d0){
case 0:
System.out.println("Sunday");
break;
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
}}}

Output:
1.f) Algorithm:
1. Import Scanner for user input and Math for mathematical operations.
2. Define the main method: public static void main(String[] args).
3. Create a Scanner object and prompt the user to enter the temperature (temp) and
wind velocity (velocity) as double values.
4. Calculate the wind chill factor w using the formula:
𝑤=35.74+(0.6215×temp)+(Math.pow(velocity, 0.16))×((0.4275×temp−35.75)
5. Print the calculated wind chill factor w.
Program:
import java.util.Scanner;
import java.lang.Math;
public class WindChill_3060 {
public static void main(String[] args) {
double temp;
double velocity;
Scanner input = new Scanner(System.in);
System.out.print("Enter the temperature:");
temp=input.nextDouble();
System.out.print("Enter the velocity:");
velocity=input.nextDouble();
double w = 35.74 + (0.6215 * temp) + Math.pow(velocity,0.16) * ((0.4275 * temp) - 35.75);
System.out.println(w);
}
}

Output:
1.g) Algorithm:
1. Import the Scanner class for user input.
2. Set Bias = -0.5, W0 = 1.0, and W1 = 1.0.
3. Get values for X1 and X2 from the user.
4. Compute Weighted Sum by calculating Y = Bias + (W0 * X1) + (W1 * X2).
5. If Y > 0.5, print 1; otherwise, print 0.
Program:
import java.util.Scanner;
public class AND_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 202203060");
double Y;
double Bias=-0.5;
double W0=1.0 , W1=1.0;
double X1;
double X2;
Scanner in=new Scanner(System.in);
System.out.println("Enter the input:");
X1=in.nextFloat();
System.out.println("Enter the input:");
X2=in.nextFloat();
Y = Bias + (W0 * X1) +(W1 * X2);
int ans = (Y>0.5)?1:0;
System.out.println("Result is: " + ans); }
}

Output:
1.h) Algorithm:
1. Import the Scanner Class for user input.
2. Prompt the user to input a number and store it in no.
3. Use the formula count = (int) (Math.log(no) / Math.log(10)) to determine the number
of digits in no.
4. Use a while loop to extract each digit by dividing no by powers of 10, and print its
position and value.
5. Update no by removing the extracted digit and reduce count to extract the next digit
until all digits are processed.
Program:
import java.util.Scanner;
public class Digit_pos_3060{
public static void main(String[] args) {
System.out.println("KATHIRVEL M 202203060");
int no;
Scanner in = new Scanner(System.in);
System.out.print("Enter the number:");
no = in.nextInt();
int count = (int) (Math.log(no) / Math.log(10));
int n = count + 1;
int i = 0;
while (i< n) {
int dig = no / (int) Math.pow((double) 10, (double) count);
System.out.println("Position: " + i + " " + "Value: " + dig);
no = no % ((int) Math.pow((double) 10, (double) count));
count--;
i++;}
}
}
Output:

1.i) Algorithm:
1. Import Random and Scanner for random number generation and user input.
2. Use Random to generate a principal between ₹10,000 and ₹100,000.
3. Get the number of years and rate of interest from the user.
4. Ensure the rate is between 1% and 10%, and years are between 1 and 30.
5. Calculate Future Value by the formula: Amount=Principal×(1+Rate) ^Years
6. Print the principal, rate, years, and future value.
Program:
import java.util.Random;
import java.util.Scanner;
public class investment_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 202203060");
Random random = new Random();
long principal = random.nextInt(10000,100001);
Scanner in=new Scanner(System.in) ;
System.out.print("Enter the no.of years:");
int years=in.nextInt();
System.out.print("Enter the rate of interest:");
double rate=in.nextDouble();
if(rate>=1 && rate<=10 && years>=1 && year<=30){
double amount = (double)principal * ((Math.pow((1 + rate ),years)));
System.out.println("Principal: ₹" + principal +"\n" + "Annual Rate:" + rate + "%" +"\n"
+"Years: " + years +"\n"+"Future Value: ₹" + amount);}
}
}
Output:

Result:
Ex.No.:02
Date:
Aim:

2.a) Algorithm:
1. Import Scanner for user input.
2. Declare a class Balance_3060 with fields for name, balance, and accno.
3. In main, prompt the user to enter account details (name, balance, and accno) and
initialize a Balance_3060 object.
4. Implement deposit(int amount) to add the specified amount to balance and display a
confirmation message.
5. Implement withdraw(int amount), which checks if balance is sufficient. If not, display
an "Insufficient balance" message; otherwise, subtract the amount from balance and
confirm.
6. Implement check_balance() to return the current balance.
Program:
import java.util.Scanner;
public class Balance_3060 {
String name;
double balance;
long accno;
Balance_3060(String name, double b, long a) {
this.name = name;
this.balance = b;
this.accno = a;}
void withdraw(int amount) {
if (this.balance< amount) {
System.out.println("Insufficient balance");
return;}
this.balance -= amount;
System.out.println("Withdrawal successful");}
void deposit(int amount) {
this.balance += amount;
System.out.println("Balance updated");}
double check_balance() {
return balance;
}
public static void main(String[] args) {
System.out.println("KATHIRVEL M 202203060");
Scanner in =new Scanner(System.in);
System.out.print("Enter the account holder name:");
String name = in.nextLine();
System.out.print("Enter the balance:");
double balance = in.nextDouble();
System.out.print("Enter the account number:");
long acc_no=in.nextLong();
Balance_3060 b = new Balance_3060(name,balance,acc_no);
int choice;
do {
System.out.print("Enter 1 for withdrawal\t2 for depoit\t3 for checking balance\t4 for exit:");
choice=in.nextInt();
switch (choice) {
case 1:
System.out.print("Enter the amount to be withdrawn:");
b.withdraw(in.nextInt());
break;
case 2:
System.out.print("Enter the amount to be deposited:");
b.deposit(in.nextInt());
break;
case 3:
System.out.println(b.check_balance());
break;
case 4:
System.out.println("Exited");
break;
}
}while(choice!=4);
}}
Output:

2.b) Algorithm:
1. Import Random and Scanner for generating random values and taking user input.
2. Prompt the user to input the size n of the arrays.
3. Initialize an integer array num and a character array c of size n.
4. Use a loop to fill num and c arrays: randomly decide each time whether to generate
an uppercase or lowercase character, assign it to c, and store its ASCII value in num.
5. Implement a bubble_sort method that sorts both c and num arrays in ascending
order, counting comparisons and swaps made during sorting.
6. Use the print method to display the sorted indices, ASCII values, and characters,
formatted with underscores as dividers.
7. After sorting, output the total number of comparisons made in the sorting process.
Program:
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class sort_3060{
public static void main(String[] args) {
System.out.println("KATHIRVEL M 202203060");
Random random = new Random();
Scanner in = new Scanner(System.in);
System.out.print("Enter the size:");
int n =in.nextInt();
int[] num=new int[n];
char[] c=new char[n];

boolean choice;
for(int i=0;i<n;i++){
choice=random.nextBoolean();
if(choice){
int temp=random.nextInt(65,91);
c[i] = (char) (temp);
num[i]=temp;}
else{
int temp=random.nextInt(97,123);
c[i]=(char)(temp);
num[i]=temp;}
}
System.out.println("Comparison:" + bubble_sort(c,num,0));
print(num,c);
}
public static void print(int[] num,char[] c){
print_underscore();
System.out.printf("|");
for (int i = 0; i<num.length; i++) {
System.out.printf("%4d |",i);
}
print_underscore();
System.out.printf("|");
for (int i = 0; i<num.length; i++) {
System.out.printf("%4d |",num[i]);
}
print_underscore();
System.out.printf("|");
for (int i = 0; i<num.length; i++) {
System.out.printf("%4s |",c[i]);
}
print_underscore();
}
public static void print_underscore(){ System.out.print("\n---------------------------------\n");}
public static int bubble_sort(char[] c,int[] num,int comp){
for(int i=0;i<c.length;i++){
for(int j=0;j<c.length-i-1;j++){
if(c[j]>c[j+1]){
char temp=c[j];
c[j]=c[j+1];
c[j+1]=temp;
comp++;
}
if(num[j]>num[j+1]){
int temp=num[j+1];
num[j+1]=num[j];
num[j]=temp;}
}}
return comp;}
}
Output:

2.c) Algorithm:
1. Import Scanner for user input.
2. Prompt the user to enter the array size n and initialize two arrays, A and B, each of
size n.
3. Using a loop, prompt the user to input elements for both arrays.
4. Implement the findoccurence method, initializing a counter count to zero.
5. For each element in B, check if it exists in A using a nested loop.
6. If an element in B is found in A, increment count and break the inner loop.
7. After counting, return count from findoccurence.
8. Display the total count of elements from B that appear in A.
Program:
import java.util.Scanner;
public class Occurence_3060{
public static void main(String[] args) {
int n;
Scanner in= new Scanner(System.in);
System.out.print("Enter the size: ");
n=in.nextInt();
int[] A =new int[n];
int[] B=new int[n];
for (int i = 0; i< n; i++) {
System.out.print("Enter the element of A:");
A[i] = in.nextInt();
System.out.print("Enter the element of B:");
B[i] = in.nextInt();
}
System.out.println(findoccurence(A,B));
}
public static int findoccurence(int[] A , int[] B){
int count=0;
for(int i: B){
for(int j=0;j<A.length;j++){
if(i==A[j]){
count++;
break;}
}
}
return count;
}}
Output:
2.d) Algorithm:
1. Import Scanner for user input.
2. Prompt the user to input the number of rows and columns, then initialize two
matrices, mat1 and mat2, of the specified size.
3. Fill both matrices with user-provided values.
4. Implement a method columnsum that creates a result matrix, where each element is
the sum of the corresponding elements from mat1 and mat2.
5. Inside columnsum, compute the sum of each column in result and store these sums
in a sum array.
6. Use a bubble method to sort the sum array in ascending order. Simultaneously,
rearrange the columns of result to match the sorted order.
7. Display the sorted result matrix in the main function by printing each element row by
row.
Program:
import java.util.Scanner;
public class Sum_of_array_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 202203060");
int row1,column1;
Scanner in=new Scanner(System.in);
System.out.print("Enter the no.of rows:");
row1=in.nextInt();
System.out.print("Enter the no.of column:");
column1=in.nextInt();
int[][] mat1=new int[row1][column1];
int[][] mat2=new int[row1][column1];
for(int i=0;i<row1;i++){
for(int j=0;j<column1;j++){
System.out.printf("Enter the mat1[%d][%d]:",i,j);
mat1[i][j]=in.nextInt();
System.out.printf("Enter the mat2[%d][%d]:",i,j);
mat2[i][j]=in.nextInt();}
}
int[][] res = columnsum(mat1,mat2);
for(int i=0;i<res.length;i++){
for(int j=0;j<res[0].length;j++){
System.out.print(res[i][j]+ " ");
}
System.out.println();
}}
public static int[][] columnsum(int[][] mat1 , int[][] mat2){
int[][] result = new int[mat1.length][mat1[0].length];
for(int j=0;j<mat1[0].length;j++){
for(int i=0;i<mat1.length;i++){
result[i][j]=mat1[i][j]+mat2[i][j];
}
}
int[] sum = new int[mat1[0].length];
for(int j=0;j<result[0].length;j++){
for(int i=0;i<result.length;i++){
sum[j]+=result[i][j];
}
}
int[] dup=new int[sum.length];
for(int i=0;i<sum.length;i++){
dup[i]=sum[i];
}
bubble(sum,result);
return result;
}
public static void bubble(int[] arr,int[][] res){
boolean swapped;
for(int i=0;i<arr.length;i++){
swapped=false;
for(int j=1; j<=arr.length-i-1;j++) {
if (arr[j] <arr[j - 1]) {
int temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
swap(j,j-1,res);
swapped=true;
}
}
if (!swapped){ break;}
}
}
public static void swap(int i,intj,int[][] res){
for(int row=0;row<res.length;row++){
for(int column=0;column<res[0].length;column++){
if(column==i){
int temp=res[row][i];
res[row][i]=res[row][j];
res[row][j]=temp; }}
}}}

Output:
Result:

Ex.No.:03
Date:
Aim:

3.a) Algorithm:
1. Import HashMap and Scanner.
2. Create Node and LinkedList_3060 classes. The Node class defines val and next
attributes for each node.
3. Define methods to insert nodes at the beginning, end, specific positions, and relative
to existing nodes.
4. Add methods to delete nodes from the beginning, end, by position, and by value.
5. Include a search method to find a node by its value and a method to count
occurrences of a value.
6. Define methods to reverse the list, remove duplicates using HashMap, and
concatenate two linked lists.
7. Implement a sorting method using merge sort and methods to calculate the length
and access nodes by position.
Program:
import java.util.HashMap;
import java.util.Scanner;
class Node{
int val;
Node next;
Node(){
this.val=0;
this.next=null;}
Node(int val){
this.val=val;
this.next=null;}
}
public class LinkedList_3060 {
Node head = null;
void insert(int val){
Node node = new Node(val);
if(head==null){
head=node;
return ;}
Node n = head;
while(n.next!=null){
n = n.next;}
n.next=node;}
void insertbeg(int val){
Node n = new Node(val);
if(head==null){
head=n;
return ;}
n.next=head;
head=n;}
void insertend(int val){
Node n = new Node(val);
if(head==null){
head=n; n.next=null; return ;}
Node temp=head;
while(temp.next!=null){
temp=temp.next;}
temp.next=n;
n.next=null;}
void insertafternode(int i,intval){
if(i<=0){
System.out.println("Position does not exist\n");
return;}
Node n=new Node(val);
int t=1;
Node temp=head;
while(t<i& temp!=null){
temp=temp.next;
t++;}
if(temp==null){
System.out.println("Position does not exist\n");
return;}
n.next=temp.next;
temp.next=n;}
void insertbeforenode(int i ,int val){
if(i<=0){
System.out.println("Position does not exist\n");
return;}
Node n = new Node(val);
if(i==1){
n.next=head;
head=n;
return;}
int t=1;
Node temp= head;
while(t<=i-2 && temp!=null){
temp=temp.next;
t++;}
if(temp==null){
System.out.println("Position does not exist\n");
return;}
n.next=temp.next;
temp.next=n;}
void insertatpos(int pos,intval){
Node n = new Node(val);
if(pos==1){
n.next=head;
head=n;
return;}
int i=1;
Node temp=head;
while(i<pos-1 && temp!=null){
temp=temp.next;
i++;}
if(temp==null){
System.out.println("Position not found");
return;}
n.next=temp.next;
temp.next=n;}
void deleteBeg(){
if(head==null)
return;
head=head.next;}
void deleteEnd(){
Node temp=head;
if(head.next==null){
head=null;
return;}
while(temp.next.next!=null){
temp=temp.next;}
temp.next=null;}
void deleteatpos(int i){
if(i==1){
System.out.printf("Deleted item is: %d\n",head.val);
head=head.next;
return ;}
int t=1;
Node temp=head;
while(t<i-1 && temp!=null){
temp=temp.next;
t++;
}
if(temp==null || temp.next==null){
System.out.println("Item not found\n");
return;}
System.out.printf("Deleted item is: %d\n",temp.next.val);
temp.next = temp.next.next;}
void deletebyval(int val){
Node temp=head;
if(temp.val==val){
head=temp.next;
return ;}
while(temp.next!=null &&temp.next.val!=val ){
temp=temp.next;}
if(temp==null || temp.next==null){
System.out.println("Value does not exist\n");
return;
}
temp.next=temp.next.next;}
void display(){
Node temp = head;
if(temp==null){
System.out.println("list is empty"); return ;}
while(temp!=null){
System.out.print(temp.val + "->");
temp=temp.next;}
System.out.print("End\n");}
void display(Node head){
Node temp = head;
if(temp==null){
System.out.println("list is empty"); return ;}
while(temp!=null){
System.out.print(temp.val + "->");
temp=temp.next;}
System.out.print("End\n");}
void reverse(){
if(head==null ) return;
Node temp=head;
Node nxt=null;
Node prev=head;
while(temp!=null) {
nxt = temp.next;
if (temp == head) {
temp.next = null;
prev = temp;
temp = nxt;
} else {
temp.next = prev;
prev = temp;
temp = nxt;}
}
head=prev;
temp = head;
if(temp==null){
System.out.println("list is empty"); return ;}
while(temp!=null){
System.out.print(temp.val + "->");
temp=temp.next;}
System.out.print("End\n");}
boolean search(int val){
Node temp=head;
while(temp!=null){
if(temp.val==val) return true;
temp=temp.next;
}
return false;
}
int accessbypos(int i){
int t=1;
Node temp=head;
while(temp!=null && t<i){
temp=temp.next;
t++;
}
if(temp==null || i<=0){ return -1;}
return temp.val;
}
int length(){
if(head==null)
return 0;
int count=0;
Node temp=head;
while(temp!=null){
temp=temp.next;
count++;
}
return count;
}
int countoccuerence(int val){
Node temp=head;
int count=0;
while(temp!=null){
if(temp.val==val) count++;
temp=temp.next;
}
return count;
}
void sortList(){
head = sort(head);
}
Node sort(Node head){
if(head==null || head.next==null){
return head;
}
Node middle= findmiddle(head);
Node lefthead = head;
Node righthead=middle.next;
middle.next=null;
lefthead=sort(lefthead);
righthead=sort(righthead);
return merge(lefthead,righthead);
}
Node findmiddle(Node head){
Node slow=head;
Node fast = head.next;
while(fast!=null &&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
}
return slow;
}
Node merge(Node head1, Node head2){
Node dummy = new Node(-1);
Node t1=head1;
Node t2=head2;
Node temp=dummy;
while(t1!=null && t2!=null){
if(t1.val<t2.val){
temp.next=t1;
temp=t1;
t1=t1.next;
}
else{
temp.next=t2;
temp=t2;
t2=t2.next;
}
}
if(t1!=null) temp.next=t1;
if(t2!=null) temp.next=t2;
return dummy.next;
}
void removeduplicates(){
HashMap<Integer,Integer> h= new HashMap<>();
Node temporary = head;
while(temporary!=null){
h.put(temporary.val,h.getOrDefault(temporary.val,0) + 1 );
temporary=temporary.next;
}
Node dummy = new Node(-1);
dummy.next=head;
Node temp=dummy;
while( temp!=null &&temp.next!=null ){
if( !h.containsKey(temp.next.val)){
temp.next=temp.next.next;
}
else{
h.remove(temp.next.val);
temp=temp.next;}
}
}
Node concat(LinkedList_3060 obj1, LinkedList_3060 obj2){
if(obj1.head==null) return obj2.head;
if(obj2.head==null) return obj1.head;
Node temp=obj1.head;
while(temp.next!=null){
temp=temp.next;
}
temp.next=obj2.head;
return obj1.head;
}
public static void main(String[] args) {
System.out.println("KATHIRVEL M 202203060");
LinkedList_3060 obj = new LinkedList_3060();
LinkedList_3060 obj1 = new LinkedList_3060();
Scanner in = new Scanner(System.in);
int ch;
do{
System.out.print("Enter 1-17 :");
ch=in.nextInt();
switch(ch){
case 1:
System.out.print("Enter the value to be inserted:");
obj.insertbeg(in.nextInt());
break;
case 2:
System.out.print("Enter the value to be inserted:");
obj.insertend(in.nextInt());
break;
case 3:
System.out.print("Enter the position:");
int pos = in.nextInt();
System.out.print("Enter the value to be inserted:");
obj.insertatpos(pos,in.nextInt());
break;
case 4:
System.out.print("Enter the node after which node has to be inserted:");
int n=in.nextInt();
System.out.print("Enter the value to be inserted:");
obj.insertafternode(n,in.nextInt());
break;
case 5:
System.out.print("Enter the node before which node has to be inserted:");
int b=in.nextInt();
System.out.print("Enter the value to be inserted:");
obj.insertbeforenode(b,in.nextInt());
break;
case 6:
obj.deleteEnd();
break;
case 7:
obj.deleteBeg();
break;
case 8:
System.out.println("Enter the position at which node has to deleted:");
obj.deleteatpos(in.nextInt());
break;
case 9:
System.out.println("Enter the value to be deleted:");
obj.deletebyval(in.nextInt());
break;
case 10:
System.out.println("Enter the value to be searched:");
System.out.println(obj.search(in.nextInt()));
break;
case 11:
System.out.println("Enter the position of the value to be fetched:");
System.out.println(obj.accessbypos(in.nextInt()));
break;
case 12:
obj.removeduplicates();
break;
case 13:
System.out.println("Enter the value whose occurrence must be counted:");
System.out.println(obj.countoccuerence(in.nextInt()));
break;
case 14:
obj.sortList();
break;
case 15:
obj.reverse();
break;
case 16:
System.out.println("Enter the value of the 2nd linked list:");
int choice;
do{
System.out.println("Enter the value to be inserted to the 2nd linked list:");
obj1.insert(in.nextInt());
System.out.println("Do you want to insert more values in 2nd list(-1 to stop inserting):");
choice=in.nextInt();
}while(choice !=-1);
obj.display(obj.concat(obj,obj1));
break;
case 17:
obj.display();
break;
case 18:
System.out.println(obj.length());
break;}
} while(ch!=-1);
}}
Output:
3.b) Algorithm:
1. Import Scanner.
2. Create the node class with integer val and next pointer to represent each element in
the queue.
3. Create Queue_3060 class with methods insert (for enqueue), delete (for dequeue),
and peek to view the front element without removing it.
4. Use the display method in llist to print elements from head to null, representing the
queue’s current state.
Program:
import java.util.*;
class node {
int val;
node next;
node(){
this.val=0;
this.next=null;}
node(int val){
this.val=val;
this.next=null;}}
class llist {
node head = null;
void insertend(int val){
node n = new node(val);
if(head==null){
head=n; n.next=null; return ;}
node temp=head;
while(temp.next!=null){
temp=temp.next;}
temp.next=n;
n.next=null;}
void deleteBeg(){
if(head==null)
return;
head=head.next;}
void display(){
node temp = head;
if(temp==null){
System.out.println("list is empty"); return ;}
while(temp!=null){
System.out.print(temp.val + "->");
temp=temp.next;}
System.out.print("End\n");}}
public class Queue_3060 {
void insert(llistobj , int val){
obj.insertend(val);}
void delete(llistobj){
obj.deleteBeg();}
void display(llistobj){
obj.display();}
void peek(llistobj){
if(obj.head==null){
System.out.println("Queue is empty");
return ;}
System.out.println(obj.head.val);}
public static void main(String[] args) {
System.out.println("KATHIRVEL M 202203060");
llistobj=new llist();
Queue_3060 object = new Queue_3060();
Scanner in = new Scanner(System.in);
int choice;
do{
System.out.println("Enter the choice(-1 to exit):");
choice = in.nextInt();
switch(choice){
case 1:
System.out.println("Enter the element to be inserted:");
object.insert(obj,in.nextInt());
break;
case 2:
object.delete(obj);
break;
case 3:
object.peek(obj);
break;
case 4:
object.display(obj);
break;}
}while(choice !=-1);
}}
Output:

Result:

Ex.No.:04
Date:

Aim:

4.a) Algorithm:
1. Import java.util.Arrays.
2. Define strings s1, s2, s3, and s4, where s4 is an interned version of s1.
3. Print the values of all initialized strings (s1, s2, s3, s4) to verify their contents.
4. Use == to compare string references and .equals() or .equalsIgnoreCase() to compare
string values and display the results of these comparisons.
5. Invoke various String Methods like charAt(), indexOf(), lastIndexOf(), compareTo(),
substring(), toUpperCase(), toLowerCase(), replace(), split(), toCharArray(), and
contains() and display their results.
Program:
import java.util.Arrays;
public class String_methods_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 202203060");
String s1 = "Welcome to Java";
String s2 = s1;
String s3 = new String("Welcome to Java");
String s4 = s1.intern();
System.out.println("String s1 is " + s1);
System.out.println("String s2 is " + s2);
System.out.println("String s3 is " + s3);
System.out.println("String s4 is " + s4);
System.out.print( "s1==s2 :");
System.out.println(s1 == s2);
System.out.print("s2 == s3 : ");
System.out.println( s2==s3);
System.out.println("s1.equalsIgnoreCase(s2) : " + s1.equalsIgnoreCase(s2));
System.out.println("s1.equals(s3) : " + s1.equals(s3));
System.out.println("s1.compareTo(s3) : " + s1.compareTo(s2));
System.out.println("s2.compareTo(s3) : " + s2.compareTo(s3));
System.out.println("s1.equals(s2) : " +s1.equals(s2));
System.out.println("s2==s4 : " );
System.out.println(s2==s4);
System.out.println("s1 + s2 : " + s1+ s2);
System.out.println("s1.charAt(0): " + s1.charAt(0));
System.out.println("s1.indexOf('j') : " + s1.indexOf('j'));
System.out.println("s1.indexOf(\"to\") : " + s1.indexOf("to"));
System.out.println("s1.lastIndexOf('a') : " + s1.lastIndexOf('a'));
System.out.println("s1.lastIndexOf(\"o\" ,15) : " + s1.lastIndexOf("a",15));
System.out.println("s1.codePointCount(0,s1.length()) : " + s1.codePointCount(0,s1.length()));
System.out.println("String.join(\"-\",s1,s2,s3) : " + String.join("-" ,s1,s2,s3));
System.out.printf("s1.substring(3) : %s\n", (s1.substring(3)));
System.out.println("s1.substring(1,3) : " + s1.substring(1,3));
System.out.println("s1.startsWith(\"Wel\") : " + s1.startsWith("Wel"));
System.out.println("s1.endsWith(\"Java\") : " +s1.endsWith("Java"));
System.out.println("s1.toLowerCase() : " + s1.toLowerCase());
System.out.println("s1.toUpperCase(): " + s1.toUpperCase());
System.out.println("\" Hi\".trim() :" + " Hi".trim());
System.out.println("s1.replace('o' , 'O') : " + s1.replace('o','O'));
System.out.println("s1.replaceAll(\"o\", \"O\") : " + s1.replaceAll("o" , "O"));
System.out.println("s1.replaceFirst(\"o\",\"O\") : " + s1.replaceFirst("o" , "O"));
System.out.println( "s1.split(\"O\") : "+ Arrays.toString(s1.split("O")));
System.out.println("s1.split(\"O\",4) : " + Arrays.toString(s1.split("O",4)));
System.out.println("s1.toCharArray() : " + Arrays.toString(s1.toCharArray()));
System.out.println("s1.codePointAt(0) : " + s1.codePointAt(0));
System.out.println("s1.contains(\"or\") : " + s1.contains("or"));
System.out.println("s1.length() : " + s1.length());}
}

Output:
4.b) Algorithm:
1. Import java.util.Scanner.
2. Use a Scanner to take a string input from the user.
3. If the input string is null, return null.
4. Convert the string to a character array to facilitate in-place swapping.
5. Use two pointers (i starting from the beginning and j from the end) to swap
characters until the middle is reached.
6. Convert the modified character array back to a string and return it.
Program:
import java.util.Scanner;
public class reverse_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 202203060");
Scanner in = new Scanner(System.in);
System.out.print("Enter the string to be reversed:");
System.out.println(rev(in.nextLine()));
}
public static String rev(String A){
if(A==null) return null;
char[] arr = A.toCharArray();
int i=0,j=A.length()-1;
while(i<j){
char temp= arr[i];
arr[i]=arr[j];
arr[j]=temp;
i++;
j--;}
return new String(arr);}
}

Output:

4.c) Algorithm:
1. Accept a string input from the user using a Scanner.
2. If the string is null or empty, print a message indicating no characters are present.
3. Initialize an integer array of size 26 to store the frequency of each lowercase letter.
4. Loop through the string, calculate the index of each character (using ASCII), and
update the corresponding index in the frequency array.
5. Loop through the frequency array and print the letter and its occurrence if the count
is greater than zero.
Program:
import java.util.Scanner;
public class Letter_Occurrence_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 202203060");
Scanner in = new Scanner(System.in);
System.out.println("Enter the input string :");
occurrence(in.nextLine());
}
public static void occurrence(String str){
if(str==null || str.length()==0) System.out.println("Given string contains no character");
int[] alpha=new int[26];
for(int i=0;i<str.length();i++){
int index = str.charAt(i) - 'a';
alpha[index]+=1;}
for (int i = 0; i< 26; i++) {
if(alpha[i]>0) System.out.println("The letter " + (char) (i + 'a' ) + " has occurred " + alpha[i] + "
times");}
}}
Output:

4.d) Algorithm:
1. Accept a string input from the user using a Scanner.
2. If the string is null or empty, return 0, indicating no words are present.
3. Use the split(" ") method to break the string into words by spaces.
4. The length of the resulting array will give the number of words in the string.
5. Return and print the count of words.
Program:
import java.util.Scanner;
public class Count_words_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 202203060");
Scanner in = new Scanner(System.in);
System.out.print("Enter the string:");
System.out.println(count(in.nextLine()));
}
public static int count(String str){
if(str==null || str.length()==0) return 0;
String[] words = str.split(" ");
return words.length;}
}

Output:

4.e) Algorithm:
1. Accept a string input from the user using a Scanner.
2. Create a string ans to store the extracted digits.
3. Loop through each character in the input string.
4. If a character is a digit (i.e., between '0' and '9'), append it to the ans string.
5. Return the string ans containing only the digits and print the result.
Program:
import java.util.Scanner;
public class String_Extraction_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 202203060");
Scanner input = new Scanner(System.in);
System.out.println("Enter the input string : ");
System.out.println(extract(input.nextLine()));
}
public static String extract(String str){
String ans = new String();
for(int i=0;i<str.length();i++){
if(str.charAt(i)>='0' &&str.charAt(i)<='9') ans = ans + str.charAt(i) ;}
return ans;}
}

Output:

4.f) Algorithm:
1. Accept a string input from the user using a Scanner.
2. Create a variable prev to store the previous character, a variable count to count
consecutive occurrences of prev, and an empty string ans to store the compressed
result.
3. Loop through the string starting from the second character.
4. If the current character matches prev, increment the count. If it differs, append the
count and the current character to ans, then reset count to 1 for the new character.
5. After iterating, if the compressed string is longer than the original string, return the
original string. Otherwise, append the count of the last character and return the
compressed string.
Program:
import java.util.Scanner;
public class Compression_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 202203060");
Scanner input = new Scanner (System.in);
System.out.println("Enter the string to be compressed: ");
System.out.println(string_compress(input.nextLine()));
}
public static String string_compress(String str){
if(str==null || str.length()==0) return null;
String ans = new String();
char prev = str.charAt(0);
ans = ans + prev;
int count=1;
for(int i =1;i<str.length();i++){
if(prev==str.charAt(i)) {count++; }
else{
ans = ans + count;
ans = ans + str.charAt(i);
prev=str.charAt(i);
count=1;}
}
if(ans.length()>=str.length()) return str;
if(count!=0) ans = ans + count;
return ans;}
}
Output:

4.g) Algorithm:
1. Accept a string from the user using a Scanner.
2. If the string is empty or null, return true since an empty string is considered a
palindrome.
3. Use a loop to compare characters from the beginning and the end of the string.
4. If any character at position i does not match the character at position str.length() - i -
1, return false.
5. If the loop completes without finding any mismatch, return true, indicating the string
is a palindrome.
Program:
import java.util.Scanner;
public class Palindrome_3060 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the string: ");
String str = in.nextLine();
if(checkPalindrome(str)) System.out.println("The string " + str + " is palindrome.");
else System.out.println("The string " + str + " is not palindrome.");}
public static booleancheckPalindrome(String str){
if(str==null || (str.length()==0)) return true;
for(int i=0;i<str.length();i++){
if(str.charAt(i) != str.charAt(str.length()-i-1)) return false;}
return true;}
}
Output:

4.h) Algorithm:
1. Accept two version strings A and B from the user using Scanner.
2. Split both version strings A and B by the . separator into arrays a1 and b1,
respectively.
3. Iterate through the arrays of version numbers and compare corresponding elements:
4. If a number in a1 is greater than the corresponding number in b1, return A as the
greater version.
5. If a number in b1 is greater than the corresponding number in a1, return B as the
greater version.
6. If all elements are equal, return null indicating both versions are equal.
7. Based on the returned result, print the comparison result (whether one version is
greater than the other or if they are equal).
Program:
import java.util.Arrays;
import java.util.Scanner;
public class Compare_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 202203060");
Scanner in= new Scanner(System.in);
System.out.print("Enter the string:");
String A = in.nextLine();
System.out.print("Enter the string:");
String B = in.nextLine();
String ans = compare_version(A,B);
if(ans.equals(A)) System.out.println(ans + " is greater than " + B);
else if(ans.equals(B)) System.out.println(ans + " is greater than " + A);
else System.out.println(A + " and " + B + " are equal.");}
public static String compare_version(String a ,String b){
String[] a1=a.split("\\.");
String[] b1 = b.split("\\.");
for(int i=0;i<a1.length;i++){
if( Integer.parseInt(a1[i]) >Integer.parseInt(b1[i])) return a;
if(Integer.parseInt(b1[i]) >Integer.parseInt(a1[i])) return b;}
return null;}
}
Output:

4.i) Algorithm:
1. Import java.util.Scanner.
2. If the URL contains spaces, return false (invalid URL).
3. Ensure the URL starts with "http://" or "https://".
4. Find the domain name by extracting the substring between the protocol and the first
slash (/).
5. Extract the URL path between the domain and the query parameters (if any).
6. Extract the query parameters from the URL after the path, replacing '&' with spaces.
Program:
import java.util.Scanner;
public class URLvalidity_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 202203060");
Scanner in = new Scanner(System.in);
System.out.print("Enter the url: ");
String url= in.nextLine();
booleanisvalid = checkValidity(url);
System.out.println(isvalid);
if(isvalid){
System.out.println("Protocol: "+ url.substring(0,url.indexOf(":")));
String domain=new String();
int domain_start= url.indexOf(":")+3;
while(domain_start<url.length() &&url.charAt(domain_start) != '/'){
domain = domain + url.charAt(domain_start) ;
domain_start++;}
System.out.println("Domain Name : " + domain);
String path = new String();
while(domain_start<url.length() &&url.charAt(domain_start)!='?'){
path = path + url.charAt(domain_start);
domain_start++;}
System.out.println("Path : " +path);
domain_start++;
String Query_param=new String();
while(domain_start<url.length()){
if(url.charAt(domain_start)=='&'){
Query_param = Query_param + " ";}
else{
Query_param = Query_param + url.charAt(domain_start);}
domain_start++;}
System.out.println("Query Parameters : " + Query_param);}}
public static booleancheckValidity(String url){
if(url.contains(" ")) return false;
booleaninit= (url.substring(0,8)).compareTo("https://")==0
||(url.substring(0,7)).compareTo("http://")==0;
int mid = url.lastIndexOf('.') - url.indexOf('.');
if(init&& mid>1) return true;
return false;}
}
Output:

4.j) Algorithm:
1. Read the input string and convert it to uppercase.
2. Create a 2D array acronym_store containing known acronym expansions.
3. For each entry in acronym_store, check if the input string matches the first letter of
each word in the acronym.
4. If a match is found, return the expanded acronym by concatenating the matched
words with spaces.
5. If no match is found, return "No Match".
Program:
import java.util.Scanner;
public class AcronymGenerator_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 202203060");
Scanner in = new Scanner(System.in);
System.out.print("Enter the abbreviated string: ");
String str = in.nextLine();
String ans = generator(str.toUpperCase());
if(ans==null) System.out.println("No Match");
else System.out.println(str.toUpperCase() + " : " + ans);}
public static String generator(String str){
String[][] acronym_store = { {"Java" , "Virtual" , "Machine"},
{"Java","Development","Kit"},
{"Java","Runtime","Environment"},
{"Virtual","Reality"},
{"Augmented","Reality"},
};
int flag=0,j,i;
for(i=0;i<acronym_store.length;i++){
String ans = new String();
for( j=0;j<acronym_store[i].length;j++){
if(str.charAt(j)!=acronym_store[i][j].charAt(0)) {flag=0; break;}
else {flag=1;
ans = ans + acronym_store[i][j];
ans = ans + " ";}
}
if(flag==1) {
return ans;}
}
return null;}
}
Output:

Result:

Ex.No.:05
Date:

Aim:

5.a) Algorithm:
1. Read the input string and the key string (word to search for) from the user.
2. Split the input string into an array of words.
3. Initialize a counter variable and iterate through the array of words, incrementing the
counter whenever the key string matches a word in the array.
4. Return the frequency (count) of the key string.
5. Print the frequency count of the key string.
Program:
import java.util.Scanner;
public class Freq_counter_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 202203060");
Scanner input = new Scanner(System.in);
System.out.print("Enter the string:");
String string = input.nextLine();
System.out.print("Enter the key string:");
String key = input.nextLine();
System.out.println(count(string,key));}
public static int count(String str,String key){
String[] in = str.split(" ");
int i=0;
for(String s : in){
if(s.equals(key)) i++;}
return i;}
}

Output:

5.b) Algorithm:
1. Import java.util.Scanner.
2. Read the input string from the user.
3. Find the index of the substring "not" and "bad" in the string.
4. If either "not" or "bad" is not found, or if "not" appears after "bad", return the
original string.
5. If "not" comes before "bad", replace the portion of the string between "not" and
"bad" with the word "good".
6. Concatenate the parts of the string before "not", the word "good", and the part after
"bad", and return the modified string.
Program:
import java.util.Scanner;
public class ItGood_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 202203060");
Scanner input = new Scanner(System.in);
System.out.print("Enter the string:");
System.out.println(good(input.nextLine()));
}
public static String good(String str){
int i=str.indexOf("not");
int j=str.indexOf("bad");
if(i==-1 || j==-1 || str.indexOf("not")>str.indexOf("bad") ) return str;
String ans = new String();
j= j+2;
for(int k=0;k<i;k++){
ans = ans + str.charAt(k);}
ans = ans + " good";
if(j+1<str.length()) ans += str.substring(j+1);
return ans;}
}
Output:
5.c) Algorithm:
1. Import java.util package.
2. Read the input string from the user.
3. Use a HashMap to store the frequency of each character, and a List to keep track of
the order of first occurrence.
4. Loop through the string, update the frequency of each character in the HashMap and
add each unique character to the List.
5. Iterate over the List to print the characters along with their frequencies.
6. After printing the frequency of each character, remove it from the HashMap to avoid
re-processing.

Program:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
public class FreqCharacter_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 202203060");
Scanner in = new Scanner(System.in);
System.out.println("Enter the string:");
charCount(in.nextLine());}
public static void charCount(String str){
HashMap<Character,Integer> h = new HashMap<>();
List<Character> l = new ArrayList<>();
for(int i=0;i<str.length();i++){
if(!h.containsKey(str.charAt(i))) l.add(str.charAt(i));
h.put(str.charAt(i),h.getOrDefault(str.charAt(i),0)+1);}
for(int i=0;i<l.size();i++){
System.out.println(l.get(i)+ " : " + h.get(l.get(i)));
h.remove(l.get(i));}}}
Output:

5.d) Algorithm:
1. Import java.util package.
2. Read the input string from the user using a Scanner.
3. Use an integer array of size 26 to track the occurrence of each letter of the alphabet
4. Use a List<Character> to store the missing characters.
5. Convert the string to lowercase.
6. Loop through the string, and for each alphabet character, mark its occurrence in the
alpha array.
7. After processing the string, check the alpha array for any unmarked (missing) letters.
8. Add missing letters to the miss list.
9. If there are no missing letters, the string is a pangram. Otherwise, print the missing
characters.
Program:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Pangram_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 202203060");
Scanner in = new Scanner(System.in);
System.out.println("Enter the input string:");
String input= in.nextLine();
List<Character> miss = new ArrayList<>();
if(checkPangram(input,miss)) System.out.println("Yes,the string is Pangram");
else{
System.out.println("NO ,the string is not Pangram.");
System.out.print("The missing characters are ");
for(Character ch : miss){
System.out.print(ch + " , ");}
}
}
public static booleancheckPangram(String str,List<Character> miss){
String s = str.toLowerCase();
int[] alpha = new int[26];
for(int i=0;i<s.length();i++){
if(s.charAt(i)==' ') continue;
int index= (int)s.charAt(i)-'a';
if(alpha[index]==0) alpha[index]=1;}
for (int i = 0; i< 26; i++) {
if(alpha[i]==0) miss.add((char) (i + 'a'));}
return miss.isEmpty();}
}
Output:

5.e) Algorithm:
1. Declare name and age as final to ensure they cannot be modified.
2. Provide a private constructor to prevent direct instantiation.
3. Use a static method getObject() to return a single instance of Person (Singleton
Pattern).
4. The static method getObject() checks if an instance (obj) already exists.
5. If not, it creates a new instance of Person. If an instance exists, it returns the existing
one.
6. In the main class, call getObject() to get the singleton instance of Person.
7. Access and print the name and age properties of the Person object.
8. Get another reference of Person using getObject().
9. Compare the two references using .equals() method to check if both references point
to the same object.
10. Print whether both objects are the same using the equals() method.
Program:
class Person{
final String name="VIGNESH";
final int age=20;
private Person(){}
static Person obj;
public static Person getObject(){
if(obj==null) obj = new Person();
return obj;
}}
public class ImmutableClass_3060 {
public static void main(String[] args) {
Person obj = Person.getObject();
System.out.println("Name of " + obj + " " + obj.name);
System.out.println("Age of "+ obj + " " + obj.age);
Person obj1 = Person.getObject();
System.out.println("object 1 equals object 2(True/False) : " + obj.equals(obj1));}
}
Output:
5.f) Algorithm:
1. Declare private fields for the real and imaginary parts of the complex number.
2. Implement a constructor to initialize the real and imaginary parts.
3. Implement methods to perform arithmetic operations:
4. add(): Adds two complex numbers.
5. sub(): Subtracts one complex number from another.
6. mul(): Multiplies two complex numbers.
7. div(): Divides one complex number by another using complex number division
formula.
8. Implement toString() to represent the complex number as a string in the form a + bi
or a - bi.
9. Implement equals() to compare two complex numbers based on their real and
imaginary parts.
10. Create two complex numbers and print them.
11. Perform arithmetic operationsand print results.
12. Compare two complex numbers for equality and print the result.
Program:
class ComplexNumber{
private double real;
private double imaginary;
ComplexNumber(double r ,double i){
this.real=r;
this.imaginary=i;}
public ComplexNumber getter(ComplexNumberobj){
return obj;}
public ComplexNumber add(ComplexNumberobj){
return new ComplexNumber( obj.real + this.real ,obj.imaginary + this.imaginary );}
public ComplexNumber sub(ComplexNumberobj){
return new ComplexNumber( this.real - obj.real ,this.imaginary - obj.imaginary );}
public ComplexNumbermul(ComplexNumberobj){
double preal = (this.real * obj.real) + -1 * (this.imaginary * obj.imaginary);
double pimag = (this.real * obj.imaginary) + (this.imaginary * obj.real);
return new ComplexNumber(preal,pimag);}
public ComplexNumber div(ComplexNumberobj ){
double oim = -1 * obj.imaginary;
double preal1 = (this.real * obj.real) + -1 * (this.imaginary * oim);
double pimag1 = (this.real * oim) + (this.imaginary * obj.real);
double preal2 = (obj.real * obj.real) + -1 * (obj.imaginary * oim);
double pimag2 = (obj.real * oim) + (obj.imaginary * obj.real);
double denom=preal2 + pimag2;
return new ComplexNumber(preal1/denom , pimag1/denom );}
public boolean equals(ComplexNumberobj){
if(this.real == obj.real&&this.imaginary==obj.imaginary) return true;
return false;}
@Override
public String toString(){
String ans =new String();
ans +=real;
if(this.imaginary>=0) ans = ans + " +" + this.imaginary + "i" ;
else ans = ans + this.imaginary + "i" ;
return ans;
}}
public class Complex_no_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 202203060");
ComplexNumberobj = new ComplexNumber(3,4);
ComplexNumber obj1 = new ComplexNumber(1,-2);
System.out.println("obj :" + obj);
System.out.println("obj1 :" + obj1);
ComplexNumber sum = obj.add(obj1);
System.out.println("Sum: "+ sum);
ComplexNumberdif = obj.sub(obj1);
System.out.println("Difference: " + dif);
ComplexNumber product = obj.mul(obj1);
System.out.println("Product: "+ product);
ComplexNumber quotient = obj.div(obj1);
System.out.println("Division: "+quotient);
System.out.println("obj equals obj1 "+ obj.equals(obj1));}
}
Output:

Result:
Ex.No.:06
Date:
Aim:

6.a)Algorithm:
1. Declare class Computer with a string OS.
2. Create a constructor in Computer to initialize OS to "Linux".
3. Define method computing() in Computer to print a message.
4. Declare class Laptop extending Computer.
5. Declare private variables brand, Ram, and price in Laptop.
6. Create a constructor in Laptop to initialize brand, Ram, and price to default values.
7. Define method get() in Laptop to print OS, brand, Ram, and price.
8. Define main class SingleInheritance_3060.
9. Print name and roll number in the main() method.
10. Create an object of Laptop.
11. Call the get() method on the Laptop object.
Program:
class Computer{
String OS;

Computer(){
this.OS="Linux";}
void computing(){
System.out.println("Computer is Computing");}
}
class Laptop extends Computer{
private String brand;
private long Ram;
private double price;
Laptop(){

//super() is called by default


this.brand=null;
this.Ram=0;
this.price=0.0;}
public void get(){
System.out.println(OS + " belongs to parent");

System.out.println(brand + " belongs to child");


System.out.println(Ram + " belongs to child");
System.out.println(price + " belongs to child");}
}
public class SingleInheritance_3060 {

public static void main(String[] args) {


System.out.println("KATHIRVEL M 2022503060");
Laptop obj = new Laptop();
obj.get();}
}

Output:

6.b)Algorithm:
1. Define class Calculator with methods add(long a, long b), sub(long a, long b),
mul(long a, long b), and div(long a, long b).
2. Define class AdvCalc that extends Calculator and overrides methods add(long a, long
b, long c), sub(long a, long b, long c), mul(long a, long b, long c), and div(long a, long
b, long c).
3. Define class SciCalc that extends AdvCalc with methods fact(long a) and pow(int
num, int e).
4. In the main method of class Multilevel_3060, print "KATHIRVEL M 2022503060",
create an object obj of SciCalc, and call and print the results of obj.fact(4),
obj.pow(10, 3), and obj.add(4, 6, 9).
Program:
class Calculator{
long add(long a,long b){return a+b;}
long sub(long a,long b){return a-b;}
long mul(long a,long b){return a*b;}
long div(long a,long b){return a/b;}}

class AdvCalc extends Calculator{


long add(long a,long b,long c){return a + add(b,c);}
long sub(long a,long b,long c){return a - sub(b,c);}
long mul(long a,long b,long c){return a*mul(b,c);}
long div(long a,long b,long c){return a/div(b,c);}}

class SciCalc extends AdvCalc{


long fact(long a) { if(a<=1) return 1;
long f = 1;
long b = a;
while (b > 1) {

f *= mul(b, b - 1);
b=b-2;}
return f;}
long pow(int num,int e){ if(num==0) return 0;
if(e==1) return num;

if(e==0) return 1;
long dup_e=e;
long p=1;
while(dup_e>1){
p*=mul(num,num);

dup_e= dup_e-2;}
if(dup_e==1) p = mul(p,num);
return p;}
}
public class Multilevel_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 2022503060");
SciCalc obj = new SciCalc();
System.out.println(obj.fact(4));

System.out.println(obj.pow(10,3));
System.out.println(obj.add(4,6,9));}
}
Output:

6.c)Algorithm:
1. Define class Phone with fields number, constructors Phone() and Phone(long no), and
method call().
2. Define class Telephone that extends Phone with a constructor Telephone(long n) and
method dialandcall().
3. Define class Mobile that extends Phone with field number2, constructor Mobile(long
no), and methods sendmessage() and connectToInternet().
4. In the main method of class Heirarchical_3060, print "KATHIRVEL M 20225503060",
create an object obj1 of Mobile and call call(), connectToInternet(), and
sendmessage(), then print number and number2 for obj1; create an object obj2 of
Telephone and call call() and dialandcall(), then print number for obj2.
Program:
class Phone{

long number;
Phone(){this.number=0;}
Phone(long no){this.number=no;}
void call(){
System.out.println("Calling......");}

}
class Telephone extends Phone{
Telephone(long n){super(n);}
void dialandcall(){
System.out.println("dialling and calling");}
}

class Mobile extends Phone{


long number2;
Mobile(long no){this.number2=no;}
void sendmessage(){
System.out.println("Sending Message");}

void connectToInternet(){
System.out.println("Connecting to Internet");}
}
public class Heirarchical_3060 {
public static void main(String[] args) {

System.out.println("KATHIRVEL M 20225503060");
Mobile obj1 = new Mobile(840713815);
System.out.println("For obj1-->");
System.out.println("number1: " + obj1.number);
System.out.println("number2: " +obj1.number2);

obj1.call();
obj1.connectToInternet();
obj1.sendmessage();
Telephone obj2 = new Telephone(425568543);
System.out.println("For obj2-->");

System.out.println("number: " + obj2.number);


obj2.call();
obj2.dialandcall();}
}
Output:
6.d)Algorithm:
Multiple Inheritance - class
1. Define class vehicle with fields model, brand, cc and method ride().
2. Define class car with method drive().
3. Define class Bike that extends both vehicle and car, with method speedup().
4. In the main method of class Multiple_inheritance_3060, print "KATHIRVEL M
2022503060" and create an object obj of Bike.
Multiple Inheriatnce-interface
1. Define interface vehicle with fields model and brand, and method ride().
2. Define interface Evehicle with method charge().
3. Define class Car that implements vehicle and Evehicle and provides implementations
for ride() and charge().
4. Define class Bike that implements vehicle and provides an implementation for ride().
5. In the main method of class Multiple_inheritance_3060, print "KATHIRVEL M
2022503060", create an object obj of Bike and call ride(), then create an object car of
Car and call ride() and charge().

i)Program:
Multiple Inheritance - class
class vehicle{

int model;
String brand;
int cc;
void ride(){
System.out.println("Riding");}
}

class car {
void drive(){
System.out.println("Driving");}
}
class Bike extends vehicle,car{

void speedup(){
System.out.println("Raise..");}
}
public class Multiple_inheritance_3060 {
public static void main(String[] args) {

System.out.println("KATHIRVEL M 2022503060");
Bike obj=new Bike();}
}
Output:

ii)Program:
Multiple Inheritance-interface
interface vehicle{
int model=00;
String brand="x";
void ride();}

interface Evehicle{
void charge();}
class Car implements vehicle,Evehicle {
public void ride(){
System.out.println("Driving Car");}

public void charge(){


System.out.println("Recharging Electronic car");}
}
class Bike implements vehicle{
public void ride(){

System.out.println("Bike Raise..");}
}
public class Multiple_inheritance_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 2022503060");

Bike obj=new Bike();


obj.ride();
Car car = new Car();
car.ride();
car.charge();}

}
Output:
6.e)Algorithm:
1. Define class check with method checkEvenorOdd(int a) that uses the modulo
operator to check if a is even or odd.
2. Define class check2 that extends check, overrides checkEvenorOdd(int a) using the
bitwise AND operator to check if a is even or odd, and provides overloaded methods
add(int a, int b) and add(int a, int b, int c).
3. In the main method of class Polymorphism_3060, print "KATHIRVEL M 2022503060",
create an object obj of type check2 and call checkEvenorOdd(2575), create an object
obj2 of type check2 and call add(14, 35) and add(23, 34, 56).
Program:

class check{
boolean checkEvenorOdd(int a){
System.out.println("Checking Using modulo operator");
return a%2==0;}
}

class check2 extends check{


@Override
boolean checkEvenorOdd(int a){ //OverRiding
System.out.println("Using \\'&\\' operator");
return (a&1)==0;}

long add(int a,int b){return a+b;}


long add(int a,int b,int c){return a+b+c;}//Overloading}
public class Polymorphism_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 2022503060");

check obj = new check2();


System.out.println(obj.checkEvenorOdd(2575));
check2 obj2=new check2();
System.out.println(obj2.add(14,35));
System.out.println(obj2.add(23,34,56));}
}
Output:
6.f)Algorithm:
1. Define class Calculator1 with fields default_a and default_b, a default constructor
that sets both to 12 and prints their values, and a parameterized constructor that
takes two integers and prints them. It also defines methods add(long a, long b),
sub(long a, long b), mul(long a, long b), and div(long a, long b).
2. Define class AdvCalc1 that extends Calculator1 with its own default_a field, a default
constructor that calls the parent class constructor using super(), and a parameterized
constructor that calls the parent class constructor with super(n1, n2). It also defines
the method display() to print instance variables of both parent and child classes, and
overloads the methods add(long a, long b, long c), sub(long a, long b, long c),
mul(long a, long b, long c), and div(long a, long b, long c).
3. In the main method of class Super_usage_3060, print "KATHIRVEL M 2022503060",
create an object cal of type AdvCalc1 using both the default and parameterized
constructors, and call display().
Program:
class Calculator1{
int default_a;

int default_b;
Calculator1(){
this.default_a=12;
this.default_b=12;
System.out.println("In parent class constructor with default values "+ default_a + " " +
default_b);}
Calculator1(int n1,int n2){

this.default_a=n1;
this.default_b=n2;
System.out.println("In parent class's parametrized constructor with values "+default_a + " " +
default_b);}
long add(long a,long b){return a+b;}
long sub(long a,long b){return a-b;}
long mul(long a,long b){return a*b;}

long div(long a,long b){return a/b;}}


class AdvCalc1 extends Calculator1{
int default_a;
AdvCalc1(){
super();//called by default}

AdvCalc1(int n1,int n2){


super(n1,n2);}
void display(){
System.out.println("Instance variable of parent class " + super.default_a);
System.out.println("Intance variable of chils class " + default_a);}

long add(long a,long b,long c){return a + add(b,c);}


long sub(long a,long b,long c){return a - sub(b,c);}
long mul(long a,long b,long c){return a*mul(b,c);}
long div(long a,long b,long c){return a/div(b,c);}}
public class Super_usage_3060 {

public static void main(String[] args) {


System.out.println("KATHIRVEL M 2022503060");
AdvCalc1 cal = new AdvCalc1();
cal = new AdvCalc1(30,40);
cal.display();}

Output:
6.g)Algorithm:
1. Define class Calculator2 with fields default_a and default_b, a default constructor
that sets both to 12 and prints their values, and a parameterized constructor that
takes two integers and prints them. It also defines methods add(long a, long b),
sub(long a, long b), mul(long a, long b), and div(long a, long b) that throws
ArithmeticException if division by zero occurs.
2. Define class AdvCalc2 that extends Calculator2 with its own default_a field, a default
constructor that calls the parent class constructor using super(), and a parameterized
constructor that calls the parent class constructor with super(n1, n2). It also
overloads the methods add(long a, long b, long c), sub(long a, long b, long c),
mul(long a, long b, long c), and div(long a, long b, long c) that throws
ArithmeticException.
3. In the main method of class Constructor_inherit_3060, print "KATHIRVEL M
2022503060", create an object cal of type AdvCalc2 using both the default and
parameterized constructors, and call div(4,0) inside a try-catch block to handle the
ArithmeticException.
Program:

class Calculator2 {
int default_a;
int default_b;
Calculator2(){
this.default_a=12;

this.default_b=12;
System.out.println("In parent class constructor with default values "+ default_a + " " +
default_b);}
Calculator2(int n1,int n2){
this.default_a=n1;
this.default_b=n2;
System.out.println("In parent class's parametrized constructor with values "+default_a + " " +
default_b);}
long add(long a,long b){return a+b;}
long sub(long a,long b){return a-b;}

long mul(long a,long b){return a*b;}


long div (long a,long b)throws ArithmeticException{return a/b;}}
class AdvCalc2 extends Calculator2{
int default_a;
AdvCalc2(){

super();//called by default}
AdvCalc2(int n1,int n2){
super(n1,n2);}
long add(long a,long b,long c){return a + add(b,c);}
long sub(long a,long b,long c){return a - sub(b,c);}

long mul(long a,long b,long c){return a*mul(b,c);}


long div (long a,long b,long c) throws ArithmeticException{return a/div(b,c);}}
public class Constructor_inherit_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 2022503060");

AdvCalc2 cal = new AdvCalc2();


cal = new AdvCalc2(30,40);
try{
cal.div(4,0);}
catch(ArithmeticException e){

System.out.println(e);}
}
}
Output:
6.h)Algorithm:

1. Define class Rectangle that implements Cloneable with fields length and breadth, a
constructor to initialize these fields, and a method area() to calculate the area. It
overrides the toString() method to return a string representation of the object and
defines a clone() method to create a shallow copy of the object.
2. In the main method of class ShallowCopyVsDeep_3060, print "KATHIRVEL M
2022503060", create an object obj of Rectangle, and create a shallow copy obj2 by
assigning obj to obj2. Print the instance variables of both objects before and after
modifying obj's values.
3. Create a deep copy of obj using the clone() method and store it in clone. Modify obj's
values and print the instance variables of both obj and clone.

Program:
class Rectangle implements Cloneable{
int length;
int breadth;
Rectangle(int l,int b){

this.length=l;
this.breadth=b;}
int area(){
return length*breadth;}
@Override

public String toString(){


return "Length : " + this.length + " Breadth: " + this.breadth ;}
protected Rectangle clone(){
Rectangle r=new Rectangle(this.length,this.breadth);
return r;}
}
public class ShallowCopyVsDeep_3060 {
public static void main(String[] args) throws CloneNotSupportedException {

System.out.println("KATHIRVEL M 2022503060");
Rectangle obj = new Rectangle(5,2);
Rectangle obj2 = obj; //shallow copy
System.out.println("Instance variables of obj " + obj);
System.out.println( "Instance variables of obj2 " + "Length : " + obj2.length + " " + " Breadth:
" + obj2.breadth);
obj.length=122;

obj.breadth=48;
System.out.println("After changing values of instance variables of obj");
System.out.println("Instance variables of obj " + obj);
System.out.println( "Instance variables of obj2 " + "Length : " + obj2.length + " " + " Breadth:
" + obj2.breadth);
Rectangle clone = obj.clone();

System.out.println("Changing the values of obj");


obj.length=100;
obj.breadth=200;
System.out.println("Instance variables of obj " + obj);
System.out.println( "Instance variables of clone " + "Length : " + clone.length + " " + " Breadth:
" + clone.breadth);}
}

Output:
6.i)Algorithm:
1. Define class Address that implements Cloneable with fields house_no, Street_name,
city, and state, and a constructor to initialize these fields. It overrides the toString()
method to return a string representation of the address and defines a clone()
method to create a shallow copy of the object.
2. Define class bioData that implements Cloneable with fields name, age, gender, and
an Address object a. It defines a constructor to initialize these fields, overrides the
toString() method to return the bio data, and defines a clone() method to create a
shallow copy of the bioData object.
3. In the main method of class ShallowCloningVsDeep, print "KATHIRVEL M
2022503060", create an object obj of bioData, and perform both shallow and deep
cloning.
4. Modify the obj's name and the Street_name of the address inside obj, then print the
original object (obj), shallow clone (shallowclone), and deep clone (deepClone) to
demonstrate the difference between shallow and deep cloning.
Program:
class Address implements Cloneable{
int house_no;

String Street_name;
String city;
String state;
Address(){}
Address(int house_no,String Street_name, String city,
String state){this.house_no=house_no;
this.Street_name=Street_name;
this.city=city;

this.state=state;}
public String toString(){
return "House_no: " + this.house_no + " " +"Street_name: " + " " +this.Street_name + " " +
"City: " + this.city + " " + "State: " + this.state + " ";}
public Address clone(){Address ad = new
Address(this.house_no,this.Street_name,this.city,this.state);
return ad;}}
class bioData implements Cloneable{

String name;
int age;
String gender;
Address a;
bioData( String name,int age, String gender, Address a){this.name=name;this.gender=gender;

this.age=age;
this.a=a;}
public bioData clone(){
bioData b = new bioData(this.name,this.age,this.gender,this.a);
return b;}

public String toString(){


return "Name: " + name + " " + "Age: " +age + " " + "Gender: " + gender + " " + a.toString();}
}
public class ShallowCloningVsDeep {
public static void main(String[] args) throws CloneNotSupportedException {

System.out.println("KATHIRVEL M 2022503060");
bioData obj=new bioData("Vignesh",20,"male",new Address(55,"Ambedkar
Nagar","Chennai","TamilNadu"));
bioData shallowclone=obj.clone();
bioData deepClone = obj.clone();
deepClone.a = deepClone.a.clone();
System.out.println("Obj : " + obj);

System.out.println( "Shallow Clone : " + shallowclone);


System.out.println("After changing values of obj:");
obj.name="Vicky";
obj.a.Street_name = "Gandhi Nagar";
System.out.println( "Obj: " + obj);

System.out.println("ShallowClone: " + shallowclone);


System.out.println("Deep Clone: " + deepClone);}
}

Output:

6.j)Algorithm:
1. Define class Address that implements Cloneable with fields house_no, Street_name,
city, and state, and a constructor to initialize these fields. It overrides the toString()
method to return a string representation of the address and defines a clone()
method to create a shallow copy of the object.
2. Define class bioData that implements Cloneable with fields name, age, gender, and
an Address object a. It defines a constructor to initialize these fields, overrides the
toString() method to return the bio data, and defines a clone() method to create a
shallow copy of the bioData object.
3. In the main method of class ShallowCloningVsDeep, print "KATHIRVEL M
2022503060", create an object obj of bioData, and perform both shallow and deep
cloning.
4. Modify the obj's name and the Street_name of the address inside obj, then print the
original object (obj), shallow clone (shallowclone), and deep clone (deepClone) to
demonstrate the difference between shallow and deep cloning.
Program:
class Rectangle1 {
int length;
int breadth;
Rectangle1(int l, int b) {

this.length = l;
this.breadth = b;}
int area() {
return length * breadth;}
@Override

public String toString() {


return "Length : " + this.length + " Breadth: " + this.breadth;}
@Override
protected void finalize() throws Throwable{
System.out.println("Inside finalize object");}

}
public class finalize_3060 {
public static void main (String[] args) {
System.out.println("KATHIRVEL M 2022503060");
Rectangle1 rec1 = new Rectangle1(54,2);

rec1=null;
System.gc();
System.out.println("Calling garbage Collection..");}}
Output:

6.k)Algorithm:
1. Define class hello in package pack1 with a static method hi() that prints "KATHIRVEL
M 2022503060" and "Hi from pack1 hi method!!". In the main() method of hello
class in pack1, print "Hello this is from package1".
2. Define class hello in package pack2 and import pack1. In the main() method of hello
class in pack2, print "This is from package 2" and call the hi() method from
pack1.hello class.
Program:
package pack1;
public class hello {

public static void hi(){


System.out.println("KATHIRVEL M 2022503060");
System.out.println("Hi from pack1 hi method!!");}
public static void main(String[] args) {
System.out.println("Hello this is from package1");}

}
package pack2;
import pack1.*;
public class hello {
public static void main(String[] args) {

System.out.println("This is from package 2");


pack1.hello.hi();}
}
Output:

6.l)Algorithm:
1. Define interface A with an abstract method sound().
2. Define interface B that extends interface A and provides a default implementation for
sound() that prints "default B sound".
3. Define interface C that extends interface A and provides a default implementation for
sound() that prints "default C sound".
4. Define class Diamond_problem_3060 that implements both interfaces C and B.
Override the sound() method in the class to resolve the diamond problem by explicitly
calling the sound() methods from both interfaces C and B.
5. In the main() method, print "KATHIRVEL M 2022503060", create an object obj of type
A (referencing Diamond_problem_3060), and call the sound() method.

Program:
interface A{
void sound();}
interface B extends A{
default void sound(){

System.out.println("default B sound");}}
interface C extends A{
default void sound(){
System.out.println("default C sound");}}
class Diamond_problem_3060 implements C,B {

public void sound(){


C.super.sound();
B.super.sound();}
public static void main(String[] args) {
System.out.println("KATHIRVEL M 2022503060");

A obj = new Diamond_problem_3060();


obj.sound();}}
Output:

Result:
Ex.No.:07

Date:
Aim:

7.a) Algorithm:

1. Import java.util package


2. Define the Classes A and B where Class A contains an integer field val1 and a method
dispA() to display a message and Class B extends A, contains an integer field val2, and
has a constructor that throws an IllegalArgumentException if the value is negative. It
also has the method dispB() to display a message.
3. Define the Exceptionsclass with a constructor that initializes an array of integers.
4. Define multiple methods to handle different types of exceptions, such as
ArrayIndexOutOfBoundsException, ArrayStoreException, ClassCastException,
IllegalArgumentException, etc.
5. For each method (e.g., outOfBound, Incomtype, cast, etc.), handle the exception
using try-catch blocks. Each method will catch a specific exception type and print a
custom error message.
6. In the main method, create an object of Exceptionsclass and call each method to test
the exception handling.
7. For each exception type, demonstrate the custom error handling in action by calling
the respective methods.
Program:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class A{
Integer val1;
A(){}
A(Integer a){
this.val1=a;}
public void dispA(){
System.out.println("Displaying from A");}
}
class B extends A{

Integer val2;
B(){}
B(Integer b){
if(b<0) throw new IllegalArgumentException();
this.val2=b;}

public void dispB(){


System.out.println("Displaying from B");}
}
class Exceptionsclass {
Integer[] array;

Exceptionsclass(){
array=new Integer[4];
}
void outOfBound(){
try{

for(int i=0;i<6;i++) array[i]=i;}


catch(ArrayIndexOutOfBoundsException e){
System.out.println("index value greater than or equal to array size");}
}
void Incomtype(){

try{
Number[] num = new Double[3];
num[0]=5;}
catch(ArrayStoreException e){
System.out.println("Incompatible type assigned to array ");}
}
void cast(){
try{
B objb= (B)new A();

objb.dispB();}
catch(ClassCastException e){
System.out.println("Incompatible class casting");}
}
void argexception(){

try{
B Bobj=new B(-58);}
catch(IllegalArgumentException e ){
System.out.println("Illegal argument detected");}
}

void IndexoutOfBound(){
try{
String s = "exception";
System.out.println(s.charAt(51));}
catch(IndexOutOfBoundsException e){

System.out.println("Index out of bound exception");}


}
void negativeArraySize(){
try{
array = new Integer[-4];}

catch (NegativeArraySizeException e ){
System.out.println("Array is created with negative Size");}
}
void nullPointer(){
try{
array = null;
System.out.println(array[0]);}
catch(NullPointerException e ){
System.out.println("Cannot access from an empty array");}

}
void numberformat(){
try{
String str = "10000000000";
System.out.println(Integer.parseInt(str));}

catch(NumberFormatException e){
System.out.println("Number Format Exception");}}
void stringIndexoutOfBound(){
try{
String s = "exception";

System.out.println(s.charAt(51));}
catch(StringIndexOutOfBoundsException e){
System.out.println("String Index out of bound exception");}
}
void unsupportedOperation(){

try{
Integer[] arr = {5,6,7};
List<Integer> l = Arrays.asList(arr);
l.add(34);
System.out.println(l);}

catch(UnsupportedOperationException e ){
System.out.println("Some unsupported operation detected");}}
}
public class UncheckedException_3060 {
public static void main(String[] args) {
Exceptionsclass obj = new Exceptionsclass();
obj.outOfBound();
obj.Incomtype();
obj.cast();

obj.argexception();
obj.IndexoutOfBound();
obj.negativeArraySize();
obj.nullPointer();
obj.numberformat();

obj.stringIndexoutOfBound();
obj.unsupportedOperation();}
}
Output:

7.b)
i) Algorithm:
1. Define func() which Attempt a division by zero inside a try block.
2. The main method invokes func(), which throws an exception.
3. Terminate Program: The program crashes with an ArithmeticException due to division
by zero
Program:
public class TryCatch_3060 {
public static void func(){
try{

int a=4/0;
System.out.println(a);}}
public static void main(String[] args) {
func();}
}

Output:
ii) Algorithm:
1. Define func() that contains a try block attempting to divide 4 by 0 which causes an
ArithmeticException.
2. The main method invokes func(), which triggers the exception.
3. The program crashes due to the unhandled exception.
Program:
public class TryCatch_3060 {
public static void func(){
try{

int a=4/0;
System.out.println(a);}
}
public static void main(String[] args) {
func();}

Output:

iii)Algorithm:
1. Define func() that contains a try block that attempts to divide 4 by 0.
2. The ArithmeticException is caught, and its message is printed.
3. Define a Finally Block which executes regardless of exception occurrence, printing
"Will always get executed".
4. The main method calls func(), triggering the exception handling process.
Program:
public class TryCatch_3060 {
public static void func(){

try{
int a=4/0;
System.out.println(a);}
catch(ArithmeticException e){
System.out.println(e);}

finally {
System.out.println("Will always get executed");}
}
public static void main(String[] args) {
func();}

Output:
iv) Algorithm:
1. Define func() which creates an array arr with 5 elements and attempts to access an
out-of-bounds index (arr[7]), triggering an ArrayIndexOutOfBoundsException.
2. Catch ArrayIndexOutOfBoundsException and print the exception message when the
array index is invalid.
3. If the array access was successful, the next operation (division by zero) triggers an
ArithmeticException, which will be caught.
4. Define a Finally Block which executes and prints "Will always get executed"
regardless of the exception type.
5. The main method creates an object of sample and calls func() .
Program:

class sample{
public static void func(){
try{
int[] arr = new int[5];
arr[7]=94;

int a=4/0;
System.out.println(a);}
catch(ArithmeticException e){
System.out.println(e);}
catch(ArrayIndexOutOfBoundsException e ){

System.out.println(e);}
finally {
System.out.println("Will always get executed");}
}
}

public class TryCatch_3060 {


public static void main(String[] args) {
sample obj = new sample();
obj.func();}
}
Output:
v) Algorithm;
1. Define func() which creates an array arr with 5 elements.
2. Loop from i = 0 to i = 9, inside the loop:
a. Attempt to divide i / i (which causes an ArithmeticException when i = 0).
b. If an exception occurs, catch it and print the message.
3. Attempt to assign arr[i], causing an ArrayIndexOutOfBoundsException when i >= 5.
4. Catch ArithmeticException and ArrayIndexOutOfBoundsException through the catch
blocks.
5. If the division fails, it will be caught outside the loop and printed.
6. Define the Finally which is executed after all operations and exceptions, printing "Will
always get executed".

Program:

class sample{
public static void func(){
try{ int[] arr = new int[5];
for(int i=0;i<10;i++){
try { arr[i] = i /i;}

catch(ArithmeticException e){
System.out.println(e);}
catch(ArrayIndexOutOfBoundsException e ){
System.out.println(e);}
}
int a =5/0;}
catch(ArithmeticException e){

System.out.println(e);}
catch(ArrayIndexOutOfBoundsException e ){
System.out.println(e);}
finally {
System.out.println("Will always get executed");}

}
}
public class TryCatch_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 2022503060");

sample obj = new sample();


obj.func();}
}

Output:

vi) Algorithm:
1. Define func() which opens a BufferedWriter inside a try-with-resources block, which
automatically closes the writer when done.
2. Write a string "Hi Hello world" to the file located at
"C:\\java_code\\Exercise_lab\\Week7\\src\\src.txt" using write() method.
3. Declare that func() can throw an IOException to handle file writing exceptions.
4. Instantiate sample object obj and invoke obj.func() to write the content to the file.
5. If the writing operation is successful, print "Content Written Successfully".
6. Wrap the func() call in a try-catch block to handle any exceptions. If any error occurs,
print "Something Went wrong".
Program:
import java.io.*;
class sample{

public static void func() throws IOException {


try(BufferedWriter b = new BufferedWriter(new
FileWriter("C:\\java_code\\Exercise_lab\\Week7\\src\\src.txt"))) {
String str = "Hi Hello world";
b.write(str);}
}
}

public class TryCatch_3060 {


public static void main(String[] args) {
System.out.println("KATHIRVEL M 2022503060");
sample obj = new sample();
try{

obj.func();
System.out.println("Content Written Successfully");}
catch(Exception e){
System.out.println("Something Went wrong");}}}
Output:
7.c) Algorithm:
1. Create a custom exception class InvalidMarkException that extends Exception.
2. Include a constructor that accepts a message and passes it to the superclass.
3. Create the Student class with fields name and totalMarks.
4. Implement the set() method that accepts a name and marks.
5. Validate if marks are between 0 and 100, else throw InvalidMarkException.
6. If marks is not in the valid range, throw an InvalidMarkException with an appropriate
message.
7. Create an object student1 of the Student class.
8. Try to call student1.set() with invalid marks.
9. Catch InvalidMarkException and print the exception message using e.getMessage().

Program:

class InvalidMarkException extends Exception{


InvalidMarkException(String message){
super(message);}
}
class Student{

private String name;


private int totalMarks;
void set(String name,int marks) throws InvalidMarkException {
if(marks<0 || marks>100) throw new InvalidMarkException("Mark must be between zero and
hundred(both inclusive)");
else{
this.name=name;

this.totalMarks=marks;}
}
}
public class CustomException_3060 {
public static void main(String[] args) {

System.out.println("KATHIRVEL M 2022503060");
Student student1=new Student();
try{
student1.set("Kathirvel M",2021);}
catch(InvalidMarkException e){

System.out.println(e.getMessage());}
}
}

Output:

7.d) Algorithm:
1. Define CheckedExceptionPropogation class that implements f1() to throw a
FileNotFoundException and also implements f2() to call f1() and propagate the
exception.
2. In f3(), call f2() inside a try-catch block to handle any exception.
3. Define Propogation_3060 Class and implement P1() which throws an
ArithmeticException by dividing by zero and implement P2() to call P1().
4. In P3(), call P2() inside a try-catch block to handle the unchecked exception
(ArithmeticException).
5. In P3(), catch the ArithmeticException and print error messages.
6. In CheckedExceptionPropogation.f3(), catch any exception thrown by f2() and print
"Checked Exception handled".
7. In main(), create objects of Propogation_3060 and CheckedExceptionPropogation and
call their respective methods (P3() and f3()).
Program:
import java.io.FileNotFoundException;
class CheckedExceptionPropogation{
public void f1() throws FileNotFoundException{
throw new FileNotFoundException();}
public void f2() throws FileNotFoundException{
f1();}
public void f3(){
try{f2();}
catch(Exception e ){
System.out.println("Checked Exception handled");}
}}
public class Propogation_3060 {
public void P1(){
int b =5/0;}
public void P2(){
P1();}
public void P3(){
try{
P2();}
catch(ArithmeticException e){
System.out.println("Unchecked Exception");
System.out.println("Something Went Wrong..");}
}
public static void main(String[] args) {
System.out.println("KATHIRVEL M 2022503060");
Propogation_3060 obj=new Propogation_3060();
obj.P3();
CheckedExceptionPropogation obj2 = new CheckedExceptionPropogation();
obj2.f3();}
}
Output:

7.e) Algorithm:
1. Define CheckedExcept Class and create two overloaded Sport() methods one without
parameters that throws ClassNotFoundException another with a String parameter that
throws both ClassNotFoundException and IOException.
2. Define OverloadesException_3060 Class and then inside it create two overloaded
divide() methods one that takes two integers and throws ArithmeticException another
one that takes an integer array and throws ArrayIndexOutOfBoundsException and
ArithmeticException.
3. In main(), call divide(3,5) and divide(new int[]{2,5,6}). Catch and print
ArithmeticException if any exception occurs.
4. In main(), call both Sport() and Sport("Cricket"). Handle and print
ClassNotFoundException and IOException.
5. Print the result of divide() and handle exceptions appropriately for both divide() and
Sport().
Program:
import java.io.IOException;
class CheckedExcept {
void Sport() throws ClassNotFoundException{
System.out.println("Default Sport");}
void Sport(String s) throws ClassNotFoundException, IOException{
System.out.println("Sport : " + s);}
}
public class OverloadesException_3060 {
public int divide(int n1,int n2) throws ArithmeticException {
return n1/n2;}
public int divide(int[] arr) throws ArrayIndexOutOfBoundsException,ArithmeticException{
System.out.println(5/0);
return arr[arr.length];}
public static void main(String[] args) {
System.out.println("KATHIRVEL M 2022503060");
OverloadesException_3060 obj = new OverloadesException_3060();
try{
System.out.println(obj.divide(3,5));
System.out.println(obj.divide(new int[] {2,5,6}));}
catch(ArithmeticException e){
System.out.println("Something Went wrong");}
CheckedExcept obj2 = new CheckedExcept();
try{
obj2.Sport();
obj2.Sport("Cricket");}
catch (ClassNotFoundException e){
System.out.println(e);}
catch (IOException e){
System.out.println(e);}}}
Output:

7.f)
a) Algorithm:
1. Create ABC Class and define dis1() method that throws ArithmeticException and also
define print() method that throws RuntimeException.
2. Create DEF Class that extends ABC and inside that override dis1() method with a more
specific exception (ArrayIndexOutOfBoundsException). Override print() method with
the same exception (RuntimeException).
3. Create an object obj1 of type ABC and assign it an instance of DEF. Call dis1() and print
the output and Create another object obj2 of type ABC and assign it an instance of
DEF. Call print() and print the output in main.
Program:
class ABC{
void dis1() throws ArithmeticException{
System.out.println("This is from ABC");}
void print() throws RuntimeException{
System.out.println("Print from ABC");}
}
class DEF extends ABC{
void dis1() throws ArrayIndexOutOfBoundsException{
System.out.println("This is from DEF");}
void print() throws RuntimeException{
System.out.println("Print from DEF");}
}
public class OverrideException_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 2022503060");
ABC obj1=new DEF();
obj1.dis1();
ABC obj2 = new DEF();
obj2.print();}
}
Output:
b) Algorithm:
1. Create ABC Class and define dis1() method that throws ArithmeticException and
print() method that throws RuntimeException.
2. Create DEF Class (extends ABC) and override dis1() method with a more specific
exception (ArrayIndexOutOfBoundsException).
3. Override print() method with the same exception (RuntimeException).
4. Create an object obj1 of type ABC and assign it an instance of DEF. Call dis1() and print
the output and create another object obj2 of type ABC and assign it an instance of DEF.
Call print() and print the output in main.
Program:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
class ABC{
void print(){
System.out.println("Print from ABC");}
void print2() throws ReflectiveOperationException{
System.out.println("This is from ABC-print2");}
void print3() throws FileNotFoundException{
System.out.println("Print3 from ABC");}
void print4() throws ParseException {
System.out.println("Print 4 from ABC");}}
class DEF extends ABC{
void print() throws ArithmeticException{
System.out.println("Print from DEF");}
void print2() throws ClassNotFoundException{System.out.println("This is from DEF-print2");}
void print3() {
System.out.println("Print 3 from DEF");}
void print4() throws ParseException {
System.out.println("Print 4 from DEF");}
}
public class OverrideException_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 2022503060");
ABC obj2 = new DEF();
obj2.print();
try{
obj2.print2();}
catch(ReflectiveOperationException e){
System.out.println(e);
}try{
obj2.print3();}
catch (FileNotFoundException e){
System.out.println(e);}
try{
obj2.print4();}
catch(ParseException e){
System.out.println(e);}}}
Output:
Result:

Ex.No.:08

Date:
Aim:

8.a) Algorithm
1. Import javax.swing , java.awt, java.awt.event.ActionEvent,
java.awt.event.ActionListener packages.
2. Use GridBagLayout to layout the quiz components.
3. Add labels, radio buttons (JRadioButton), checkboxes (JCheckBox), text area
(JTextArea), and text field (JTextField).
4. Group JRadioButton options into ButtonGroup to ensure only one option is selected
for each question and provide a submit button (JButton).
5. Capture User Input by creating an actionPerformed() method to handle the submit
button click.
6. Check the answers selected by the user (correct answers increase the score).
7. Compare the user input for each question (radio buttons, checkboxes, text area, text
field) with the correct answers.
8. Display the score and correct answers.
9. Disable Submit Button After Submission.
Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Quiz_3060 extends JFrame implements ActionListener {
JButton submit;
JRadioButton[] ch1;
JRadioButton[] ch2;
ButtonGroup[] grp;
JCheckBox[] cb1;
JTextArea ta;
JTextField tf;
int mark;
public Quiz_3060(){
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx=0;
gbc.gridy=0;
mark=0;
//Qno1
add(new Label("1.Who was the first President of India?"),gbc);
ch1 = new JRadioButton[4];
ch1[0]=new JRadioButton("Jawaharlal Nehru");
ch1[1]=new JRadioButton("Rajendra Prasad");
ch1[2]=new JRadioButton("Narendra Modi");
ch1[3]=new JRadioButton("Abdul Kalam");
grp=new ButtonGroup[4];
grp[0]=new ButtonGroup();
for(int i=0;i<4;i++){
grp[0].add(ch1[i]);}
gbc.gridy++;
add(ch1[0],gbc);
gbc.gridy++;
add(ch1[1],gbc);
gbc.gridy++;
add(ch1[2],gbc);
gbc.gridy++;
add(ch1[3],gbc);
gbc.gridx=0;
gbc.gridy++;
//Qno2
add(new Label("Who invented Java?"),gbc);
ch2 = new JRadioButton[4];
ch2[0]=new JRadioButton("Dennis Ritchie");
ch2[1]=new JRadioButton("James Gosling");
ch2[2]=new JRadioButton("BJarne Stroustrup");
ch2[3]=new JRadioButton("Tim Berners Lee");
grp[1]=new ButtonGroup();
for(int i=0;i<4;i++){
grp[1].add(ch2[i]);}
gbc.gridy++;
add(ch2[0],gbc);
gbc.gridy++;
add(ch2[1],gbc);
gbc.gridy++;
add(ch2[2],gbc);
gbc.gridy++;
add(ch2[3],gbc);
gbc.gridx=0;
gbc.gridy++;
//Qno3
add(new JLabel("Which of the following are object oriented programming language?"),gbc);
cb1=new JCheckBox[4];
cb1[0]=new JCheckBox("Python");
cb1[1]=new JCheckBox("C");
cb1[2]=new JCheckBox("HTML");
cb1[3]=new JCheckBox("Java");
gbc.gridy++;
add(cb1[0],gbc);
gbc.gridy++;
add(cb1[1],gbc);
gbc.gridy++;
add(cb1[2],gbc);
gbc.gridy++;
add(cb1[3],gbc);
gbc.gridx=0;
gbc.gridy++;
//Qno4
add(new Label("Expand AWT in Java"),gbc);
ta = new JTextArea(1,50);
gbc.gridy++;
add(ta,gbc);
gbc.gridx=0;
gbc.gridy++;
//QNo5
add(new Label("Java is dynamically typed Language(Enter true/false)"),gbc);
gbc.gridy++;
tf=new JTextField(5);
add(tf,gbc);
gbc.gridx=0;
gbc.gridy++;
submit = new JButton("Submit");
add(submit,gbc);
setSize(400,500);
setVisible(true);
submit.addActionListener(this);}
public void actionPerformed(ActionEvent e){
if(ch1[1].isSelected()){
mark++;}
if(ch2[1].isSelected()){
mark++;}
if(cb1[0].isSelected() && cb1[3].isSelected()) mark++;
if(ta.getText().toLowerCase().equals("abstract window toolkit")) mark++;
if(tf.getText().toLowerCase().equals("false")) mark++;
String answers = String.format("\n1.Rajendra Prasad\n2.James Gosling\n3.Python and
Java\n4.Abstract Window Toolkit\n5.false (Reason:Java is statically typed language)");
JOptionPane.showMessageDialog(null,"Your Score:"+mark+"/5"+answers);
submit.setEnabled(false);}
public static void main(String[] args) {
new Quiz_3060();}
}
Output:
8.b) Algorithm:
1. Import javax.swing.*, java.awt.*, java.awt.event.*.
2. Create a JFrame layout with a BorderLayout to display the calculator interface.
3. Create a JTextField for input/output display.
4. Set up a JPanel with a GridLayout to hold 16 buttons (digits 0-9, operators, =, and C).
5. Add buttons for digits and operators (+, -, *, /) and define actions for each.
6. Add ActionListener to all buttons to capture user input.
7. Concatenate numbers to the display when digits (0-9) are clicked.
8. Store the first operand when an operator is clicked and update the display to show the
operator.
9. When the = button is clicked, evaluate the expression by calling eval() method.
10. Depending on the operator (+, -, *, /), perform the corresponding arithmetic
operation.
11. When the C button is clicked, clear the display and reset all operands and variables.
Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import static java.awt.GridBagConstraints.RELATIVE;
import static java.awt.GridBagConstraints.REMAINDER;
public class Cal_3060 extends JFrame implements ActionListener {
private JButton[] buttons ;
private JTextField tf;
private Integer op1,op2;
char op;
int ind;
Cal_3060(){
ind=-1;
setLayout(new BorderLayout());
tf=new JTextField(50);
add(tf,BorderLayout.NORTH);
JPanel bt = new JPanel();
bt.setLayout(new GridLayout(4,4));
GridBagConstraints gbc = new GridBagConstraints();
buttons = new JButton[16];
gbc.gridx=0;
gbc.gridy=0;
for(int i=0;i<10;i++){
buttons[i]=new JButton(i+"");
bt.add(buttons[i],gbc);
if(i%4==0){
gbc.gridx=0;
gbc.gridy++;}
else{
gbc.gridx++;}}
tf.setText("");
buttons[10]=new JButton("+");
bt.add(buttons[10],gbc);
gbc.gridx++;
buttons[11]=new JButton("-");
bt.add(buttons[11],gbc);
gbc.gridx=0;
gbc.gridy++;
buttons[12]=new JButton("*");
bt.add(buttons[12],gbc);
gbc.gridx++;
buttons[13]=new JButton("/");
bt.add(buttons[13],gbc);
gbc.gridx++;
buttons[14]=new JButton("=");
bt.add(buttons[14],gbc);
gbc.gridx++;
buttons[15]=new JButton("C");
bt.add(buttons[15],gbc);
add(bt,BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,300);
setVisible(true);
for(int i=0;i<16;i++)
buttons[i].addActionListener(this);}
public void actionPerformed(ActionEvent e ){
if(e.getActionCommand().equals("0") || e.getActionCommand().equals("1") ||
e.getActionCommand().equals("2") || e.getActionCommand().equals("3") ||
e.getActionCommand().equals("4") || e.getActionCommand().equals("5") ||
e.getActionCommand().equals("6") || e.getActionCommand().equals("7") ||
e.getActionCommand().equals("8") || e.getActionCommand().equals("9")){
String str = tf.getText();
tf.setText(str+e.getActionCommand());
str=tf.getText();
if( ind==-1 && (str.contains("+") || str.contains("-") || str.contains("*") || str.contains("/")) ){
for(int i=0;i<str.length();i++){
if(str.charAt(i)==op) {ind=i; break;}}
}
if(ind!=-1)
op2 = Integer.parseInt(str.substring(ind+1));}
if(e.getActionCommand().equals("+") || e.getActionCommand().equals("-") ||
e.getActionCommand().equals("*") || e.getActionCommand().equals("/")){
op1 = Integer.parseInt(tf.getText());
tf.setText(op1 + "" + e.getActionCommand());
String str = tf.getText();
op =str.charAt(str.length()-1);}
if(e.getActionCommand().equals("=")){
eval(op1,op2,op);}
if(e.getActionCommand().equals("C")){
tf.setText("");
op1=0;
op2=0;
ind=-1;}}
public void eval(int op1,int op2,char op){
switch(op){
case '+':
{
tf.setText(op1+op2 + "");
break;}
case '-':{
tf.setText(op1-op2 + "");
break;}
case '*':{
tf.setText(op1*op2 + "");
break;}
case '/':{
tf.setText(op1/op2 + "");
break;}
}
}
public static void main(String[] args) {
new Cal_3060();}
}
Output:
8.c) Algorithm:
1. Create a JFrame with GridBagLayout for arranging fields and buttons.
2. Add five JTextFields with titles for first name, last name, username, phone number,
and recovery email.
3. Add two JPasswordFields for password and confirm password, also with titled borders.
4. Add dropdowns (JComboBox) for date of birth (day, month, year) and gender.
5. Add buttons for "Create Account," "Reset," and "Cancel."
6. Set background colors and add action listeners.
7. On Reset: Clear all input fields and reset dropdowns.
8. On Cancel: Exit the program.
9. Check that the password is at least 8 characters and matches the confirmation.
10. Verify that no required fields are empty.
11. If all checks pass, display a success message.
12. Start the form in the main method by instantiating GoogleAccount_3060.
Program:
import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GoogleAccount_3060 extends JFrame implements ActionListener {
private JTextField[] tf;
private JPasswordField pwd, cpwd;
private JComboBox<String> dayBox, monthBox, yearBox, genderBox;
private JButton create, reset, cancel;
public GoogleAccount_3060() {
setTitle("Create your Google Account");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
tf = new JTextField[5]; // For First name, Last name, Username, Phone, Recovery email
gbc.gridx = 0;
gbc.gridy = 0;
tf[0] = new JTextField(10);
tf[0].setName("First Name");
tf[0].setBorder(BorderFactory.createTitledBorder("First Name"));
add(tf[0], gbc);
gbc.gridx = 1;
tf[1] = new JTextField(10);
tf[1].setName("Last Name");
tf[1].setBorder(BorderFactory.createTitledBorder("Last Name"));
add(tf[1], gbc);
gbc.gridx = 0;
gbc.gridy++;
tf[2] = new JTextField(20);
tf[2].setName("Username");
tf[2].setBorder(BorderFactory.createTitledBorder("Username"));
gbc.gridwidth = 2;
add(tf[2], gbc);
gbc.gridy++;
gbc.gridwidth = 1;
pwd = new JPasswordField(10);
pwd.setBorder(BorderFactory.createTitledBorder("Password"));
add(pwd, gbc);
gbc.gridx = 1;
cpwd = new JPasswordField(10);
cpwd.setBorder(BorderFactory.createTitledBorder("Confirm Password"));
add(cpwd, gbc);
gbc.gridy++;
gbc.gridx = 0;
tf[3] = new JTextField(15);
tf[3].setName("Phone Number");
tf[3].setBorder(BorderFactory.createTitledBorder("Phone Number"));
gbc.gridwidth = 2;
add(tf[3], gbc);
gbc.gridy++;
tf[4] = new JTextField(20);
tf[4].setName("Recovery Email");
tf[4].setBorder(BorderFactory.createTitledBorder("Recovery Email"));
add(tf[4], gbc);
gbc.gridy++;
gbc.gridx = 0;
gbc.gridwidth = 1;
String[] months = {"Month", "January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"};
monthBox = new JComboBox<>(months);
monthBox.setBorder(BorderFactory.createTitledBorder("Month"));
add(monthBox, gbc);
gbc.gridx = 1;
String[] days = {"Day", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14",
"15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30",
"31"};
dayBox = new JComboBox<>(days);
dayBox.setBorder(BorderFactory.createTitledBorder("Day"));
add(dayBox, gbc);
gbc.gridx = 2;
String[] years = {"Year", "1990", "1991", "1992", "1993", "1994", "1995", "1996", "1997",
"1998", "1999", "2000", "2001", "2002", "2003", "2004", "2005"};
yearBox = new JComboBox<>(years);
yearBox.setBorder(BorderFactory.createTitledBorder("Year"));
add(yearBox, gbc);
gbc.gridy++;
gbc.gridx = 0;
gbc.gridwidth = 2;
String[] genders = {"Select Gender", "Male", "Female", "Other"};
genderBox = new JComboBox<>(genders);
genderBox.setBorder(BorderFactory.createTitledBorder("Gender"));
add(genderBox, gbc);
gbc.gridy++;
gbc.gridx = 0;
gbc.gridwidth = 1;
create = new JButton("Create Account");
create.setBackground(Color.RED);
create.setForeground(Color.WHITE);
add(create, gbc);
gbc.gridx = 1;
reset = new JButton("Reset");
reset.setBackground(Color.RED);
reset.setForeground(Color.WHITE);
add(reset, gbc);
gbc.gridx = 2;
cancel = new JButton("Cancel");
cancel.setBackground(Color.RED);
cancel.setForeground(Color.WHITE);
add(cancel, gbc);
create.addActionListener(this);
reset.addActionListener(this);
cancel.addActionListener(this);
setSize(600, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);}
private void resetFields() {
for (JTextField field : tf) {
field.setText("");
field.setBorder(BorderFactory.createTitledBorder(field.getName()));}
pwd.setText("");
pwd.setBorder(BorderFactory.createTitledBorder("Password"));
cpwd.setText("");
cpwd.setBorder(BorderFactory.createTitledBorder("Confirm Password"));
dayBox.setSelectedIndex(0);
monthBox.setSelectedIndex(0);
yearBox.setSelectedIndex(0);
genderBox.setSelectedIndex(0);}
public void actionPerformed(ActionEvent e) {
String password = new String(pwd.getPassword());
String confirmPassword = new String(cpwd.getPassword());
if (e.getSource() == reset) {
resetFields();
return;
} else if (e.getSource() == cancel) {
System.exit(0);
} else if (password.length() < 8) {
JOptionPane.showMessageDialog(null, "Password must be at least 8 characters.");
} else if (!password.equals(confirmPassword)) {
JOptionPane.showMessageDialog(this, "Password and Confirmation do not match.");
} else {
for (JTextField f : tf) {
if (f.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, f.getName() + " should not be empty.");
return;}
}
JOptionPane.showMessageDialog(null, "Account Created Successfully.");}
}
public static void main(String[] args) {
new GoogleAccount_3060();}
}
Output:

Result:

Ex.No.:09
Date:
Aim:

9.a)Algorithm:
1. Show options (Byte Stream Copy, Character Stream Copy, Compare Times, Count
Character, Encrypt and Copy) and prompt the user for their choice.
2. Byte Stream Copy: If selected, open input and output byte streams, copy contents
byte-by-byte, record the time taken, and close the streams.
3. Character Stream Copy: If selected, open input and output character streams, copy
contents character-by-character, record the time taken, and close the streams.
4. Compare Times: Display recorded times for byte and character stream copying.
5. Count Character Occurrence: Count and display occurrences of a specified character
in the input file.
6. Encrypt and Copy: Encrypt each character from input to output using a provided key.
7. Repeat or Exit: Continue looping until the user inputs -1 to exit.
Program:
import java.io.*;
import java.util.Scanner;
public class Q1_3060 {
public static void main(String[] args) throws IOException {
System.out.println("KATHIRVEL M 2022503060");
Scanner sc = new Scanner(System.in);
int choice;
long byteTime=0,chTime=0;
System.out.println("1-byteStream 2-character stream 3-compare 4-count a charcter 5-
encryption and copying");
System.out.println();
do {
System.out.println("Enter the choice:");
choice =sc.nextInt();
switch (choice) {
case 1: {
FileInputStream in=null;
FileOutputStream out=null;
try{
in = new FileInputStream("C:\\java_code\\Exercise_lab\\week9\\f1.txt");
out = new FileOutputStream("C:\\java_code\\Exercise_lab\\week9\\f2.txt");
byteTime = copyBytestream(in, out);
System.out.println("Successfully Copied");}
catch(FileNotFoundException e){
System.out.println(e.getMessage());}
catch(IOException e){
System.out.println(e.getMessage());}
finally{
if(in!=null) in.close();
if(out!=null) out.close();}
break;}
case 2: {
FileReader fin=null;
FileWriter fout=null;
try{
fin = new FileReader("C:\\java_code\\Exercise_lab\\week9\\f1.txt");
fout = new FileWriter("C:\\java_code\\Exercise_lab\\week9\\f2.txt");
chTime = copyCharacterStream(fin, fout);
System.out.println("Successfully Copied");}
catch(FileNotFoundException e){
System.out.println(e.getMessage());}
catch(IOException e){
System.out.println(e.getMessage());}
finally{
if(fin!=null) fin.close();
if(fout!=null) fout.close();}
break;}
case 3: { System.out.printf("Byte Stream :%d\nCharacter Stream:%d", byteTime, chTime);
break;}
case 4: { FileInputStream inf=null;
try{inf = new FileInputStream("C:\\java_code\\Exercise_lab\\week9\\f1.txt");
System.out.println("Enter the character to be counted:");
char c = sc.next().charAt(0);
System.out.println(countOccurence(c, inf));}
catch(FileNotFoundException e){
System.out.println(e.getMessage());}
catch(IOException e){
System.out.println(e.getMessage());}
finally{
if(inf!=null) inf.close();}
break;}
case 5: {FileReader fin=null;
FileWriter fout=null;
try{fin = new FileReader("C:\\java_code\\Exercise_lab\\week9\\f1.txt");
fout = new FileWriter("C:\\java_code\\Exercise_lab\\week9\\f2.txt");
System.out.print("Enter the key for encryption:");
int key = sc.nextInt();
encrypt(fin, fout, key);
System.out.println("Successfully Encrypted and Copied");}
catch(FileNotFoundException e){
System.out.println(e.getMessage());}
catch(IOException e){
System.out.println(e.getMessage());}
finally{
if(fin!=null) fin.close();
if(fout!=null) fout.close();}
break;}}
}while(choice!=-1);}
public static int countOccurence(char c,FileInputStream fin) throws IOException{
int n,count=0;
while((n=fin.read())!=-1){
if(c==(char)n) count++;}
return count;}
public static long copyBytestream(FileInputStream in,FileOutputStream out) throws
IOException{
long startTime =System.currentTimeMillis();
int c;
while((c=in.read())!=-1){
out.write(c);}
out.close();
long TotalTime = System.currentTimeMillis()-startTime;
return TotalTime;}
public static long copyCharacterStream(FileReader in, FileWriter out)throws IOException{
long startTime = System.currentTimeMillis();
int c;
String s="";
while((c=in.read())!=-1){
char ch = (char)c;
s+=ch;}
out.write(s);
out.close();
long TotalTime = System.currentTimeMillis()-startTime;
return TotalTime;}
public static void encrypt(FileReader fi,FileWriter fo,int key) throws IOException{
int c;
while((c=fi.read())!=-1){
fo.write( (c + key)%256);}}}

Output:
9.b) Algorithm:
1. Display the menu options for different file operations.
2. Prompt the user to choose an option until choice = -1 is entered.
3. Buffered Byte Stream: Copy file using buffered byte stream, timing the operation.
4. Buffered Character Stream: Copy file using buffered character stream, timing the
operation.
5. Non-Buffered Operations: Perform and time byte stream copy, character stream copy,
and encryption using non-buffered streams.
6. Compare Times: Display times for buffered and non-buffered operations.
7. Count Character: Count occurrences of a specified character in the file using a buffered
input stream.
8. Buffered Encryption: Encrypt and copy file using buffered character streams with a
provided encryption key.
9. Declare countOccurrence() that Counts character occurrences.
10. Declare copyBytestream(), copyCharacterStream(), encrypt() that perform and time
file operations for copying and encryption.
11. Exit loop if -1 is chosen.
Program:
import java.io.*;
import java.util.Scanner;
public class Q2_3060 {
public static void main(String[] args) throws IOException{
System.out.println("KATHIRVEL M 2022503060");
Scanner sc = new Scanner(System.in);
int choice;
long BbyteTime=0,BchTime=0,BenTime=0;
long byteTime=0,chTime=0,enTime=0;
System.out.println("1-Buffered byteStream 2-Buffered character stream 3-non-Buffered
Operations 4-compare 5-count a character 6-encryption and copying");
System.out.println();
do {
System.out.println("Enter the choice:");
choice =sc.nextInt();
switch (choice) {
case 1: {
FileInputStream in=null;
FileOutputStream out=null;
BufferedInputStream bi=null;
BufferedOutputStream bo=null;
try{
in = new FileInputStream("C:\\java_code\\Exercise_lab\\week9\\f1.txt");
out = new FileOutputStream("C:\\java_code\\Exercise_lab\\week9\\f2.txt");
bi = new BufferedInputStream(in);
bo = new BufferedOutputStream(out);
BbyteTime = copyBytestream(bi, bo);
System.out.println("Successfully Copied");}
catch(FileNotFoundException e){
System.out.println(e.getMessage());}
catch(IOException e){
System.out.println(e.getMessage());}
finally{
if(bi!=null) bi.close();
if(bo!=null) bo.close();}
break;}
case 2: {
FileReader fin=null;
FileWriter fout=null;
BufferedReader br = null;
BufferedWriter bw=null;
try{ fin = new FileReader("C:\\java_code\\Exercise_lab\\week9\\f1.txt");
fout = new FileWriter("C:\\java_code\\Exercise_lab\\week9\\f2.txt");
br = new BufferedReader(fin);
bw = new BufferedWriter(fout);
BchTime = copyCharacterStream(br,bw);
System.out.println("Successfully Copied");}
catch(FileNotFoundException e){
System.out.println(e.getMessage());}
catch(IOException e){
System.out.println(e.getMessage());}
finally{
if(br!=null) br.close();
if(bw!=null) bw.close();}
break;}
case 3:{
System.out.print("Enter the Key:");
int key = sc.nextInt();
try {
byteTime = Q1_3060.copyBytestream(new
FileInputStream("C:\\java_code\\Exercise_lab\\week9\\f1.txt"), new
FileOutputStream("C:\\java_code\\Exercise_lab\\week9\\f2.txt"));
chTime = Q1_3060.copyCharacterStream(new
FileReader("C:\\java_code\\Exercise_lab\\week9\\f1.txt"), new
FileWriter("C:\\java_code\\Exercise_lab\\week9\\f2.txt"));
enTime = Q1_3060.encrypt(new FileReader("C:\\java_code\\Exercise_lab\\week9\\f1.txt"),
new FileWriter("C:\\java_code\\Exercise_lab\\week9\\f2.txt"), key);}
catch(IOException e){
System.out.println(e.getMessage());}
break;}
case 4: {
System.out.printf("Buffered Byte Stream :%d\nBuffered Character Stream:%d\nBuffered
Encryption:%d\n", BbyteTime, BchTime,BenTime);
System.out.printf("Byte Stream :%d\nCharacter Stream:%d\nEncryption:%d", byteTime,
chTime,enTime);
break;}
case 5: {
FileInputStream inf=null;
BufferedInputStream bi=null;
try{ inf = new FileInputStream("C:\\java_code\\Exercise_lab\\week9\\f1.txt");
bi=new BufferedInputStream(inf);
System.out.println("Enter the character to be counted:");
char c = sc.next().charAt(0);
System.out.println(countOccurence(c, bi));}
catch(FileNotFoundException e){
System.out.println(e.getMessage());}
catch(IOException e){
System.out.println(e.getMessage());}
finally{
if(bi!=null) bi.close();}
break;}
case 6: {
FileReader fin=null;
FileWriter fout=null;
BufferedReader br=null;
BufferedWriter bw=null;
try{
fin = new FileReader("C:\\java_code\\Exercise_lab\\week9\\f1.txt");
fout = new FileWriter("C:\\java_code\\Exercise_lab\\week9\\f2.txt");
System.out.print("Enter the key for encryption:");
int key = sc.nextInt();
br=new BufferedReader(fin);
bw=new BufferedWriter(fout);
BenTime=encrypt(br, bw, key);
System.out.println("Successfully Encrypted and Copied");}
catch(FileNotFoundException e){
System.out.println(e.getMessage());}
catch(IOException e){
System.out.println(e.getMessage());}
finally{
if(br!=null) br.close();
if(bw!=null) bw.close();}
break;}}
}while(choice!=-1);}
public static int countOccurence(char c,BufferedInputStream fin) throws IOException{
int n,count=0;
while((n=fin.read())!=-1){
if(c==(char)n) count++;}
return count;}
public static long copyBytestream(BufferedInputStream in,BufferedOutputStream out)
throws IOException{
long startTime =System.currentTimeMillis();
int c;
while((c=in.read())!=-1){
out.write(c);}
long TotalTime = System.currentTimeMillis()-startTime;
return TotalTime;}
public static long copyCharacterStream(BufferedReader in, BufferedWriter out)throws
IOException{
long startTime = System.currentTimeMillis();
String s=new String();
while((s=in.readLine())!=null){
out.write(s);}
long TotalTime = System.currentTimeMillis()-startTime;
return TotalTime;}
public static long encrypt(BufferedReader fi,BufferedWriter fo,int key) throws IOException{
long s=System.currentTimeMillis();
int c;
while((c=fi.read())!=-1){
fo.write( (c + key)%256);}
long tot=System.currentTimeMillis()-s;
return tot;}
}
Output:
9.c) Algorithm:
1. Initialize Streams by opening file input (f1.txt) and output (f2.txt) streams.
2. Create InputStreamReader and OutputStreamWriter for UTF-8 encoding.
3. Use buffered readers and writers for efficient line-by-line copying.
4. Read each line from the input file and write it to the output file.
5. Print a success message once completed.
6. Handle Exceptions by catching FileNotFoundException and IOException errors, printing
error messages.
7. Ensure all resources are closed in the finally block.
Program:
import java.io.*;
public class Q3_3060 {
public static void copyFile(FileInputStream fi , FileOutputStream fo) throws IOException{
InputStreamReader ir = new InputStreamReader(fi,"UTF-8");
BufferedReader br = new BufferedReader(ir);
OutputStreamWriter or = new OutputStreamWriter(fo,"UTF-8");
BufferedWriter bw=new BufferedWriter(or);
String str;
try {
while ((str = br.readLine()) != null) {
bw.write(str);
bw.newLine();}
System.out.println("File Copied Successfully");}
catch(IOException e){
System.out.println(e.getMessage());}
finally{
br.close();
bw.close();}}
public static void main(String[] args) throws IOException{
System.out.println("KATHIRVEL M 2022503060");
FileInputStream fi=null;
FileOutputStream fo=null;
try{
fi = new FileInputStream("C:\\java_code\\Exercise_lab\\week9\\f1.txt");
fo = new FileOutputStream("C:\\java_code\\Exercise_lab\\week9\\f2.txt");
copyFile(fi,fo);}
catch(FileNotFoundException e){
System.out.println(e.getMessage());}
catch(IOException e){
System.out.println(e.getMessage());}
finally{
if(fi!=null) fi.close();
if(fo!=null) fo.close();}
}
}
Output:
9.d) Algorithm:
1. Prompt for a student’s registration number, name, GPA, and grade.
2. Create a Student object and serialize it (append if the file exists).
3. Ask for a registration number and a new GPA.
4. Read all students into a list, updating the specified student’s GPA.
5. Clear the file, then rewrite all student objects from the list.
6. Read each student from the file and print their registration number and grade.
7. Manage FileNotFound, EOFException, and general IOException exceptions.
8. Use try-with-resources to automatically close file streams after use.
Program:
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Student implements Serializable {
String name;
int regno;
double GPA;
String grade;
public Student(int regno, String name, double GPA, String grade) {
this.regno = regno;
this.name = name;
this.GPA = GPA;
this.grade = grade;}
public void add() throws IOException {
File file = new File("C:\\java_code\\Exercise_lab\\week9\\f1.txt");
boolean append = file.exists() && file.length() > 0;
try (FileOutputStream fos = new FileOutputStream(file, append);
ObjectOutputStream oos = append ? new AppendObjectOutputStream(fos) : new
ObjectOutputStream(fos)) {
oos.writeObject(this);}}
public static void updateGPA(int regno, double newGPA) throws Exception {
List<Student> studList = new ArrayList<>();
File file = new File("C:\\java_code\\Exercise_lab\\week9\\f1.txt");
if (!file.exists() || file.length() == 0) {
throw new FileNotFoundException("File is empty or doesn't exist.");}
try (FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis)) {
Student st;
while (true) {
try {
st = (Student) ois.readObject();
if (st.regno == regno) {
st.GPA = newGPA;}
studList.add(st);
} catch (EOFException e) {
break;}}}
clearFile();
try (FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
for (Student student : studList) {
oos.writeObject(student);
}}
}
public static void displayGrades() throws IOException, ClassNotFoundException {
File file = new File("C:\\java_code\\Exercise_lab\\week9\\f1.txt");
if (!file.exists() || file.length() == 0) {
System.out.println("No data to display.");
return;}
try (FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis)) {
Student st;
while (true) {
try {
st = (Student) ois.readObject();
System.out.println("Regno: " + st.regno + ", Grade: " + st.grade);
} catch (EOFException e) {
break;}}}
}
private static void clearFile() throws IOException {
FileOutputStream fos = new
FileOutputStream("C:\\java_code\\Exercise_lab\\week9\\f1.txt");
fos.close();
}
static class AppendObjectOutputStream extends ObjectOutputStream {
public AppendObjectOutputStream(OutputStream out) throws IOException {
super(out);
}
@Override
protected void writeStreamHeader() throws IOException {
reset();}
}
}
public class Q4_3060 {
public static void main(String[] args) {
System.out.println("KATHIRVEL M 2022503060");
Scanner sc = new Scanner(System.in);
try {
System.out.println("Enter regno, name, GPA, and grade of the student:");
Student s = new Student(sc.nextInt(), sc.next(), sc.nextDouble(), sc.next());
s.add();
System.out.println("Student added.");
System.out.println("Enter the regno to update and the new GPA:");
int regnoToUpdate = sc.nextInt();
double newGPA = sc.nextDouble();
Student.updateGPA(regnoToUpdate, newGPA);
System.out.println("GPA updated.");
System.out.println("Displaying all students' grades:");
Student.displayGrades();
} catch (Exception e) {
e.printStackTrace();}}
}
Output:
Result:
Ex.No.:10
Date:
Aim:

10.a)Algorithm:
1. Create buttons for "Quick Wash," "Normal Wash," "Heavy Duty Wash," and "Reset."
Add a text field to display the timer.
2. Use FlowLayout for arranging components and register action listeners for each
button.
3. Disable all buttons except the one corresponding to the selected mode.
4. Start a Timer with a TimerTask to decrement the countdown value and update the
text field.
5. Enable Buttons After Countdown:
6. When the countdown reaches zero, cancel the timer and re-enable all buttons.
7. On "Reset" button press, cancel the timer (if active), set the display to "0," and
enable all buttons.
Program:
import javax.swing.*;
import java.awt.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;
import java.util.TimerTask;
public class Washing_Machine_3060 extends JFrame implements ActionListener {
JButton Qw,Nw,Hd,Reset;
JTextField Display;
Timer timer;
TimerTask task;
public Washing_Machine_3060(){

Qw=new JButton("Quick Wash");


add(Qw);
Nw=new JButton("Normal Wash");
add(Nw);
Hd=new JButton("Heavy Duty Wash");
add(Hd);

Reset=new JButton("Reset");
add(Reset);
Display=new JTextField(50);
add(Display);
setSize(400,500);

setVisible(true);
setLayout(new FlowLayout());
Qw.addActionListener(this);
Nw.addActionListener(this);
Hd.addActionListener(this);

Reset.addActionListener(this);}
public void actionPerformed(ActionEvent e) {
timer=new Timer();
if(e.getSource()==Qw){
Qw.setEnabled(false);

Hd.setEnabled(false);
Nw.setEnabled(false);
task = new TimerTask() {
int count=10;
@Override

public void run() {


Display.setText(String.valueOf(count));
count--;
if(count<0){ timer.cancel();
Qw.setEnabled(true);
Hd.setEnabled(true);
Nw.setEnabled(true);}}
};
timer.scheduleAtFixedRate(task,0,1000);}

else if(e.getSource()==Nw){
Qw.setEnabled(false);
Hd.setEnabled(false);
Nw.setEnabled(false);
task=new TimerTask(){

int count=20;
public void run(){
Display.setText(String.valueOf(count));
count--;
if(count<0) {timer.cancel();

Qw.setEnabled(true);
Hd.setEnabled(true);
Nw.setEnabled(true);}}
};
timer.scheduleAtFixedRate(task,0,1000);}

else if(e.getSource()==Hd){
Qw.setEnabled(false);
Hd.setEnabled(false);
Nw.setEnabled(false);
task=new TimerTask(){

int count=30;
public void run(){
Display.setText(String.valueOf(count));
count--;
if(count<0) {timer.cancel();
Qw.setEnabled(true);
Hd.setEnabled(true);
Nw.setEnabled(true);}}
};

timer.scheduleAtFixedRate(task,0,1000);}
else if( e.getSource()==Reset ){
if(task!=null) task.cancel();
Display.setText("0");
Qw.setEnabled(true);

Hd.setEnabled(true);
Nw.setEnabled(true);}}
public static void main(String[] args) {
new Washing_Machine_3060();}
}

Output:

10.b)Algorithm:
1. Define Thread1 and Thread2 classes by extending Thread and overriding the run()
method with their specific logic.
2. In Thread1, print numbers from 0 to 999,999.
3. In Thread2, print numbers from 1,000,000 down to 0.
4. Create instances of Thread1 and Thread2 in the main() method.
5. Use the start() method on both thread instances to execute their run() methods
concurrently.
6. Threads execute their run() methods simultaneously, printing their respective outputs
independently.
Program:
class Thread1 extends Thread{
public void run(){
for(int i=0;i<1000000;i++){
System.out.println("Thread1: "+ i);}}
}
class Thread2 extends Thread{

public void run(){


for(int i=1000000;i>=0;i--){
System.out.println("Thread2: " + i);}}
}
public class Threading_3060 {

public static void main(String[] args) {


Thread1 t1=new Thread1();
Thread2 t2 = new Thread2();
t1.start();
t2.start();}}

Output:
10.c) Algorithm:
1. Create a Rectangle class with length and breadth as attributes.
2. Add methods for calculating area (area()), string representation (toString()), and deep
cloning (clone()).
3. Instantiate a Rectangle object (obj) with initial dimensions.
4. Assign it to another reference (obj2) for a shallow copy.
5. Print instance variables of obj and obj2.
6. Modify obj's dimensions and observe changes in both obj and obj2 to illustrate shallow
copying.
7. Use the clone() method to create a deep copy of obj and assign it to clone.
8. Modify obj's dimensions again.
9. Print instance variables of obj and clone to show that changes in obj do not affect
clone.
Program:
class Rectangle implements Cloneable{
int length;

int breadth;
Rectangle(int l,int b){
this.length=l;
this.breadth=b;}
int area(){

return length*breadth;
}
@Override
public String toString(){
return "Length : " + this.length + " Breadth: " + this.breadth ;}

protected Rectangle clone(){


Rectangle r=new Rectangle(this.length,this.breadth);
return r;}
}
public class ShallowCopyVsDeep_3060 {

public static void main(String[] args) throws CloneNotSupportedException {


System.out.println("KATHIRVEL M 2022503060");
Rectangle obj = new Rectangle(5,2);
Rectangle obj2 = obj; //shallow copy
System.out.println("Instance variables of obj " + obj);

System.out.println( "Instance variables of obj2 " + "Length : " + obj2.length + " " + " Breadth:
" + obj2.breadth);

obj.length=122;
obj.breadth=48;
System.out.println("After changing values of instance variables of obj");
System.out.println("Instance variables of obj " + obj);
System.out.println( "Instance variables of obj2 " + "Length : " + obj2.length + " " + " Breadth:
" + obj2.breadth);

Rectangle clone = obj.clone();


System.out.println("Changing the values of obj");
obj.length=100;
obj.breadth=200;
System.out.println("Instance variables of obj " + obj);

System.out.println( "Instance variables of clone " + "Length : " + clone.length + " " + " Breadth:
" + clone.breadth);}

}
Output:

10.d)Algorithm:
1. Define Cloneable Classes and implement clone() in Address and bioData to support
cloning.
2. Instantiate bioData with nested Address.
3. Shallow Clone: Clone bioData without cloning Address.
4. Deep Clone: Clone both bioData and its Address object.
5. Modify obj and observe changes in shallow and deep clones to illustrate differences.

Program:
class Address implements Cloneable{
int house_no;
String Street_name;
String city;

String state;
Address(){}
Address(int house_no,String Street_name, String city,
String state){this.house_no=house_no;
this.Street_name=Street_name;

this.city=city;
this.state=state;}
public String toString(){
return "House_no: " + this.house_no + " " +"Street_name: " + " " +this.Street_name + " " +
"City: " + this.city + " " + "State: " + this.state + " ";}
public Address clone(){Address ad = new
Address(this.house_no,this.Street_name,this.city,this.state);
return ad;}}
class bioData implements Cloneable{

String name;
int age;
String gender;
Address a;
bioData( String name,int age, String gender, Address a){this.name=name;this.gender=gender;
this.age=age;
this.a=a;}
public bioData clone(){
bioData b = new bioData(this.name,this.age,this.gender,this.a);
return b;}

public String toString(){


return "Name: " + name + " " + "Age: " +age + " " + "Gender: " + gender + " " + a.toString();}
}
public class ShallowCloningVsDeep {
public static void main(String[] args) throws CloneNotSupportedException {

System.out.println("KATHIRVEL M 2022503060");
bioData obj=new bioData("Vignesh",20,"male",new Address(55,"Ambedkar
Nagar","Chennai","TamilNadu"));
bioData shallowclone=obj.clone();
bioData deepClone = obj.clone();
deepClone.a = deepClone.a.clone();
System.out.println("Obj : " + obj);

System.out.println( "Shallow Clone : " + shallowclone);


System.out.println("After changing values of obj:");
obj.name="Vicky";
obj.a.Street_name = "Gandhi Nagar";
System.out.println( "Obj: " + obj);

System.out.println("ShallowClone: " + shallowclone);


System.out.println("Deep Clone: " + deepClone);}
}

Output:
10.e)Algorithm:
1. CheckedExcept has overloaded Sport() methods that throw checked exceptions.
2. OverloadesException_3060 defines divide() methods throwing runtime exceptions.
3. Use try-catch blocks to handle checked exceptions (ClassNotFoundException,
IOException) and runtime exceptions (ArithmeticException,
ArrayIndexOutOfBoundsException).
4. Test the overloaded divide() methods with various inputs, catching exceptions for
invalid operations (e.g., division by zero).
5. Invoke both Sport() methods with and without arguments, managing their exceptions
in a try-catch block.
6. Print method outputs when successful and error messages when exceptions occur.
Program:

import java.io.IOException;
class CheckedExcept {
void Sport() throws ClassNotFoundException{
System.out.println("Default Sport");}
void Sport(String s) throws ClassNotFoundException, IOException{

System.out.println("Sport : " + s);}}


public class OverloadesException_3060 {
public int divide(int n1,int n2) throws ArithmeticException {
return n1/n2;}
public int divide(int[] arr) throws ArrayIndexOutOfBoundsException,ArithmeticException{

System.out.println(5/0);
return arr[arr.length];}
public static void main(String[] args) {
System.out.println("KATHIRVEL M 2022503060");

OverloadesException_3060 obj = new OverloadesException_3060();


try{
System.out.println(obj.divide(3,5));
System.out.println(obj.divide(new int[] {2,5,6}));}
catch(ArithmeticException e){

System.out.println("Something Went wrong");}


CheckedExcept obj2 = new CheckedExcept();
try{
obj2.Sport();
obj2.Sport("Cricket");}

catch (ClassNotFoundException e){


System.out.println(e);}
catch (IOException e){
System.out.println(e);}}}
Output:

Result:
Ex.No.:11
Date:
Aim:

11.a)Algorithm:
1. The server starts on a specified port (52135) using ServerSocket.
2. It waits for a client connection and accepts it, establishing a Socket.
3. The client connects to the server using the same port and establishes a Socket.
4. The client takes input using Scanner and sends the message to the server via
DataOutputStream.
5. The server receives the message using DataInputStream.
6. It processes the message (e.g., converts it to uppercase) and sends it back to the
client using DataOutputStream.
7. The client reads the processed message from the server using DataInputStream.
8. The client displays the server's response on the console.
9. The server remains in a loop to accept more clients.
10. The client disconnects after receiving the response.
Program:
Server:
import java.io.DataInputStream;

import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Sever {
public static void main(String[] args) {

try{
ServerSocket ss=new ServerSocket(52135);
System.out.println("Server started");
while(true){
try{

Socket socket = ss.accept();


System.out.println("Client accepted");
DataInputStream in =new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
String fromClient = in.readUTF();

System.out.println("Message from client " + fromClient);


out.writeUTF(fromClient.toUpperCase());}
catch(Exception e ){
System.out.println(e);}}
}

catch(Exception e){
System.out.println(e);}
}}
Client:
import java.io.DataInputStream;

import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {

try{
Socket socket = new Socket("localhost",52135);
System.out.println("Client requested for connection");
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out=new DataOutputStream(socket.getOutputStream());

Scanner sc = new Scanner(System.in);


String str = sc.next();
out.writeUTF(str);
System.out.println(in.readUTF());}
catch(Exception e){
System.out.println(e);}}}
Output:

11.b)Algorithm:
1. Both client and server create a DatagramSocket for communication.
2. The client sends a message, and the server listens on a specific port (52623).
3. The client reads user input, converts it into bytes, and sends it to the server using
DatagramPacket.
4. The server receives the message from the client using DatagramSocket.receive() and
processes it (e.g., converting the message to uppercase).
5. The server creates a DatagramPacket with the processed message and sends it back
to the client.
6. The client receives the response from the server, converts it into a string, and displays
it on the console.
7. Both client and server close their DatagramSocket once communication is complete.
Program:
Client:
import java.net.DatagramPacket;

import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.*;
public class Capitalize_UDP_Client {
public static void main(String[] args) {

try {
DatagramSocket ds = new DatagramSocket();
Scanner sc = new Scanner(System.in);
byte[] toServer = sc.nextLine().getBytes();
DatagramPacket sPacket=new DatagramPacket(toServer,toServer.length,
InetAddress.getByName("localhost"),52623);
ds.send(sPacket);

byte[] fromServer=new byte[toServer.length];


DatagramPacket rPacket=new DatagramPacket(fromServer,fromServer.length);
ds.receive(rPacket);
String str=new String(rPacket.getData(),0,rPacket.getLength());
System.out.println("Received Packet: " + str);}

catch(Exception e){
e.printStackTrace();}}
}
Server:
import java.net.DatagramPacket;

import java.net.DatagramSocket;
public class Capitalize_UDP_Server {
public static void main(String[] args) {
try{
DatagramSocket ds=new DatagramSocket(52623);
byte[] recArr = new byte[10000];
DatagramPacket rPacket= new DatagramPacket(recArr,recArr.length);
ds.receive(rPacket);

String str = new String(rPacket.getData(),0,rPacket.getLength());


str=str.toUpperCase();
byte[] sArr=str.getBytes();
DatagramPacket sPacket=new
DatagramPacket(sArr,sArr.length,rPacket.getAddress(),rPacket.getPort());
ds.send(sPacket);
ds.close();}

catch (Exception e){


e.printStackTrace();
}}
}
Output:
11.c)Algorithm:
1. The client reads the email input from the user.
2. It converts the email to a byte array and sends it to the server via a DatagramPacket.
3. The server listens on port 9999 and receives the email message from the client.
4. It processes the email and checks if it is valid using a set of rules (presence of @,
domain validation, etc.).
5. The server checks the email format by:
6. Ensuring the @ symbol exists between the local part and domain.
7. Validating that the local and domain parts contain only allowed characters.
8. Ensuring the domain doesn’t start or end with a dot.
9. Based on the email validity check, the server sends a response ("true" or "false") back
to the client.
10. The client receives the response from the server.
11. It displays whether the email is valid or not based on the server's response.
Program:
Server:
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class ServerEmailUDP_3060 {


public static void main(String[] args) {
try{
DatagramSocket ds =new DatagramSocket(9999);
byte[] fromClient=new byte[1024];
byte[] toClient;
DatagramPacket clientrec=new DatagramPacket(fromClient,fromClient.length);
ds.receive(clientrec);

String rec=new String(clientrec.getData(),0,clientrec.getLength());


System.out.println("Received data: "+ rec);
String message="Received Data: "+rec;
String str=check(rec)?"true":"false";
toClient=str.getBytes();

DatagramPacket sendp=new DatagramPacket(toClient,toClient.length,


clientrec.getAddress(),clientrec.getPort());

ds.send(sendp);
System.out.println("Sent Successfully");
ds.close();}
catch(Exception e ){
System.out.println(e);}}

public static boolean check(String email){


int atindex=email.indexOf('@');
int dot=email.lastIndexOf('.');
boolean b1,b2;
if(atindex>0 && atindex<dot){

b1=checkLocal(email.substring(0,atindex));
b2=checkDomain(email.substring(atindex+1));
return b1 && b2;}
else return false;}
public static boolean checkLocal(String str){

for(char ch:str.toCharArray()){
if( !(Character.isLetterOrDigit(ch) || ch=='.' || ch=='_') ) return false;}
return true;}
public static boolean checkDomain(String str){
for(char ch:str.toCharArray()){
if(!(Character.isLetterOrDigit(ch) || ch=='.' || ch=='_')) return false;}
return !str.startsWith(".") && !str.endsWith(".");}
}

Client:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Arrays;

import java.util.Scanner;
public class ClientEmailUDP_3060 {
public static void main(String[] args) {
try{
DatagramSocket ds=new DatagramSocket();

byte[] toServer;
byte[] fromServer=new byte[1024];
Scanner sc =new Scanner(System.in);
String str=sc.nextLine();
toServer=str.getBytes();

InetAddress ip= InetAddress.getByName("localhost");


DatagramPacket sendPack=new DatagramPacket(toServer,toServer.length,ip,9999);
ds.send(sendPack);
DatagramPacket recpack=new DatagramPacket(fromServer,fromServer.length);
ds.receive(recpack);

String recString=new String(recpack.getData(),0,recpack.getLength());


System.out.println("From Server: " + recString);}
catch(Exception e){}}
}
Output:
11.d)Algorithm:

1. The client establishes a TCP connection to the server on port 9999.


2. It reads an email address from the user and sends it to the server via a
DataOutputStream.
3. The server listens for incoming client connections using a ServerSocket.
4. Upon connection, the server receives the email string from the client via a
DataInputStream.
5. The server checks the email format:
6. Ensures the presence of @ between the local and domain parts.
7. Validates that the local part contains only allowed characters (letters, digits, ., _).
8. Ensures the domain part is valid and does not start or end with a dot.
9. The server sends back a response ("String accepted" or "String not accepted") to the
client via a DataOutputStream.
10. The client reads the response from the server via a DataInputStream.
11. It displays whether the email address was accepted or not.
Program:
Server:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerEmail_3060 {
public static void main(String[] args) {
try {

ServerSocket ssocket = new ServerSocket(9999);


System.out.println("Server started");
while(true){
Socket socket=ssocket.accept();
DataInputStream di = new DataInputStream(socket.getInputStream());

DataOutputStream dout=new DataOutputStream(socket.getOutputStream());


String email=di.readUTF();
dout.writeUTF(check(email)?"String accepted":"String not accepted");}}
catch(Exception e){}
}

public static boolean check(String email){


int atindex=email.indexOf('@');
int dot=email.lastIndexOf('.');
boolean b1,b2;
if(atindex>0 && atindex<dot){

b1=checkLocal(email.substring(0,atindex));
b2=checkDomain(email.substring(atindex+1));
return b1 && b2;}
else return false;}
public static boolean checkLocal(String str){

for(char ch:str.toCharArray()){
if( !(Character.isLetterOrDigit(ch) || ch=='.' || ch=='_') ) return false;}
return true;}
public static boolean checkDomain(String str){
for(char ch:str.toCharArray()){
if(!(Character.isLetterOrDigit(ch) || ch=='.' || ch=='_')) return false;}
return !str.startsWith(".") && !str.endsWith(".");}}

Client:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Scanner;

public class ClientEmail_3060 {


public static void main(String[] args) {
try{
Socket socket = new Socket("localhost",9999);
Scanner sc =new Scanner(System.in);

DataInputStream di = new DataInputStream(socket.getInputStream());


DataOutputStream dout=new DataOutputStream(socket.getOutputStream());
dout.writeUTF(sc.next());
System.out.println(di.readUTF());}
catch(Exception e){

System.out.println(e);}}
}
Output:

Result:

You might also like