assignment7
assignment7
ASSIGNMENT-7
1. Write a Java program to show the use of all
keywords for exception handling.
publicclasssample{
publicstaticvoidmain(S tring[]args) {
try{
intresult=divide(1 0,0);
System.o ut.p
rintln(" Result: "+result);
}catch(ArithmeticExceptione) {
System.o ut.p
rintln(" ArithmeticException caught: "+e.g etMessage());
}catch(Exceptione) {
System.o ut.p
rintln(" Exception caught: "+e.g
etMessage());
}finally{
System.o
ut.p
rintln(" Finally block executed");
}
}
publicstaticintdivide(intnum1,intnum2)throwsArithmeticException{
if(n
um2==0) {
thrownewArithmeticException(" Division by zero is not allowed");
}
returnnum1/num2;
}
}
Output:
ArithmeticException caught: Division by zero is not allowed
Finally block execute
. Write
2 a Java program using try and catch to generate NegativeArrayIndex
Exception and Arithmetic Exception.
publicclasssample{
publicstaticvoidmain(S tring[]args) {
try{
int[]arr= {1,2,3} ;
System.o ut.p
rintln(" Element at index 3: "+arr[3]);
}catch(NegativeArraySizeExceptione) {
System.o ut.p
rintln(" NegativeArrayIndexException caught: "+
e.g
etMessage());
}
try{
intresult=divide(1 0,0);
System.o
ut.p
rintln(" Result: "+result);
}catch(ArithmeticExceptione) {
System.o
ut.p
rintln(" ArithmeticException caught: "+e.g
etMessage());
}
}
publicstaticintdivide(intnum1,intnum2)throwsArithmeticException{
if(n
um2==0) {
thrownewArithmeticException(" Division by zero is not allowed");
}
returnnum1/num2;
}
}
publicclasssample{
publicstaticvoidmain(S tring[]args) {
try{
StringinputString="College";
if(!inputString.e quals(" University")) {
thrownewNoMatchFoundException("String does not match 'University'");
}
System.o ut.p
rintln(" String matches 'University'");
}catch(NoMatchFoundExceptione) {
System.o
ut.p
rintln(" NoMatchFoundException caught: "+e.g
etMessage());
}
}
}
Output:
NoMatchFoundException caught: String does not match 'University'
. Write a class that keeps a running total of all characters passed to it
4
(one at a time) and throws an exception if it is passed
a non-alphabetic character.
classNonAlphabeticCharacterExceptionextendsException{
publicNonAlphabeticCharacterException(S tringmessage) {
super(message);
}
}
publicclasssample{
privateinttotal;
publicsample() {
this.total=0;
}
publicvoidaddChar(c harc)throwsNonAlphabeticCharacterException{
if(!Character.isLetter(c )) {
thrownewNonAlphabeticCharacterException(" Non-alphabeticcharacter
detected: "+c);
}
this.total++;
}
publicintgetTotal() {
returnthis.total;
}
publicstaticvoidmain(S
tring[]args) {
samplerunningTotal=newsample();
try{
runningTotal.a ddChar('A');
runningTotal.a ddChar('B');
runningTotal.a ddChar('C');
runningTotal.a ddChar('1');
runningTotal.a ddChar('D');
}catch(NonAlphabeticCharacterExceptione) {
System.o
ut.p
rintln(" NonAlphabeticCharacterExceptioncaught: "+
e.getMessage());
}
System.out.p
rintln("Total alphabetic characters: "+runningTotal.g
etTotal());
}
}
. Write
5 program called Factorial.java that computes factorials and catches
a
the result in an array of type long for reuse. The long type of variable has its
wn range. For example 20! Is as high as the range of long type. So check the
o
argument passes and “throw an exception”, if it is
too big or too small.
).If
a x is less than 0 throw an IllegalArgumentException with a
message “Value of x must be
positive”.
b).If x is above the length
of the array throw an
IllegalArgumentException with a message
“Result will overflow”.
publicclasssample{
privatestaticfinalintMAX_FACTORIAL=20;
privatestaticlong[]factorials=newlong[M
AX_FACTORIAL];
publicstaticvoidmain(S tring[]args) {
try{
intx=5;
longresult=factorial(x ) ;
System.o ut.p
rintln(x +"! = "+result);
x =21;
result=factorial(x );
System.o ut.p
rintln(x +"! = "+result);
}catch(FactorialExceptione) {
System.o ut.p
rintln(" FactorialException caught: "+e.getMessage());
}
}
publicstaticlongfactorial(intx) throwsFactorialException{
if(x <0) {
thrownewIllegalArgumentException("Value of x must be positive");
}
if(x >=MAX_FACTORIAL) {
thrownewFactorialException(" Result will overflow");
}
if(x ==0||x==1) {
factorials[x ] =1;
}else{
factorials[x ] =x*factorial(x -1);
}
returnfactorials[x];
}
}
Output:
5! = 120
FactorialException caught: Result will overflow
. Write a program that outputs the name of the capital of the country
6
entered at the command line. The program should throw a
“NoMatchFoundException” when it fails to print the capital of
the country entered at the command line.
classNoMatchFoundExceptionextendsException{
publicNoMatchFoundException(Stringmessage) {
super(message);
}
}
publicclasssample{
publicstaticvoidmain(S tring[]args) {
try{
if(args.length==0) {
thrownewIllegalArgumentException("Country name not provided");
}
tringcountry=args[0];
S
Stringcapital=findCapital(country);
if(capital==null) {
thrownewNoMatchFoundException("No capital found for country: "+
country);
}
ystem.o
S ut.p
rintln(" Capital of "+country+": "+capital);
}catch(IllegalArgumentExceptione) {
System.o ut.p
rintln(" IllegalArgumentException caught: "+e.g etMessage());
}catch(NoMatchFoundExceptione) {
System.o
ut.p
rintln(" NoMatchFoundException caught: "+e.g etMessage());
}
}
publicstaticStringfindCapital(S
tringcountry) {
switch(c ountry.toLowerCase()) {
case"united states":
return"Washington, D.C.";
case"united kingdom":
return"London";
case"france":
return"Paris";
default:
returnnull;
}
}
}
Output:
IllegalArgumentException caught: Country name not provided
. Write
7 a program that takes a value at the command line for which factorial is
to be computed. The program must convert the string to its integer equivalent.
There are threepossible user input errors that can prevent the
program from executing normally.
). The
a first error is when the
user provides no argument while executing
the program and an ArrayIndexOutOfBoundsException is raised.
You must write a catch block for this.
classFactorialExceptionextendsException{
publicFactorialException(S
tringmessage) {
super(message);
}
}
publicclasssample{
publicstaticvoidmain(S tring[]args) {
try{
if(args.length==0) {
thrownewArrayIndexOutOfBoundsException(" No argument provided");
}
intx=Integer.p
arseInt(a
rgs[0
]);
if(x==0) {
thrownewIllegalArgumentException("Value of x must be greaterthan 0");
}
longresult=factorial(x ) ;
System.o ut.p
rintln(x +"! = "+result);
}catch(ArrayIndexOutOfBoundsExceptione) {
System.o ut.p
rintln(" ArrayIndexOutOfBoundsException caught: "+
e.getMessage());
}catch(NumberFormatExceptione) {
System.o ut.p
rintln(" NumberFormatException caught: Invalid argument
provided");
}catch(IllegalArgumentExceptione) {
System.o ut.p
rintln(" IllegalArgumentException caught: "+e.g etMessage());
}catch(FactorialExceptione) {
System.o
ut.p
rintln(" FactorialException caught: "+e.getMessage());
}
}
publicstaticlongfactorial(intx) throwsFactorialException{
if(x <0) {
thrownewIllegalArgumentException("Value of x must be positive");
}
if(x ==0||x==1) {
return1;
}
longresult=x*factorial(x -1);
if(r esult<0) {
thrownewFactorialException(" Result will overflow");
}
returnresult;
}
}
Output:
ArrayIndexOutOfBoundsException caught: No argument provided
publicclasssample{
publicstaticvoidmain(String[]args) {
try{
if(a
rgs.length<5) {
thrownewCheckArgumentException(" At least 5 arguments
required");
}
intsum=0;
for(S
tringarg:args) {
sum+=Integer.p arseInt(arg);
}
ystem.o
S ut.p
rintln(" Sum of all arguments: "+sum);
}catch(C heckArgumentExceptione) {
System.o ut.p
rintln(" CheckArgumentException caught: "+
e.getMessage());
}catch(N
umberFormatExceptione) {
System.o
ut.p
rintln(" NumberFormatException caught: Invalidargument
provided");
}
}
}
Output:
CheckArgumentException caught: At least 5 arguments required
. Consider
9 a Student examination database system
that prints the marksheet of students. Inputthe
following from the command line.
1.Student’s Name
2.Marks in sixsubjects
These marks should be between 0 to 50. If the marks are not in the specified
range, raise a RangeException, else find the total marks and prints the
percentage of the students.
classRangeExceptionextendsException{
publicRangeException(Stringmessage) {
super(m
essage);
}
}
publicclasssample{
publicstaticvoidmain(String[]args) {
try{
if(a
rgs.length<7) {
thrownewIllegalArgumentException("At least 7 arguments
required");
}
tringname=args[0
S ];
int[]marks=newint[6];
for(inti=1;i<=6;i++) {
intmark=Integer.parseInt(a rgs[i]);
if(m
ark<0||mark>50) {
thrownewRangeException("Marks should be between0 to 50");
}
marks[i-1] =mark;
}
inttotalMarks=0;
for(intmark:marks) {
totalMarks+=mark;
}
oublepercentage= (double)totalMarks/300*100;
d
System.o ut.p
rintln(" Name: "+name);
System.o ut.p
rintln(" Total Marks: "+totalMarks);
System.o ut.p
rintln(" Percentage: "+percentage+"%");
}catch(IllegalArgumentExceptione) {
System.o ut.p
rintln(" IllegalArgumentException caught: "+
e.getMessage());
}catch(R angeExceptione) {
System.o
ut.p
rintln(" RangeException caught: "+e.g etMessage());
}
}
}
Output:
IllegalArgumentException caught: At least 7 arguments required
classTooColdExceptionextendsException{
publicTooColdException(Stringmessage) {
super(m
essage);
}
}
publicclasssample{
publicstaticvoidmain(String[]args) {
try{
if(a
rgs.length==0) {
thrownewIllegalArgumentException("No argument provided");
}
inttemperature=Integer.p
arseInt(args[0]);
if(temperature>35) {
thrownewTooHotException(" Temperature is too hot");
}elseif(temperature<5) {
thrownewTooColdException("Temperature is too cold");
}else{
System.out.p rintln(" Normal");
doublefahrenheit= (temperature*9/5) +32;
System.out.p
rintln(" Temperature in Fahrenheit: "+fahrenheit);
}
}catch(IllegalArgumentExceptione) {
System.o ut.p
rintln(" IllegalArgumentException caught: "+
e.getMessage());
}catch(T ooHotExceptione) {
System.o ut.p
rintln(" TooHotException caught: "+e.g
etMessage());
}catch(T ooColdExceptione) {
System.o ut.p
rintln(" TooColdException caught: "+e.g etMessage());
}
}
}
Output:
IllegalArgumentException caught: No argument providedo
11.Write an application that displays a series of at least five student ID
numbers (that you have
stored in an array) and asks the user to enter a numeric test score for the
student. Create
ScoreException class, and throw a ScoreException for the
classif
the user does not enter a valid score (zero to 100). Catch the ScoreException and
then display an appropriate
message. In addition, store a 0 for the student’s score. At the end of the application,
display all the student IDs and scores.
classScoreExceptionextendsException{
publicScoreException(Stringmessage) {
super(message);
}
}
publicclasssample{
publicstaticvoidmain(S tring[]args) {
String[]studentIDs= {"S001","S002","S003","S004","S005"};
int[]scores=newint[5
];
for(inti=0;i<studentIDs.length;i++) {
try{
System.out.p rint(" Enter score for student "+studentIDs[i] +": ");
intscore=Integer.parseInt(System.c onsole().readLine());
if(score<0||score>100) {
thrownewScoreException("Score should be between 0 to 100");
}
s cores[i] =score;
}catch(ScoreExceptione) {
System.out.p rintln(" ScoreException caught: "+e.g
etMessage());
scores[i] =0;
}catch(NumberFormatExceptione) {
System.out.p rintln(" NumberFormatException caught: Invalidinput
provided");
scores[i] =0;
}
}
ystem.out.p
S rintln("Student IDs and Scores:");
for(inti=0;i<studentIDs.length;i++) {
System.o ut.p rintln(s tudentIDs[i] +": "+scores[i]);
}
}
}
Output:
nter score for student S001: 34
E
Enter score for student S002: 56
Enter score for student S003: 34
Enter score for student S004: 67
Enter score for student S005: 89
Student IDs and Scores:
S001: 34
S002: 56
S003: 34
S004: 67
S005: 89
or
publicclasssample{
publicstaticvoidmain(S
tring[]args) {
Threadthread1=newThread(newMyRunnable(),"Thread 1");
Threadthread2=newThread(newMyRunnable(),"Thread 2");
Threadthread3=newThread(newMyRunnable(),"Thread 3");
Threadthread4=newThread(newMyRunnable(),"Thread 4");
thread1.s tart();
thread2.s tart();
thread3.s tart();
thread4.s tart();
}
staticclassMyRunnableimplementsRunnable{
@Override
publicvoidrun() {
System.o
ut.p
rintln(" Running thread: "+Thread.currentThread().getName());
}
}
}
Output:
Running thread: Thread 4
Running thread: Thread 3
Running thread: Thread 2
Running thread: Thread 1
thread1.s tart();
thread2.s tart();
thread3.s tart();
thread4.s tart();
try{
thread1.join();
thread2.join();
thread3.join();
thread4.join();
}catch(InterruptedExceptione) {
e.p
rintStackTrace();
}
ystem.out.p
S rintln("Final value of count for each thread:");
System.out.p rintln(thread1.getName() +": "+thread1.g
etCount());
System.out.p rintln(thread2.getName() +": "+thread2.g
etCount());
System.out.p rintln(thread3.getName() +": "+thread3.g
etCount());
System.out.p
rintln(thread4.getName() +": "+thread4.g
etCount());
}
staticclassCounterThreadextendsThread{
privateintcount;
publicCounterThread(S tringname,intpriority) {
super(name);
setPriority(priority);
}
publicintgetCount() {
returncount;
}
Override
@
publicvoidrun() {
for(inti=0;i<10;i++) {
count++;
try{
Thread.s leep(1 0);
}catch(InterruptedExceptione) {
e.p
rintStackTrace();
}
}
}
}
}
Output:
Final value of count for each thread:
Thread 1: 10
Thread 2: 10
Thread 3: 10
Thread 4: 10
publicclasssample{
privateintcount=0;
publicsynchronizedvoidincrement() {
count++;
}
publicsynchronizedvoiddecrement() {
count--;
}
publicsynchronizedintgetCount() {
returncount;
}
publicstaticvoidmain(S
tring[]args)throwsInterruptedException{
sampleexample=newsample();
Threadthread1=newThread(()->{
for(inti=0;i<1000;i+
+) {
example.increment();
}
});
Threadthread2=newThread(()->{
for(inti=0;i<1000;i+
+) {
example.d ecrement();
}
});
thread1.s tart();
thread2.s tart();
thread1.join();
thread2.join();
System.out.p
rintln("Final count: "+example.g
etCount());
}
}
Output:
Final count: 0
5. Write a
1 Java Program to Use Block Level
Synchronization.
publicclasssample{
privateintcount=0;
privatefinalObjectlock=newObject();
publicvoidincrement() {
synchronized(lock) {
count++;
}
}
publicvoiddecrement() {
synchronized(lock) {
count--;
}
}
publicintgetCount() {
synchronized(lock) {
returncount;
}
}
publicstaticvoidmain(String[]args)throwsInterruptedException{
sampleexample=newsample();
Threadthread1=newThread(()->{
for(inti=0;i<1000;i+
+) {
example.increment();
}
});
Threadthread2=newThread(()->{
for(inti=0;i<1000;i+
+) {
example.d ecrement();
}
});
thread1.s tart();
thread2.s tart();
thread1.join();
thread2.join();
System.o
ut.p
rintln(" Final count: "+example.g
etCount());
}
}
utput:
O
Final count : 0