[Go to site: main page, start]

0% found this document useful (0 votes)
10 views12 pages

Java String and Exception Handling Programs

Uploaded by

sv825385
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)
10 views12 pages

Java String and Exception Handling Programs

Uploaded by

sv825385
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

Q1- Write a program to check whether the given string is anagram or not

Code :

import [Link];
public class AnagramChecker {
public static boolean areAnagrams(String str1, String str2) {
if ([Link]()!= [Link]()) {
return false;
}
char[] arr1 = [Link]().toCharArray();
char[] arr2 = [Link]().toCharArray();
[Link](arr1);
[Link](arr2);
for (int i = 0; i < [Link]; i++) {
if (arr1[i]!= arr2[i]) {
return false;
}
}
return true;
}
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
if (areAnagrams(str1, str2)) {
[Link]("The strings are anagrams.");
} else {
[Link]("The strings are not anagrams.");
}
}
}

Output :

The strings are anagrams.

1
Q2- Write a program to check whether the given string is panagram or not.

Code:

import [Link];
public class PangramChecker {
public static boolean isPangram(String str) {
str = [Link]();
for (char c = 'a'; c <= 'z'; c++) {
if ([Link](c) == -1) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a string: ");
String inputString = [Link]();
if (isPangram(inputString)) {
[Link]("The string is a pangram.");
} else {
[Link]("The string is not a pangram.");
}

[Link]();
}
}

Output :

Enter a string: Hello World


The string is not a pangram.

2
Q3- Write a program to count the distinct characters in a string.

Code:

import [Link];
import [Link];
import [Link];
public class DistinctCharacterCounter {
public static int countDistinctCharacters(String str) {
Set<Character> distinctCharacters = new HashSet<>();
for (char c : [Link]()) {
[Link](c);
}
return [Link]();
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a string: ");
String inputString = [Link]();
int distinctCount = countDistinctCharacters(inputString);
[Link]("The number of distinct characters in the string is: " +
distinctCount);
[Link]();
}
}

Output:

Enter a string: Hello World


The number of distinct characters in the string is: 8

3
Q4- Write a program to check whether a given substring exists in a main string or
not.

Code:

import [Link];
public class SubstringChecker {
public static boolean isSubstring(String mainString, String subString) {
return [Link](subString);
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the main string: ");
String mainString = [Link]();
[Link]("Enter the substring to check: ");
String subString = [Link]();
if (isSubstring(mainString, subString)) {
[Link]("The substring exists in the main string.");
} else {
[Link]("The substring does not exist in the main string.");
}
[Link]();
}
}

Output:

Enter the main string: Hello World


Enter the substring to check: World
The substring exists in the main string.

4
Q5- Write a program to check whether the given string ends with 'ed' or 'ing' suffix.

Code:

import [Link];
public class SuffixChecker {
public static boolean endsWithSuffix(String str) {
return [Link]("ed") || [Link]("ing");
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a string: ");
String inputString = [Link]();
if (endsWithSuffix(inputString)) {
[Link]("The string ends with 'ed' or 'ing'.");
} else {
[Link]("The string does not end with 'ed' or 'ing'.");
}
[Link]();
}
}

Output:

Enter a string: started


The string ends with 'ed' or 'ing'.

5
Q6- Write a Java program to create a method that takes an integer as a parameter
and throws an exception if the number is a multiple of both 5 and 7, otherwise not.

Code:

class MultipleOfBothException extends Exception {


public MultipleOfBothException(String message) {
super(message);
}
}
public class MultipleChecker {
public static void checkMultiple(int number) throws MultipleOfBothException {
if (number % 5 == 0 && number % 7 == 0) {
throw new MultipleOfBothException(number + " is a multiple of both 5 and
7.");
}
}
public static void main(String[] args) {
try {
int num1 = 35;
checkMultiple(num1);
[Link](num1 + " is not a multiple of both 5 and 7.");
int num2 = 15;
checkMultiple(num2);
[Link](num2 + " is not a multiple of both 5 and 7.");
} catch (MultipleOfBothException e) {
[Link]("Caught Exception: " + [Link]());
}
}
}

Output:

35 is a multiple of both 5 and 7.


Caught Exception: 35 is a multiple of both 5 and 7.

6
Q7- Write a Java program that reads a list of integers from the user and throws an
exception if any numbers are duplicates.

Code:

import [Link].*;
class DuplicateNumberException extends Exception {
public DuplicateNumberException(String message) {
super(message);
}
}
public class DuplicateChecker {
public static void checkDuplicates(List<Integer> numbers) throws
DuplicateNumberException {
Set<Integer> set = new HashSet<>();
for (int num : numbers) {
if (![Link](num)) {
throw new DuplicateNumberException("Duplicate number found: " + num);
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a list of integers separated by space: ");
String input = [Link]().trim();
List<Integer> numbers = new ArrayList<>();
try {
String[] parts = [Link]("\\s+");
for (String part : parts) {
[Link]([Link](part));
}
checkDuplicates(numbers);
[Link]("No duplicates found in the list.");
} catch (NumberFormatException e) {
[Link]("Invalid input. Please enter integers separated by
space.");
} catch (DuplicateNumberException e) {
[Link]("Caught Exception: " + [Link]());
}
[Link]();
}
}

Output:

Enter a list of integers separated by space: 1 2 3 4 5 2


Caught Exception: Duplicate number found: 2

7
Q8- Write a program using thread to print all multiples of 3 between 1 to 100.

Code:

public class MultiplesOfThreePrinter {


public static void main(String[] args) {
Thread thread = new Thread(() -> {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0) {
[Link](i).append(" ");
}
}
[Link]([Link]().trim());
});
[Link]();
try {
[Link]();
} catch (InterruptedException e) {
[Link]();
}
}
}

Outout:

3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84
87 90 93 96 99

8
Q9- Write a Java program that demonstrates the basic concept of exception
handling. Perform the following steps:
● Create a method divideNumbers(int numerator, int denominator) that takes
two integer parameters: numerator and denominator.
● Inside the method, attempt to divide the numerator by the denominator.
● Use a try-catch, block to handle any potential arithmetic exception that may
occur (e.g., division by zero).
● If an exception occurs, print an appropriate error message.
● Test your method by calling it with different values and observe the output
● Input must be given using Command Line Argument

Code:

public class DivideNumbers {


public static void divideNumbers(int numerator, int denominator) {
try {
int result = numerator / denominator;
[Link]("Division result: " + result);
} catch (ArithmeticException e) {
[Link]("Error: Division by zero is not allowed.");
}
}
public static void main(String[] args) {
if ([Link] < 2) {
[Link]("Usage: java DivideNumbers <numerator>
<denominator>");
return;
}
try {
int numerator = [Link](args[0]);
int denominator = [Link](args[1]);
divideNumbers(numerator, denominator);
} catch (NumberFormatException e) {
[Link]("Error: Please enter valid integers for numerator and
denominator.");
}
}
}

Output:

$ java DivideNumbers 8 0
Error: Division by zero is not allowed.

9
Q10- Extend the previous program to handle multiple types of exceptions. Perform
the following steps:
● Modify the divideNumbers method to also handle NumberFormatException as
well as ArrayIndexOutOfBoundsException
● Handle all Exceptions separately using multiple catch blocks.
● Print appropriate error messages for each type of exception,
● Test your method with different inputs to ensure all exceptions are handled
correctly.

Code:

public class DivideNumbers {


public static void divideNumbers(int numerator, int denominator) {
try {
int result = numerator / denominator;
[Link]("Division result: " + result);
} catch (ArithmeticException e) {
[Link]("Error: Division by zero is not allowed.");
}
}
public static void main(String[] args) {
try {
if ([Link] < 2) {
throw new ArrayIndexOutOfBoundsException("Insufficient arguments
provided.");
}
int numerator = [Link](args[0]);
int denominator = [Link](args[1]);
divideNumbers(numerator, denominator);
} catch (NumberFormatException e) {
[Link]("Error: Please enter valid integers for numerator and
denominator.");
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Error: " + [Link]());
[Link]("Usage: java DivideNumbers <numerator>
<denominator>");
}
}
}

Output:

$ java DivideNumbers 8 0
Error: Division by zero is not allowed.

10
Q11- Write a Java program that demonstrates synchronization between multiple
threads. Perform the following steps:
● Create a counter variable (shared resource) that will be accessed by multiple
threads.
● Define a method to increment the counter value.
● Create multiple threads that simultaneously attempt to increment the counter.
● Use synchronization to ensure that only one thread can increment the counter
at a time.
● Print the updated counter value after each increment operation.

Code:

public class CounterDemo {


private static int counter = 0;
private synchronized static void incrementCounter() {
counter++;
[Link]("Counter value: " + counter);
}
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
incrementCounter();
try {
[Link](100);
} catch (InterruptedException e) {
[Link]();
}
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
incrementCounter();
try {
[Link](100);
} catch (InterruptedException e) {
[Link]();
}
}
});
[Link]();
[Link]();
try {
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]();
}
}
}

11
Output:

Counter value: 1
Counter value: 2
Counter value: 3
Counter value: 4
Counter value: 5
Counter value: 6
Counter value: 7
Counter value: 8
Counter value: 9
Counter value: 10

12

Common questions

Powered by AI

The strategic purpose of using a synchronized method in a multi-threaded environment, as in the `CounterDemo` program, is to control access to a shared resource, the counter. By declaring the `incrementCounter` method synchronized, the program ensures only one thread can execute the method at any given time, thus preventing race conditions where multiple threads attempt to read, modify, and write shared data concurrently. This exclusive lock mechanism is crucial in maintaining data integrity and consistency across threads when the shared resource is accessed multiple times .

The method `areAnagrams` checks the length of the input strings first because if two strings are to be anagrams, they must have the same number of characters. By checking the lengths up front, the algorithm can quickly return `false` if the strings differ in size, which saves computing time by avoiding unnecessary character comparisons and sorting .

Using specific exception handlers is crucial as it allows the program to provide precise and contextually appropriate error messages for each type of exception encountered, improving the clarity and usability of the application. In the given program, separate catch blocks for `ArithmeticException`, `NumberFormatException`, and `ArrayIndexOutOfBoundsException` provide tailored messages for division by zero, invalid number formats, and insufficient arguments, respectively. This approach not only enhances user feedback but also aids debugging by clearly indicating the nature of the error .

Using a HashSet in the `DistinctCharacterCounter` program is effective for counting distinct characters because a HashSet inherently prevents duplicates, automatically distinctively storing only unique characters from the string. This choice of data structure ensures that the addition of each character is managed in constant average time complexity, O(1), making the overall performance efficient. However, the potential downside is the memory overhead, as a HashSet uses more space compared to a simple array, due to the way elements are stored and hashed .

The primary mechanism to ensure thread safety when incrementing a shared resource is synchronization. In the provided example, the `incrementCounter` method is declared as synchronized, which ensures that only one thread can execute this method at a time, preventing race conditions. When a method is synchronized, the thread holding the lock on the method will complete its execution before another thread can invoke it, thus maintaining thread safety .

When processing input strings with very large lengths in the anagram checking program, potential runtime issues could arise due to the sorting step, which has a time complexity of O(n log n) where n is the length of the string. Longer strings increase the computation time exponentially, leading to significant delays. Additionally, memory usage might become a limiting factor since two sorted arrays need to be held in memory simultaneously, potentially causing memory overflow if the string lengths exceed available memory resources .

Exception handling in the `DuplicateChecker` program maintains robust user interaction by catching and managing anticipated errors such as duplicate numbers or invalid input formats. By using custom exceptions like `DuplicateNumberException`, the program can provide specific feedback to users, defining clear remedies or actions they can take. This promotes a user-friendly experience, as users are guided to correct their inputs or understand the application's state without frustration or confusion due to abrupt interruptions or cryptic error messages .

The custom exception `MultipleOfBothException` in the `MultipleChecker` program enhances error handling by providing a clear, specific indication that an unusual condition has occurred: the number being a multiple of both 5 and 7. This exception allows the developer to catch and handle this specific scenario distinctly from other types of numeric errors, enabling precise debugging and error reporting. Potential use cases for such a custom exception include situations where specific business rules need to be enforced or when a condition requires unique handling separate from common exceptions .

The `PangramChecker` class determines if a string is a pangram by converting it to lowercase and iterating through each letter of the alphabet to check for its presence in the string. This is efficient because it only requires a single pass through the alphabet (O(1) checks per character), making the complexity linear with respect to the alphabet size, not the string length. A limitation, however, is that this method does not account for non-alphabetic characters or multiple languages, and relies on the input string being in English .

The use of threads in the `MultiplesOfThreePrinter` enhances the program by enabling it to execute the logic for printing multiples of 3 concurrently, without blocking the main execution thread. This design allows potentially other processes or threads to run simultaneously, potentially improving overall application efficiency and responsiveness. The benefits include better CPU utilization and the potential to handle other tasks while waiting for this separate computation to complete. However, in this simple case, the impact on execution is minimal, but it provides an illustration of multithreading .

You might also like