0% found this document useful (0 votes)
100 views

Java Programming Lab

Java lab iibsc cs

Uploaded by

sanjeevrk051
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
100 views

Java Programming Lab

Java lab iibsc cs

Uploaded by

sanjeevrk051
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

COLLEGE

92 / 1 & 9, Muthamizh Nagar,


Kodungaiyur, Chennai – 118.

I B.COM ISM

INFORMATION MANAGEMENT SYSTEM

JAVA PROGRAMMING LAB

Name of Student :

Batch Number :

University Register No. :

1
COLLEGE
92 / 1 & 9, Muthamizh Nagar,
Kodungaiyur, Chennai – 118.

B.COM ISM
INFORMATION MANAGEMENT SYSTEM
JAVA PROGRAMMING LAB

Name of Student :

Batch Number :

University Register No. :

Certified to be bonafide record of works done in the computer lab.

Head of the Department Staff-in-Charge

Submitted for the Practical Examination held in the year 2024 on at


Sree Muthukumaraswamy College, Chennai-118.

Internal Examiner External Examiner


2
INDEX
Page
S.NO Date Title sign
.No
An integer and then prints out all
1. the prime numbers up to that
Integer
2. To multiply two given matrices
That displays the number of
3.
characters, lines and words in a text
Generate random numbers between
two given limits using Random
4.
class and print messages according
to the range of the value generated
String Manipulation using
5.A Character Array,
“String Length”
String Manipulation using
Character Array,
5.B
“Finding a character at a
particular position”
String Manipulation using
5.C Character Array,
“Concatenating two strings”
String operations using String
6.A
class, “String Concatenation”
String operations using String
6.B
class, “Search a substring”
String operations using String
6.C class, “To extract substring from
given string”
String operations using
7.A StringBuffer class,
“Length of a string”
3
String operations using
StringBuffer class,
7.B “Reverse a string”
String operations using
StringBuffer class,
7.C
“Delete a substring from the
given string”
That implements a multi-thread
application that has three threads.
First thread generates random
integer every 1 second and if the
8. value is even, second thread
computes the square of the number
and prints. If the value is odd, the
third thread will print the value of
cube of the number.
which uses the same method
asynchronously to print the
9. numbers 1 to 10 using Thread-0
and to print 90 to 100 using
Thread-1
Write a program to demonstrate the
use of following exceptions.
a) Arithmetic Exception

10. b) Number Format Exception


c) Array Index Out of Bound
Exception
d) Negative Array Size
Exception

4
Ex.No:01 AN INTEGER AND THEN PRINTS OUT ALL THE
Date: PRIME NUMBERS UP TO THAT INTEGER

AIM:

To write a java program that prompts the user for an integer and then prints
out all the prime numbers up to that Integer.

PROCEDURE:

Step 1- Start

Step 2- Declare an integer : n

Step 3- Prompt the user to enter an integer value/ Hardcode the


integer

Step 4- Read the values

Step 5- Using a while loop from 1 to n, check if the 'i' value is


divisible by any number from 2 to i.

Step 6- If yes, check the next number

Step 7- If no, store the number as a prime number

Step 8- Display the 'i' value as LCM of the two numbers

Step 9- Stop

5
SOURCE CODING:

public class PrimeNumbers


{
public static void main(String args[])
{
int i,n,counter, j;
n= 10;
System.out.printf("Enter the n value is %d ", n);
System.out.printf("\nPrime numbers between 1 to %d are ", n);
for(j=2;j<=n;j++)
{
counter=0;
for(i=1;i<=j;i++)
{
if(j%i==0)
{
counter++;
}
}
if(counter==2)
System.out.print(j+" ");
}
}
}

6
OUTPUT:

Enter the n value is 10


Prime numbers between 1 to 10 are 2 3 5 7

RESULTS:

Thus, the above java program executed successfully and output verified.

7
Ex.No:02 WRITE A JAVA PROGRAM TO MULTIPLY TWO
Date: GIVEN MATRICES

AIM:

Write a Java program to multiply two given matrices.

PROCEDURE:

Step 1: Initialize matrices 'a' and 'b' with predefined values.

Step 2: Create matrix 'c' to store the multiplication result.

Step 3: Iterate through each row of matrix 'a'.

Step 4: For each row of 'a', iterate through each column of 'b'.

Step 5: Calculate the sum of products of corresponding elements


from 'a' and 'b'.

Step 6: Store the sum in the corresponding cell of matrix 'c'.

Step 7: Print the elements of matrix 'c'.

Step 8: Repeat steps 3-7 for all rows of 'a'.

Step 9: End of the program.

8
SOURCE CODING:

public class MatrixMultiplicationExample

public static void main(String args[])

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

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

int c[][]=new int[3][3];

for(int i=0;i<3;i++)

for(int j=0;j<3;j++)

c[i][j]=0;

for(int k=0;k<3;k++)

c[i][j]+=a[i][k]*b[k][j];

System.out.print(c[i][j]+" ");

System.out.println();//new line

}
9
OUTPUT:

666

12 12 12

18 18 18

RESULTS:

Thus, the above java program executed successfully and output verified.

10
Ex.No:03 WRITE A JAVA PROGRAM THAT DISPLAYS THE
Date: NUMBER OF CHARACTERS, LINES AND WORDS
IN A TEXT?

AIM:

Write a Java program that displays the number of characters, lines and
words in a text.

PROCEDURE:

Step 1: Open the text file for reading.

Step 2: Initialize counters for words, characters, paragraphs,


whitespaces, and sentences.

Step 3: Read the first line from the file.

Step 4: If the line is not null, go to step 5. Otherwise, go to step 9.

Step 5: If the line is empty, increment the paragraph count and go


to step 8.

Step 6: Count the number of characters, words, whitespaces, and


sentences in the line.

Step 7: Update the counters accordingly.

Step 8: Read the next line from the file and go back to step 4.

Step 9: If there's at least one sentence, increment the paragraph


count.

Step 10: Print the total counts of words, sentences, characters,


paragraphs, and whitespaces.

Step 11: End of the program.

11
SOURCE CODING:

import java.io.*;

public class Test {

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

File file = new File("C:\\Users\\hp\\Desktop\\TextReader.txt");

FileInputStream fileInputStream = new FileInputStream(file);

InputStreamReader inputStreamReader = new


InputStreamReader(fileInputStream);

BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

String line;

int wordCount = 0;

int characterCount = 0;

int paraCount = 0;

int whiteSpaceCount = 0;

int sentenceCount = 0;

while ((line = bufferedReader.readLine()) != null) {

if (line.equals("")) {

paraCount += 1;

} else {

characterCount += line.length();

12
String words[] = line.split("\\s+");

wordCount += words.length;

whiteSpaceCount += words.length - 1;

String sentence[] = line.split("[!?.:]+");

sentenceCount += sentence.length;

if (sentenceCount >= 1) {

paraCount++;

System.out.println("Total word count = " + wordCount);

System.out.println("Total number of sentences = " + sentenceCount);

System.out.println("Total number of characters = " + characterCount);

System.out.println("Number of paragraphs = " + paraCount);

System.out.println("Total number of whitespaces = " + whiteSpaceCount);

13
OUTPUT:

Total word count = 26

Total number of sentences = 3

Total number of characters = 130

Number of paragraphs = 4

Total number of whitespaces = 22

RESULTS:

Thus, the above java program executed successfully and output verified.

14
Ex.No:04 GENERATE RANDOM NUMBERS BETWEEN TWO
Date: GIVEN LIMITS USING RANDOM CLASS AND
PRINT MESSAGES ACCORDING TO THE RANGE
OF THE VALUE GENERATED

AIM:

Write a Java program that displays the generate random numbers


between two given limits using random class and print messages according to
the range of the value generated.

PROCEDURE:

Step 1: Import necessary packages (java.io.* and java.util.*).

Step 2: Define a class named GFG.

Step 3: Define the main method.

Step 4: Create a Random object named rand.

Step 5: Define variables max and min to represent the range of


generated numbers.

Step 6: Print the message indicating the range of generated


numbers.

Step 7: Generate and print a random number within the specified


range using rand.nextInt(max - min + 1) + min.

Step 8: Repeat steps 7 for two more times to generate and print two
additional random numbers.

Step 9: End of the program.

15
SOURCE CODING:

import java.io.*;

import java.util.*;

class GFG {

public static void main (String[] args) {

Random rand = new Random();

int max=100,min=50;

System.out.println("Generated numbers are within "+min+" to "+max);

System.out.println(rand.nextInt(max - min + 1) + min);

System.out.println(rand.nextInt(max - min + 1) + min);

System.out.println(rand.nextInt(max - min + 1) + min);

16
OUTPUT:

Generated numbers are within 50 to 100

76

89

53

RESULTS:

Thus, the above java program executed successfully and output verified.
17
Ex.No:05-A WRITE A PROGRAM TO DO STRING
MANIPULATION USING CHARACTER ARRAY AND
Date:
PERFORM THE FOLLOWING STRING
OPERATIONS:
“A-STRING LENGTH”

AIM:

Write a Java program that displays the String Manipulation using


Character Array, “String Length”

PROCEDURE:

Step 1: Define a class named Stringoperation5.

Step 2: Define the main method.

Step 3: Declare a string variable s and initialize it with the value "
Welcome to ISM department".

Step 4: Print the length of the string s using the length() method.

Step 5: End of the program.

18
SOURCE CODING:

public class Stringoperation5

public static void main(String args[])

String s=" Welcome to ISM department";

System.out.println(s.length());

19
OUTPUT:

26

RESULTS:

Thus, the above java program executed successfully and output verified.
20
Ex.No:05-B WRITE A PROGRAM TO DO STRING
MANIPULATION USING CHARACTER ARRAY AND
Date: PERFORM THE FOLLOWING STRING
OPERATIONS:
“B- FINDING A CHARACTER AT A PARTICULAR
POSITION”

AIM:

Write a Java program that displays the String Manipulation using


Character Array, “Finding a character at a particular position”

PROCEDURE:

Step 1: Declare a public class named "CharAtExample".

Step 2: Define the main method inside the class.

Step 3: Declare a String variable "str" and assign it the value


"Hello, World!".

Step 4: Declare an integer variable "position" and assign it the


value 7.

Step 5: Check if the position is within the valid range (greater than
or equal to 0 and less than the length of the string).

Step 6: If the position is valid, use the charAt method to retrieve


the character at the specified position.

Step 7: Print the character at the specified position.

Step 8: If the position is not valid, print a message indicating that


the position is invalid.

Step 9: End of the program.

21
SOURCE CODING:

public class CharAtExample {

public static void main(String[] args) {

String str = "Hello, World!";

int position = 7;

if (position >= 0 && position < str.length()) {

char result = str.charAt(position);

System.out.println("Character at position " + position + ": " + result);

} else {

System.out.println("Invalid position. Please provide a valid position within


the string length.");

22
OUTPUT:

Character at position 7: W

RESULTS:

Thus, the above java program executed successfully and output verified.

23
Ex.No:05-C WRITE A PROGRAM TO DO STRING
MANIPULATION USING CHARACTER ARRAY AND
Date:
PERFORM THE FOLLOWING STRING
OPERATIONS:
“C-Concatenating two strings”

AIM:

Write a Java program that displays the String Manipulation using


Character Array, “Concatenating two strings”

PROCEDURE:

Step 1: Declare a public class named "StringManipulation".

Step 2: Define the main method inside the class.

Step 3: Declare two char arrays "str1" and "str2" containing the
characters of "Hello" and " World" respectively.

Step 4: Create a new char array "result" with a length equal to the
sum of the lengths of "str1" and "str2".

Step 5: Copy the characters from "str1" to the "result" array


starting from index 0 using System.arraycopy.

Step 6: Copy the characters from "str2" to the "result" array


starting from the index after the end of "str1" using
System.arraycopy.

Step 7: Convert the "result" char array to a String and print it,
displaying the concatenated string with space between
"Hello" and "World".

Step 8: End of the program.

24
SOURCE CODING:

public class StringManipulation {

public static void main(String[] args) {

char[] str1 = {'H', 'e', 'l', 'l', 'o'};

char[] str2 = {' ', 'W', 'o', 'r', 'l', 'd'};

char[] result = new char[str1.length + str2.length];

System.arraycopy(str1, 0, result, 0, str1.length);

System.arraycopy(str2, 0, result, str1.length, str2.length);

System.out.println("Concatenated String: " + new String(result));

25
OUTPUT:

Concatenated String: Hello World

RESULTS:

Thus, the above java program executed successfully and output verified.

26
Ex.No:06-A
Date: String operations using String class,
“A-String Concatenation”

AIM:

Write a Java program that displays the String operations using String
class, “String Concatenation”

PROCEDURE:

Step 1: Declare a public class named "StringConcatenation".

Step 2: Define the main method inside the class.

Step 3: Initialize two strings "str1" with the value "Hello, " and
"str2" with the value "World!".

Step 4: Concatenate the strings "str1" and "str2" using the '+'
operator, storing the result in a new string variable "result".

Step 5: Print the concatenated string "result".

Step 6: End of the program.

27
SOURCE CODING:

public class StringConcatenation {

public static void main(String[] args) {

// Initializing two strings

String str1 = "Hello, ";

String str2 = "World!";

// Concatenating the strings

String result = str1 + str2;

// Displaying the result

System.out.println(result);

28
OUTPUT:

Hello, World!

RESULTS:

Thus, the above java program executed successfully and output verified.
29
Ex.No:06-B
Date: String operations using String class,
“B-Search a substring”

AIM:

Write a Java program that displays the String operations using String
class, “Search a substring”

PROCEDURE:

Step 1: Declare a public class named "SubstringSearch".

Step 2: Define the main method inside the class.

Step 3: Initialize a string variable "mainString" with the value


"The quick brown fox jumps over the lazy dog.".

Step 4: Initialize a string variable "substring" with the value


"brown".

Step 5: Use the contains method of the String class to check if the
"mainString" contains the "substring".

Step 6: If the substring is found within the main string, print a


message indicating its existence.

Step 7: If the substring is not found within the main string, print a
message indicating its absence.

Step 8: End of the program.

30
SOURCE CODING:

public class SubstringSearch {

public static void main(String[] args) {

// Example string

String mainString = "The quick brown fox jumps over the lazy dog.";

// Substring to search for

String substring = "brown";

// Check if the substring exists in the main string

if (mainString.contains(substring)) {

System.out.println("The substring \"" + substring + "\" is found in the main


string.");

} else {

System.out.println("The substring \"" + substring + "\" is not found in the


main string.");

31
OUTPUT:

The substring "brown" is found in the main string

RESULTS:

Thus, the above java program executed successfully and output verified.
32
Ex.No:06-C
Date: String operations using String class,
“C-To extract substring from given string”

AIM:

Write a Java program that displays the String operations using String
class, “To extract substring from given string”

PROCEDURE:

Step 1: Declare a string variable mainString and assign it the


value "Hello, World!".

Step 2: Use the substring method on mainString to extract a


substring. Provide the starting index (inclusive) as 7 and
the ending index (exclusive) as 12.

Step 3: Assign the extracted substring to a new string variable


named extractedSubstring.

Step 4: Print the extracted substring along with a message


indicating what it is.

Step 5: End the program.

33
SOURCE CODING:

public class SubstringExtraction {

public static void main(String[] args) {

// Input string

String mainString = "Hello, World!";

// Extracting a substring

String extractedSubstring = mainString.substring(7, 12);

// Displaying the extracted substring

System.out.println("Extracted Substring: " + extractedSubstring);

34
OUTPUT:

Extracted Substring: World

RESULTS:

Thus, the above java program executed successfully and output verified.
35
Ex.No:07-A
Date: String operations using StringBuffer class,
“A-Length of a string”

AIM:

Write a Java program that displays the String operations using


StringBuffer class, “Length of a string”

PROCEDURE:

Step 1: Declare a string variable inputString and assign it the


value "Hello, World!".

Step 2: Create a StringBuffer object named stringBuffer by


passing inputString as an argument to its constructor.

Step 3: Use the length() method on the StringBuffer object


stringBuffer to get the length of the string.

Step 4: Assign the length of the string to an integer variable


named length.

Step 5: Print the length of the string along with a message


indicating what it represents.

Step 6: End the program

36
SOURCE CODING:

public class StringBufferLength {

public static void main(String[] args) {

// Input string

String inputString = "Hello, World!";

// Creating a StringBuffer from the input string

StringBuffer stringBuffer = new StringBuffer(inputString);

// Getting the length of the string using the length() method

int length = stringBuffer.length();

// Displaying the length of the string

System.out.println("Length of the string: " + length);

37
OUTPUT:

Length of the string: 13

RESULTS:

Thus, the above java program executed successfully and output verified.
38
Ex.No:07-B
Date: String operations using StringBuffer class,
“B-Reverse a string”

AIM:

Write a Java program that displays the String operations using


StringBuffer class, “Reverse a string”

PROCEDURE:

Step 1: Declare a string variable inputString and assign it the


value "Hello, World!".

Step 2: Create a StringBuffer object named stringBuffer by


passing inputString as an argument to its constructor.

Step 3: Use the reverse() method on the StringBuffer object


stringBuffer to reverse the characters of the string.

Step 4: Print the reversed string along with a message indicating


that it's the reversed string.

Step 5: End the program.

39
SOURCE CODING:

public class StringBufferReverse {

public static void main(String[] args) {

// Input string

String inputString = "Hello, World!";

// Creating a StringBuffer from the input string

StringBuffer stringBuffer = new StringBuffer(inputString);

// Reversing the string using the reverse() method

stringBuffer.reverse();

// Displaying the reversed string

System.out.println("Reversed String: " + stringBuffer);

40
OUTPUT:

Reversed String: !dlroW ,olleH

RESULTS:

Thus, the above java program executed successfully and output verified.
41
Ex.No:07-C
Date: String operations using StringBuffer class,
“C-Delete a substring from the given string”

AIM:

Write a Java program that displays the String operations using


StringBuffer class, “Delete a substring from the given string”

PROCEDURE:

Step 1: Declare a class named StringBufferSubstringDeletion.

Step 2: Define the main method within the class


StringBufferSubstringDeletion.

Step 3: Initialize a StringBuffer variable named mainString with


the value "Hello, World!".

Step 4: Declare a String variable named substringToDelete with


the value "World".

Step 5: Use the indexOf method of the StringBuffer class to find


the starting index of the substring to delete within the
mainString.

Step 6: Use the delete method of the StringBuffer class to remove


the substring from the mainString, providing the starting
index and the ending index (calculated by adding the
length of the substring).

Step 7: Display the modified string after deletion using the


System.out.println statement.

Step 8: End of the program.

42
SOURCE CODING:

public class StringBufferSubstringDeletion {

public static void main(String[] args) {

// Input string

StringBuffer mainString = new StringBuffer("Hello, World!");

// Substring to delete

String substringToDelete = "World";

// Deleting the substring

mainString.delete(mainString.indexOf(substringToDelete),
mainString.indexOf(substringToDelete) + substringToDelete.length());

// Displaying the modified string

System.out.println("String after deletion: " + mainString);

43
OUTPUT:

String after deletion: Hello, !

RESULTS:

Thus, the above java program executed successfully and output verified.
44
Ex.No:08 That implements a multi-thread application that has three
Date: threads. First thread generates random integer every 1 second
and if the value is even, second thread computes the square of
the number and prints. If the value is odd, the third thread will
print the value of cube of the number.

AIM:

Write a Java program That implements a multi-thread application that


has three threads. First thread generates random integer every 1 second and if the
value is even, second thread computes the square of the number and prints. If the
value is odd, the third thread will print the value of cube of the number.

PROCEDURE:

Step 1: Import the necessary Java utilities including Random.

Step 2: Define a class Square that extends Thread. This class


calculates the square of a given number.

Step 3: Define a class Cube that extends Thread. This class


calculates the cube of a given number.

Step 4: Define a class Number that extends Thread. This class


generates random integers, creates instances of Square and
Cube classes for each random integer, and starts their
threads.

Step 5: Inside the run() method of Number class, create a Random


object to generate random integers.

Step 6: Generate 10 random integers and print each one.

Step 7: For each random integer, create an instance of Square and


Cube, passing the random integer as a parameter, and start
their threads.

Step 8: Add a delay of 1000 milliseconds (1 second) using


Thread.sleep() to space out the generation of random
integers.

45
Step 9 : Define the main method in the LAB3B class.

Step 10 : Instantiate an object of the Number class.

Step 11: Start the thread by calling the start() method on the
Number object.

Step 12 : End of the program.

46
SOURCE CODING:

import java.util.Random;

class Square extends Thread

int x;

Square(int n)

x = n;

public void run()

int sqr = x * x;

System.out.println("Square of " + x + " = " + sqr );

class Cube extends Thread

int x;

Cube(int n)

x = n;

public void run()


47
{

int cub = x * x * x;

System.out.println("Cube of " + x + " = " + cub );

class Number extends Thread

public void run()

Random random = new Random();

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

int randomInteger = random.nextInt(100);

System.out.println("Random Integer generated : " + randomInteger);

Square s = new Square(randomInteger);

s.start();

Cube c = new Cube(randomInteger);

c.start();

try {

Thread.sleep(1000);

catch (InterruptedException ex)

{
48
System.out.println(ex);

public class LAB3B {

public static void main(String args[])

Number n = new Number();

n.start();

49
OUTPUT:

Random Integer generated : 42

Square of 42 = 1764

Cube of 42 = 74088

Random Integer generated : 57

Square of 57 = 3249

Cube of 57 = 185193

Random Integer generated : 89

Square of 89 = 7921

Cube of 89 = 704969

Random Integer generated : 15

Square of 15 = 225

Cube of 15 = 3375

Random Integer generated : 37

Square of 37 = 1369

Cube of 37 = 50653

Random Integer generated : 61

Square of 61 = 3721

Cube of 61 = 226981

Random Integer generated : 43

Square of 43 = 1849

Cube of 43 = 79507

Random Integer generated : 99


50
Square of 99 = 9801

Cube of 99 = 970299

Random Integer generated : 39

Square of 39 = 1521

Cube of 39 = 59319

Random Integer generated : 56

Square of 56 = 3136

Cube of 56 = 175616

RESULTS:

Thus, the above java program executed successfully and output verified.

51
Ex.No:09
Which uses the same method asynchronously to print the
Date:
numbers 1 to 10 using thread-0 and to print 90 to 100 using
thread-1

AIM:

Write a Java program that displays the same method asynchronously to


print the numbers 1 to 10 using thread-0 and to print 90 to 100 using thread-1

PROCEDURE:

Step 1: Create a class named "TenThreads" with a variable


"currentTaskValue" initialized to 1.

Step 2: In the main method of "TenThreads", create an instance of


"TenThreads" and a list to hold "ModThread" instances.

Step 3: Create 10 "ModThread" instances, passing each a unique


index and the "TenThreads" instance.

Step 4: Start each thread in the list.

Step 5: Define the "ModThread" class with variables "modValue"


and "monitor".

Step 6: In the "ModThread" constructor, initialize "modValue" and


"monitor".

Step 7: Override the "run" method.

Step 8: Inside "run", synchronize on "monitor".

Step 9: Use a while loop to wait until the current task value
modulo 10 equals the "modValue".

Step 10: Check if the current task value is 101, if so, break the
loop.

Step 11: Print the thread name and the current task value.

52
Step 12: Increment the current task value.

Step 13: Notify all waiting threads.

Step 14: End of the algorithm.

53
SOURCE CODING:

package com.xxxx.simpleapp;

import java.util.ArrayList;
import java.util.List;

public class TenThreads {

public int currentTaskValue = 1;

public static void main(String[] args) {


TenThreads monitor = new TenThreads();
List<ModThread> list = new ArrayList();
for (int i = 0; i < 10; i++) {
ModThread modThread = new ModThread(i, monitor);
list.add(modThread);
}
for (ModThread a : list) {
a.start();
}
}

class ModThread extends Thread {


private int modValue;
private TenThreads monitor;

public ModThread(int modValue, TenThreads monitor) {


this.modValue = modValue;
this.monitor = monitor;
}

@Override

54
public void run() {
synchronized (monitor) {
try {
while (true) {
while (monitor.currentTaskValue % 10 != modValue) {
monitor.wait();
}

if (monitor.currentTaskValue == 101) {
break;
}
System.out.println(Thread.currentThread().getName() + " : "
+ monitor.currentTaskValue + " ,");
monitor.currentTaskValue = monitor.currentTaskValue + 1;
monitor.notifyAll();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

55
OUTPUT:

Thread-1 : 1 ,
Thread-2 : 2 ,
Thread-3 : 3 ,
Thread-4 : 4 ,
Thread-5 : 5 ,
Thread-6 : 6 ,
Thread-7 : 7 ,
Thread-8 : 8 ,
Thread-9 : 9 ,
......
.....
...
Thread-4 : 94 ,
Thread-5 : 95 ,
Thread-6 : 96 ,
Thread-7 : 97 ,
Thread-8 : 98 ,
Thread-9 : 99 ,
Thread-0 : 100 ,

RESULTS:

Thus, the above java program executed successfully and output verified.
56
Ex.No:10 Write a program to demonstrate the use of following
Date: exceptions.
a) Arithmetic Exception
b) Number Format Exception
c) Array Index Out of Bound Exception
d) Negative Array Size Exception
AIM:

Write a Java program that displays the demonstrate the use of


following exceptions.
- Arithmetic Exception
- Number Format Exception
- Array Index Out of Bound Exception
- Negative Array Size Exception

PROCEDURE:

Step 1: Define a class named ExceptionDemo.

Step 2: Inside the ExceptionDemo class, implement the main()


method.

Step 3: Within the main() method:


Step 3.A: Handle Arithmetic Exception:
- Perform division by zero and assign the result to a variable
result.
- Catch the ArithmeticException and print a message along
with the exception's message.

Step 3.B: Handle Number Format Exception:


- Initialize a string variable str with a non-numeric value.
- Parse the string str to an integer variable num using
Integer.parseInt().
- Catch the NumberFormatException and print a message
along with the exception's message.

57
Step 3.C: Handle Array Index Out of Bound Exception:
- Create an integer array arr with a length of 3.
- Access an element at index 5 of the array arr.
- Catch the ArrayIndexOutOfBoundsException and print a
message along with the exception's message.

Step 3.D: Handle Negative Array Size Exception:


- Create an integer array with a negative size (-5).
- Catch the NegativeArraySizeException and print a message
along with the exception's message.

Step 4: End of the program.

58
SOURCE CODING:

public class ExceptionDemo {


public static void main(String[] args) {
// Arithmetic Exception
try {
int result = 10 / 0; // Division by zero
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception caught: " + e.getMessage());
}

// Number Format Exception


try {
String str = "abc";
int num = Integer.parseInt(str);
} catch (NumberFormatException e) {
System.out.println("Number Format Exception caught: " +
e.getMessage());
}

// Array Index Out of Bound Exception


try {
int[] arr = new int[3];
int value = arr[5]; // Accessing index out of bound
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Out of Bound Exception caught: " +
e.getMessage());
}

// Negative Array Size Exception


try {
int[] negativeArr = new int[-5]; // Creating array with negative size
} catch (NegativeArraySizeException e) {
System.out.println("Negative Array Size Exception caught: " +
e.getMessage());

59
}
}
}

60
OUTPUT:

Arithmetic Exception caught: / by zero


Number Format Exception caught: For input string: "abc"
Array Index Out of Bound Exception caught: Index 5 out of bounds for length 3
Negative Array Size Exception caught: -5

RESULTS:

Thus, the above java program executed successfully and output verified.

61

You might also like