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

Java File

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)
4 views12 pages

Java File

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
You are on page 1/ 12

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

Code :

import java.util.Arrays;
public class AnagramChecker {
public static boolean areAnagrams(String str1, String str2) {
if (str1.length()!= str2.length()) {
return false;
}
char[] arr1 = str1.toLowerCase().toCharArray();
char[] arr2 = str2.toLowerCase().toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
for (int i = 0; i < arr1.length; 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)) {
System.out.println("The strings are anagrams.");
} else {
System.out.println("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 java.util.Scanner;
public class PangramChecker {
public static boolean isPangram(String str) {
str = str.toLowerCase();
for (char c = 'a'; c <= 'z'; c++) {
if (str.indexOf(c) == -1) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
if (isPangram(inputString)) {
System.out.println("The string is a pangram.");
} else {
System.out.println("The string is not a pangram.");
}

scanner.close();
}
}

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 java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class DistinctCharacterCounter {
public static int countDistinctCharacters(String str) {
Set<Character> distinctCharacters = new HashSet<>();
for (char c : str.toCharArray()) {
distinctCharacters.add(c);
}
return distinctCharacters.size();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
int distinctCount = countDistinctCharacters(inputString);
System.out.println("The number of distinct characters in the string is: " +
distinctCount);
scanner.close();
}
}

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 java.util.Scanner;
public class SubstringChecker {
public static boolean isSubstring(String mainString, String subString) {
return mainString.contains(subString);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the main string: ");
String mainString = scanner.nextLine();
System.out.print("Enter the substring to check: ");
String subString = scanner.nextLine();
if (isSubstring(mainString, subString)) {
System.out.println("The substring exists in the main string.");
} else {
System.out.println("The substring does not exist in the main string.");
}
scanner.close();
}
}

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 java.util.Scanner;
public class SuffixChecker {
public static boolean endsWithSuffix(String str) {
return str.endsWith("ed") || str.endsWith("ing");
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
if (endsWithSuffix(inputString)) {
System.out.println("The string ends with 'ed' or 'ing'.");
} else {
System.out.println("The string does not end with 'ed' or 'ing'.");
}
scanner.close();
}
}

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);
System.out.println(num1 + " is not a multiple of both 5 and 7.");
int num2 = 15;
checkMultiple(num2);
System.out.println(num2 + " is not a multiple of both 5 and 7.");
} catch (MultipleOfBothException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

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 java.util.*;
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 (!set.add(num)) {
throw new DuplicateNumberException("Duplicate number found: " + num);
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a list of integers separated by space: ");
String input = scanner.nextLine().trim();
List<Integer> numbers = new ArrayList<>();
try {
String[] parts = input.split("\\s+");
for (String part : parts) {
numbers.add(Integer.parseInt(part));
}
checkDuplicates(numbers);
System.out.println("No duplicates found in the list.");
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter integers separated by
space.");
} catch (DuplicateNumberException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
scanner.close();
}
}

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) {
sb.append(i).append(" ");
}
}
System.out.println(sb.toString().trim());
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

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;
System.out.println("Division result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
}
}
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Usage: java DivideNumbers <numerator>
<denominator>");
return;
}
try {
int numerator = Integer.parseInt(args[0]);
int denominator = Integer.parseInt(args[1]);
divideNumbers(numerator, denominator);
} catch (NumberFormatException e) {
System.out.println("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;
System.out.println("Division result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
}
}
public static void main(String[] args) {
try {
if (args.length < 2) {
throw new ArrayIndexOutOfBoundsException("Insufficient arguments
provided.");
}
int numerator = Integer.parseInt(args[0]);
int denominator = Integer.parseInt(args[1]);
divideNumbers(numerator, denominator);
} catch (NumberFormatException e) {
System.out.println("Error: Please enter valid integers for numerator and
denominator.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage());
System.out.println("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++;
System.out.println("Counter value: " + counter);
}
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
incrementCounter();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
incrementCounter();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

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

You might also like