0% found this document useful (0 votes)
46 views18 pages

Java Exception Handling and Multithreading Programs

The document describes three Java programs. Program 1 validates student registration numbers and phone numbers by checking character lengths and data types, throwing different exceptions for invalid values. Program 2 simulates a student election using threads to count votes stored in an array. Program 3 defines a Donor class to store donor details, writes donor objects to a file, then reads and displays details of donors with blood type A+ who have not donated in the past six months.

Uploaded by

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

Java Exception Handling and Multithreading Programs

The document describes three Java programs. Program 1 validates student registration numbers and phone numbers by checking character lengths and data types, throwing different exceptions for invalid values. Program 2 simulates a student election using threads to count votes stored in an array. Program 3 defines a Donor class to store donor details, writes donor objects to a file, then reads and displays details of donors with blood type A+ who have not donated in the past six months.

Uploaded by

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

JAVA PROGRAMMING LAB-4

Program 1) Write a program to demonstrate the knowledge of students in Java Exception


handling.

Eg., Read the Register Number and Mobile Number of a student. If the Register Number does
not contain exactly 9 characters or if the Mobile Number does not contain exactly 10 characters,
throw an IllegalArgumentException. If the Mobile Number contains any character other than a
digit, raise a NumberFormatException. If the Register Number contains any character other than
digits and alphabets, throw a NoSuchElementException. If they are valid, print the message
‘valid’ else ‘invalid’

Code-

import [Link];

import [Link];

import [Link];

import [Link];

/**

* @author batch1

*/

public class ExcepHandle{

static void validate(String r, String n)

{ if([Link]() != 9){

[Link]("Invalid");

throw new IllegalArgumentException("Register Number does not contain exactly 9


characters");

if([Link]() != 10){
[Link]("Invalid");

throw new IllegalArgumentException("Mobile Number does not contain exactly 10


characters");

String pattern = "^[6|7|8|9]{1}\\d{9}";

Pattern a = [Link](pattern);

Matcher m1 = [Link](n); if(!

[Link]()){

throw new NumberFormatException("Mobile Number cannot contain any character other


than a digit");

String pattern2 = "^[1-9]{2}[A-Z a-z]{3}[0-9]{4}$";

Pattern b = [Link](pattern2);

Matcher m2 = [Link](r);

if(![Link]()){

throw new NoSuchElementException("Registration Number cannot contain any character


other than digits and alphabets");

public static void main(String args[]){

String reg;

String no;
[Link]("Enter the registeration number followed by phone number");

try (Scanner sc = new Scanner([Link])) {

reg = [Link]();

no = [Link]();

validate(reg, no);

[Link]("Valid");

Output-
Program 2) Write a program to demonstrate the knowledge of students in multithreading.

Eg., Three students A, B and C of [Link]- II year contest for the PR election. With the total
strength of 240 students in II year, simulate the vote casting by generating 240 random numbers
(1 for student A, 2 for B and 3 for C) and store them in an array. Create four threads to equally
share the task of counting the number of votes cast for all the three candidates. Use synchronized
method or synchronized block to update the three count variables. The main thread should
receive the final vote count for all three contestants and hence decide the PR based on the values
received.

Code-

[Link]-

import [Link];

import [Link];

import [Link];

public class MultiThreadVote {

public static void main(String[] args) {

Vector votevec = new Vector(240); // creating a vote array for 240 votes

Vote a = new Vote(1,

votevec); [Link]();
Vote b = new Vote(2,

votevec); [Link]();

Vote c = new Vote(3,

votevec); [Link]();

try{

[Link]();

[Link]();

[Link]();

[Link]("Voting has ended!");

}catch(Exception e){[Link](e);}

count ac = new count(1, votevec);

count bc = new count(2, votevec);

count cc = new count(3, votevec);

[Link]();

[Link]();

[Link]();

try{

[Link]();

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

[Link]("Counting has ended!");

}catch(Exception e){[Link](e);}

int av = [Link];

int bv = [Link];

int cv = [Link];

[Link]("[Link] Vector:" + "\n" +

votevec); [Link](av + " votes for A");

[Link](bv + " votes for B");

[Link](cv + " votes for C");

if(av >= bv && av >= cv){

if(av == bv || av == cv)

[Link]("Tie in elections!");

else

[Link]("A has won the elections!");

else if(bv >= av && bv >= cv){

if(av == bv || bv == cv)

[Link]("Tie in elections!");

else

[Link]("B has won the elections!");

}
else if(cv >= av && cv >= bv){

if(cv == bv || cv == av)

[Link]("Tie in elections!");

else

[Link]("C has won the elections!");

[Link]-

package elections;

import [Link];

import [Link];

public class Vote extends

Thread{ Random rand = new

Random(); int max = 750;

int min =

100; int v, s;

Vector vec;

public Vote(int v, Vector vec)

this.v = v;

[Link] =

vec;
}

public void run()

{ try

// while voting print id

while([Link]() < 240) {

[Link]("Thread " + [Link]() + " is

Voting"); [Link](v);

s = [Link]((max - min) + 1) + min;

[Link]("Thread " + [Link]() + " is sleeping for " +

s); [Link](s);

catch(InterruptedException e)

[Link]("Voting Exception: " + e);

}
[Link]-

package elections;

/**

* @author batch1

*/

import [Link];

public class count extends

Thread{ Vector vec;

int k, i;

public int count = 0;

public count(int k, Vector vec)

{ this.k = k;

[Link] = vec;

@Override

public void run()

try{

for(i = 0; i < [Link](); i++)

{ if([Link](i).equals(k

))

count++;
}

catch(Exception e){

[Link](e);

Output-
Counting has ended!

[Link] Vector:

[3, 2, 1, 1, 2, 3, 3, 2, 1, 2, 1, 3, 2, 1, 1, 2, 3, 2, 1, 2, 3, 2, 3, 1, 1, 2, 3, 1, 2, 1, 3, 2, 1, 1, 3, 2, 1, 3, 2, 1, 1, 3, 2,
3, 1, 3, 1, 2, 3, 1, 2, 1, 2, 1, 3, 1, 2, 3, 2, 1, 2, 3, 1, 2, 3, 2, 1, 3, 2, 3, 1, 3, 3, 2, 1, 3, 1, 2, 2, 1, 3, 2, 2, 1, 2, 3,
2, 3, 1, 2, 3, 1, 2, 3, 2, 1, 3, 1, 2, 3, 2, 1, 3, 1, 3, 2, 1, 2, 1, 3, 3, 2, 1, 3, 1, 2, 3, 3, 1, 2, 1, 2, 3, 1, 3, 2, 1, 3, 1,
2, 2, 3, 1, 3, 2, 1, 3, 2, 3, 2, 1, 3, 2, 1, 3, 2, 3, 1, 2, 3, 2, 3, 1, 1, 2, 3, 2, 1, 2, 1, 2, 3, 2, 3, 1, 2, 1, 3, 1, 2, 3, 2,
2, 1, 1, 3, 1, 2, 2, 3, 1, 2, 1, 3, 2, 3, 2, 1, 3, 1, 2, 1, 3, 1, 3, 1, 2, 3, 1, 3, 2, 1, 2, 3, 2, 3, 1, 3, 2, 3, 1, 1, 2, 3, 2,
1, 3, 2, 1, 2, 3, 2, 3, 1, 2, 2, 3, 2, 1, 3, 1, 3, 1, 2, 3, 1, 2, 3, 1, 2]

80 votes for

A 83 votes

for B 77 votes

for C

B has won the elections!

BUILD SUCCESSFUL (total time: 20 seconds)

Program 3) Write a program to demonstrate the knowledge of students in File handling.


Eg., Define a class ‘Donor’ to store the below mentioned details of a blood donor.
Name, age, Address, Contact number, blood group, date of last donation

Create ‘n’ objects of this class for all the regular donors at Vellore. Write these objects to a file.
Read these objects from the file and display only those donors’ details whose blood group is
‘A+ve’ and had not donated for the recent six months.

Code-

//requires [Link] jar files

import [Link].*;

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class Donor {

String name,addr,contact,bldgrp;

Date date;

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


int n, i;

SimpleDateFormat ft = new SimpleDateFormat("MM-dd-

yyyy"); String temp;

String pattern = "[A|B|O|AB][+|-]";

Matcher m;

Pattern r = [Link](pattern);

// delete existing file first

try{

[Link]([Link]("[Link]"));

catch(NoSuchFileException e)

[Link]("No such file/directory exists");

catch(IOException e)

[Link]("Invalid permissions.");

[Link]("Deletion successful.");

Scanner sc = new Scanner([Link]);

[Link]("Enter number of donors: ");

n = [Link]();

[Link]();
Donor arr[] = new Donor[n];

ByteArrayOutputStream outputstream = new ByteArrayOutputStream();

try (FileOutputStream fos = new FileOutputStream("[Link]")) {

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

arr[i] = new Donor(); // initializing new donor

[Link]("Name: ");

arr[i].name = [Link]();

[Link]("Address: ");

arr[i].addr = [Link]();

[Link]("Contact: ");

arr[i].contact = [Link]();

arr[i].bldgrp = "";

m=

[Link](arr[i].bldgrp);

while(![Link]()){

[Link]("Blood Group: ");

arr[i].bldgrp = [Link]();

m = [Link](arr[i].bldgrp);

boolean flag = false;

while(!flag){

[Link]("Date: ");

temp = [Link]();

try {
arr[i].date = [Link](temp);

flag = true;

} catch (ParseException e) {

flag = false;

[Link]("Unparseable using " + ft);

[Link](("Donor " + (i+1) + "\n").getBytes());

[Link]("---------------\n".getBytes());

[Link]("Name: ".getBytes());

[Link](arr[i].[Link]());

[Link]("\n".getBytes());

[Link]("Address: ".getBytes());

[Link](arr[i].[Link]());

[Link]("\n".getBytes());

[Link]("Contact: ".getBytes());

[Link](arr[i].[Link]());

[Link]("\n".getBytes());

[Link]("Blood Group: ".getBytes());

[Link](arr[i].[Link]());

[Link]("\n".getBytes());

[Link]("Date: ".getBytes());
[Link](arr[i].[Link]().getBytes());

[Link]("\n".getBytes());

[Link]("\n".getBytes());

byte c[] = [Link]();

[Link](c);

byte[] fileContent = [Link]([Link]("[Link]"));

String fileInput = new String(fileContent);

String[] content = [Link]("\n");

Date dt2;

String[] fileDate, fileGrp;

SimpleDateFormat ft2 = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy");

LocalDate current = [Link]();

for(i = 5; i < [Link]; i += 8){

fileGrp = content[i].split(": ");

fileDate = content[i+1].split(": ");

try {
dt2 = [Link](fileDate[1]);

DateTime dt3 = new DateTime(dt2);

LocalDate dt1 = new LocalDate(dt3);

Period p = new Period(dt1, current);

if(([Link]() > 6 | [Link]() >= 1) && fileGrp[1].equals("A+"))

[Link]("\n" + "Donors who haven't donated in 6 months and \"A+\"" +


"\n");

[Link](content[i-3]);

[Link](content[i-2]);

[Link](content[i-1]);

[Link](content[i]);

[Link](content[i+1]);

[Link]("\n");

} catch (ParseException e) {

Output-

Common questions

Powered by AI

Java uses DateTime operations from the Joda-Time library to parse dates of last donation, calculate the period since then, and filter donors who haven't donated in over six months. The Period class calculates the time difference, ensuring only eligible donors, as per criteria, are displayed .

Exception handling in Java makes programs robust by allowing developers to anticipate and manage errors. In the programs, exceptions such as IllegalArgumentException, NumberFormatException, and NoSuchElementException allow the program to respond to invalid inputs, maintain control flow, and provide clear user feedback, thus enhancing resilience .

The program uses input streams to read and write donor information, stores objects of class Donor, and parses strings for date and blood group verification using SimpleDateFormat and regular expressions. Efficiently reading from and writing to file through streams allows for structured data management and retrieval based on specified criteria .

Using Vector allows for thread-safe operations, but it can become a bottleneck due to its synchronized methods on each operation, which may affect performance. Synchronization ensures that vote counts are accurate and consistent across threads. The choice of data structure and synchronization directly impacts the reliability and efficiency of concurrent processes .

The program creates multiple threads for simulating voting and counting. Threads repeatedly add votes to a shared Vector under synchronized control to prevent interference. Voting threads simulate delays with Thread.sleep to mimic real-time activity. This demonstrates handling concurrent operations proficiently by utilizing inter-thread communication .

Regular expressions are used to define string patterns for validating inputs. In the Java programs, they ensure that Mobile Numbers follow a specific digit pattern and Register Numbers adhere to a specified alphanumeric format. This automation in validation reduces manual checks and potential user input errors .

The program compares the total votes of each candidate using conditional statements. If two candidates have equal highest votes, it declares a tie. If one candidate's votes exceed others, that candidate is declared the winner. The logical structure ensures that ties and wins based on vote equality and inequality are handled accurately .

The program uses synchronized blocks or methods to ensure thread safety when updating the count variables for each candidate, preventing race conditions. The threads handle equal portions of the vote count and update shared counters in a synchronized manner before determining the election outcome based on these counts .

The Java program checks the Register Number for having exactly 9 characters, and the Mobile Number for having 10 digits. It uses Regex patterns to ensure the Mobile Number starts with digits 6-9 and is followed by 9 other digits. An IllegalArgumentException is thrown if lengths aren't met, a NumberFormatException if the Mobile Number contains non-digits, and a NoSuchElementException if the Register Number has invalid characters .

The program catches NoSuchFileException when attempting to delete a file that doesn't exist, and IOException for permissions issues. During parsing, ParseException is managed for unparseable date formats. Files.deleteIfExists and outputstream are used for deleting files and managing output stream operations safely .

You might also like