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

Java Lab Internal Questions

Uploaded by

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

Java Lab Internal Questions

Uploaded by

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

GROUP-1

1. Write a Java Program to open a text file and read the contents from it. If the file have any
special characters other than alphabets and numeric characters create a user defined
exception named SpecialCharacterFoundException. Otherwise, display the contents
normally to the console output.
2. import java.io.BufferedReader;
3. import java.io.FileReader;
4. import java.io.IOException;
5.
6. class SpecialCharacterFoundException extends Exception {
7. public SpecialCharacterFoundException(String message) {
8. super(message);
9. }
10.}
11.
12.public class ReadTextFile {
13. public static void main(String[] args) {
14. try {
15. // Provide the path to your text file
16. String filePath = "D:\\Java Workspace\\JDBC\\src\\Abc.txt";
17.
18. // Read the contents of the file
19. String fileContents = readTextFile(filePath);
20.
21. // Display the contents if no special characters are found
22. System.out.println("File Contents:\n" + fileContents);
23. } catch (IOException e) {
24. System.err.println("Error reading the file: " +
e.getMessage());
25. } catch (SpecialCharacterFoundException e) {
26. System.err.println("Special Character Found: " +
e.getMessage());
27. }
28. }
29.
30. private static String readTextFile(String filePath) throws
IOException, SpecialCharacterFoundException {
31. StringBuilder content = new StringBuilder();
32.
33. try (BufferedReader reader = new BufferedReader(new
FileReader(filePath))) {
34. int currentChar;
35. while ((currentChar = reader.read()) != -1) {
36. char character = (char) currentChar;
37.
38. // Check if the character is not alphanumeric
39. if (!Character.isLetterOrDigit(character)) {
40. throw new SpecialCharacterFoundException("Special
character found: " + character);
41. }
42.
43. content.append(character);
44. }
45. }
46.
47. return content.toString();
48. }
49.}
50.
2. Write a java program such that deadlock occurs using synchronized method.

public class DeadLockExample {

public static void main(String[] args) {


Resource resource1 = new Resource();
Resource resource2 = new Resource();

// Thread 1
Thread thread1 = new Thread(() -> {
try {
resource1.method1(resource2);
} catch (InterruptedException e) {
e.printStackTrace();
}
});

// Thread 2
Thread thread2 = new Thread(() -> {
try {
resource2.method2(resource1);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
// Start both threads
thread1.start();
thread2.start();
}
}
class Resource {

synchronized void method1(Resource otherResource) throws


InterruptedException {
System.out.println(Thread.currentThread().getName() + " is executing
method1()");
Thread.sleep(1000); // Simulating some work
otherResource.method2(this);
}
synchronized void method2(Resource otherResource) throws
InterruptedException {
System.out.println(Thread.currentThread().getName() + " is executing
method2()");
otherResource.method1(this);
}
}
}
3. Write a program that reads a text file concurrently using multiple threads, and each thread
processes a portion of the file content.
4. import java.io.BufferedReader;
5. import java.io.FileReader;
6. import java.io.IOException;
7. import java.util.concurrent.ExecutorService;
8. import java.util.concurrent.Executors;
9.
10.public class ConcurrentFileReader {
11.
12. public static void main(String[] args) {
13. // Provide the path to your text file
14. String filePath = "D:\\Java Workspace\\JDBC\\src\\Abc.txt";
15.
16. // Number of threads to use
17. int numThreads = 3;
18.
19. // Create an ExecutorService with a fixed number of threads
20. ExecutorService executorService =
Executors.newFixedThreadPool(numThreads);
21.
22. try (BufferedReader reader = new BufferedReader(new
FileReader(filePath))) {
23. // Get the total number of lines in the file
24. int totalLines = getTotalLines(filePath);
25.
26. // Calculate the number of lines each thread should handle
27. int linesPerThread = totalLines / numThreads;
28.
29. // Submit tasks to the ExecutorService
30. for (int i = 0; i < numThreads; i++) {
31. int startLine = i * linesPerThread + 1;
32. int endLine = (i == numThreads - 1) ? totalLines : (i +
1) * linesPerThread;
33.
34. executorService.submit(new FileReaderTask(filePath,
startLine, endLine));
35. }
36. } catch (IOException e) {
37. System.err.println("Error reading the file: " +
e.getMessage());
38. } finally {
39. // Shut down the ExecutorService
40. executorService.shutdown();
41. }
42. }
43.
44. // Helper method to get the total number of lines in a file
45. private static int getTotalLines(String filePath) throws
IOException {
46. try (BufferedReader reader = new BufferedReader(new
FileReader(filePath))) {
47. int totalLines = 0;
48. while (reader.readLine() != null) {
49. totalLines++;
50. }
51. return totalLines;
52. }
53. }
54.}
55.
56.class FileReaderTask implements Runnable {
57. private final String filePath;
58. private final int startLine;
59. private final int endLine;
60. public FileReaderTask(String filePath, int startLine, int endLine)
{
61. this.filePath = filePath;
62. this.startLine = startLine;
63. this.endLine = endLine;
64. }
65. @Override
66. public void run() {
67. try (BufferedReader reader = new BufferedReader(new
FileReader(filePath))) {
68. // Skip lines until reaching the startLine
69. for (int i = 1; i < startLine; i++) {
70. reader.readLine();
71. }
72. // Read and process lines within the specified range
73. for (int i = startLine; i <= endLine; i++) {
74. String line = reader.readLine();
75. if (line != null) {
76. // Process the line (e.g., print it)
77. System.out.println("Thread " +
Thread.currentThread().getId() + ": " + line);
78. }
79. }
80. } catch (IOException e) {
81. System.err.println("Error reading the file: " +
e.getMessage());
82. }
83. }
84.}
85.
4. This program searches for a specific word in a text file using multiple threads. Each thread
reads a portion of the file content, and the program reports the line number where the word
is found.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConcurrentWordSearch {

public static final String SEARCH_WORD = "dfg";

public static void main(String[] args) {


// Provide the path to your text file
String filePath = "D:\\Java Workspace\\JDBC\\src\\Abc.txt";

// Number of threads to use


int numThreads = 3;

// Create an ExecutorService with a fixed number of threads


ExecutorService executorService =
Executors.newFixedThreadPool(numThreads);

try (BufferedReader reader = new BufferedReader(new


FileReader(filePath))) {
// Get the total number of lines in the file
int totalLines = getTotalLines(filePath);

// Calculate the number of lines each thread should handle


int linesPerThread = totalLines / numThreads;

// Submit tasks to the ExecutorService


for (int i = 0; i < numThreads; i++) {
int startLine = i * linesPerThread + 1;
int endLine = (i == numThreads - 1) ? totalLines : (i + 1) *
linesPerThread;

executorService.submit(new WordSearchTask(filePath, startLine,


endLine));
}
} catch (IOException e) {
System.err.println("Error reading the file: " + e.getMessage());
} finally {
// Shut down the ExecutorService
executorService.shutdown();
}
}

// Helper method to get the total number of lines in a file


private static int getTotalLines(String filePath) throws IOException {
try (BufferedReader reader = new BufferedReader(new
FileReader(filePath))) {
int totalLines = 0;
while (reader.readLine() != null) {
totalLines++;
}
return totalLines;
}
}
}

class WordSearchTask implements Runnable {


private final String filePath;
private final int startLine;
private final int endLine;

public WordSearchTask(String filePath, int startLine, int endLine) {


this.filePath = filePath;
this.startLine = startLine;
this.endLine = endLine;
}

@Override
public void run() {
try (BufferedReader reader = new BufferedReader(new
FileReader(filePath))) {
// Skip lines until reaching the startLine
for (int i = 1; i < startLine; i++) {
reader.readLine();
}

// Read and search for the word in lines within the specified
range
for (int lineNumber = startLine; lineNumber <= endLine;
lineNumber++) {
String line = reader.readLine();
if (line != null &&
line.contains(ConcurrentWordSearch.SEARCH_WORD)) {
// Word found, print the line number and the line
System.out.println("Thread " +
Thread.currentThread().getId() +
": Word found at line " + lineNumber + ": " +
line);
}
}
} catch (IOException e) {
System.err.println("Error reading the file: " + e.getMessage());
}
}
}

5. Write a java code to create Framebased application that displays the coordinates of the
mouse when a mouse creates any event such as mouse pressed, released, clicked, entered or
exited.
6. import java.awt.Frame;
7. import java.awt.Label;
8. import java.awt.event.MouseAdapter;
9. import java.awt.event.MouseEvent;
10.
11.public class MouseEventApp {
12. private Frame frame;
13. private Label label;
14.
15. public MouseEventApp() {
16. frame = new Frame("Mouse Events App");
17. label = new Label();
18.
19. frame.addMouseListener(new MouseAdapter() {
20. @Override
21. public void mousePressed(MouseEvent e) {
22. showMouseEvent("Mouse Pressed", e);
23. }
24.
25. @Override
26. public void mouseReleased(MouseEvent e) {
27. showMouseEvent("Mouse Released", e);
28. }
29.
30. @Override
31. public void mouseClicked(MouseEvent e) {
32. showMouseEvent("Mouse Clicked", e);
33. }
34.
35. @Override
36. public void mouseEntered(MouseEvent e) {
37. showMouseEvent("Mouse Entered", e);
38. }
39.
40. @Override
41. public void mouseExited(MouseEvent e) {
42. showMouseEvent("Mouse Exited", e);
43. }
44. });
45.
46. frame.setLayout(null);
47. label.setBounds(20, 50, 300, 30);
48. frame.add(label);
49.
50. frame.setSize(400, 300);
51. frame.setVisible(true);
52.
53. frame.addWindowListener(new java.awt.event.WindowAdapter() {
54. public void windowClosing(java.awt.event.WindowEvent
windowEvent) {
55. System.exit(0);
56. }
57. });
58. }
59.
60. private void showMouseEvent(String eventType, MouseEvent e) {
61. int x = e.getX();
62. int y = e.getY();
63. label.setText(eventType + " at (" + x + ", " + y + ")");
64. }
65.
66. public static void main(String[] args) {
67. new MouseEventApp();
68. }
69.}
70.
GROUP-2
1. Demonstrate the creation and use of a custom exception (CustomException) in Java.
2. public class CustomExceptionExample {
3.
4. public static void main(String[] args) {
5. try {
6. // Simulate a situation that triggers the custom exception
7. int result = divideNumbers(10, 0);
8.
9. // This line won't be reached if an exception is thrown
10. System.out.println("Result: " + result);
11. } catch (CustomException e) {
12. // Catch and handle the custom exception
13. System.err.println("Custom Exception Caught: " +
e.getMessage());
14. }
15. }
16.
17. // A method that may throw a custom exception
18. private static int divideNumbers(int dividend, int divisor) throws
CustomException {
19. if (divisor == 0) {
20. // Throw the custom exception if the divisor is zero
21. throw new CustomException("Cannot divide by zero!");
22. }
23.
24. // Perform the division if the divisor is not zero
25. return dividend / divisor;
26. }
27.}
28.
29.// Custom exception class extending Exception
30.class CustomException extends Exception {
31. public CustomException(String message) {
32. super(message);
33. }
34.}
35.
2. Write a java program to show how to handle arithmetic exceptions, in this case, division by
zero.

import java.util.Scanner;

public class DivideByZeroHandler {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

try {
System.out.print("Enter the dividend: ");
int dividend = scanner.nextInt();

System.out.print("Enter the divisor: ");


int divisor = scanner.nextInt();

// Perform division and handle arithmetic exception


int result = divideNumbers(dividend, divisor);

// Print the result if no exception occurs


System.out.println("Result of division: " + result);
} catch (ArithmeticException e) {
// Catch and handle arithmetic exception (division by zero)
System.err.println("Error: " + e.getMessage());
} catch (Exception e) {
// Catch any other exceptions that may occur
System.err.println("An unexpected error occurred: " +
e.getMessage());
} finally {
// Close the scanner to prevent resource leak
scanner.close();
}
}

// A method that may throw an arithmetic exception


private static int divideNumbers(int dividend, int divisor) {
// Check for division by zero
if (divisor == 0) {
// Throw an arithmetic exception
throw new ArithmeticException("Cannot divide by zero!");
}

// Perform the division if the divisor is not zero


return dividend / divisor;
}
}
3. Write a program that reads a text file and identify words that start with vowels copy into
another file.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class VowelWordsExtractor {

public static void main(String[] args) {


// Provide the paths to your input and output files
String inputFilePath = "D:\\Java Workspace\\JDBC\\src\\Abc.txt";
String outputFilePath = "D:\\Java Workspace\\JDBC\\src\\Output.txt";

try {
extractVowelWords(inputFilePath, outputFilePath);
System.out.println("Vowel words extracted and copied to the output
file successfully.");
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}

private static void extractVowelWords(String inputFilePath, String


outputFilePath) throws IOException {
// Create a BufferedReader to read from the input file
try (BufferedReader reader = new BufferedReader(new
FileReader(inputFilePath));
// Create a BufferedWriter to write to the output file
BufferedWriter writer = new BufferedWriter(new
FileWriter(outputFilePath))) {

// Define a regular expression to match words starting with vowels


Pattern pattern = Pattern.compile("\\b[aeiouAEIOU]\\w*\\b");

String line;
while ((line = reader.readLine()) != null) {
// Use a Matcher to find words matching the pattern in each
line
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
// Write the matching words to the output file
writer.write(matcher.group());
writer.newLine(); // Add a new line for each word
}
}
}
}
}

4. Write a program that displays various information about a file, such as its size, last modified
date, and whether it's a directory or a file.

import java.io.File;

public class FileInfo {

public static void main(String[] args) {


// Provide the path to the file or directory
String filePath = "D:\\Java Workspace\\JDBC\\src\\Abc.txt";

// Create a File object


File file = new File(filePath);

// Check if the file exists


if (file.exists()) {
// Display information about the file
System.out.println("File Information:");
System.out.println("Name: " + file.getName());
System.out.println("Path: " + file.getAbsolutePath());
System.out.println("Size: " + file.length() + " bytes");
System.out.println("Last Modified: " + file.lastModified());
System.out.println("Is Directory: " + file.isDirectory());
System.out.println("Is File: " + file.isFile());
} else {
System.out.println("File not found: " + filePath);
}
}
}
5. Create a java program that prints first 10 factorial, Fibonacci, odd and even numbers using
different threads. Ensure that threads are terminated in the order of Odd, Even, Fibonacci,
Factorial only.
6. public class MultiThreadExample {
7.
8. public static void main(String[] args) {
9. Thread oddThread = new Thread(new OddNumberPrinter());
10. Thread evenThread = new Thread(new EvenNumberPrinter());
11. Thread fibonacciThread = new Thread(new FibonacciPrinter());
12. Thread factorialThread = new Thread(new FactorialPrinter());
13.
14. // Start the threads
15. oddThread.start();
16. evenThread.start();
17. fibonacciThread.start();
18. factorialThread.start();
19.
20. try {
21. // Join the threads to ensure they terminate in the
specified order
22. oddThread.join();
23. evenThread.join();
24. fibonacciThread.join();
25. factorialThread.join();
26. } catch (InterruptedException e) {
27. e.printStackTrace();
28. }
29.
30. System.out.println("Main thread terminated.");
31. }
32.}
33.
34.class OddNumberPrinter implements Runnable {
35.
36. @Override
37. public void run() {
38. System.out.println("Odd Numbers:");
39. for (int i = 1; i <= 20; i += 2) {
40. System.out.println("Odd Thread: " + i);
41. }
42. System.out.println("Odd thread terminated.");
43. }
44.}
45.
46.class EvenNumberPrinter implements Runnable {
47.
48. @Override
49. public void run() {
50. System.out.println("Even Numbers:");
51. for (int i = 2; i <= 20; i += 2) {
52. System.out.println("Even Thread: " + i);
53. }
54. System.out.println("Even thread terminated.");
55. }
56.}
57.
58.class FibonacciPrinter implements Runnable {
59.
60. @Override
61. public void run() {
62. System.out.println("Fibonacci Numbers:");
63. int n = 10;
64. int a = 0, b = 1;
65. for (int i = 0; i < n; i++) {
66. System.out.println("Fibonacci Thread: " + a);
67. int temp = a;
68. a = b;
69. b = temp + b;
70. }
71. System.out.println("Fibonacci thread terminated.");
72. }
73.}
74.
75.class FactorialPrinter implements Runnable {
76.
77. @Overrid
78. public void run() {
79. System.out.println("Factorials:");
80. for (int i = 1; i <= 10; i++) {
81. System.out.println("Factorial Thread: " + factorial(i));
82. }
83. System.out.println("Factorial thread terminated.");
84. }
85.
86. private long factorial(int n) {
87. if (n == 0 || n == 1) {
88. return 1;
89. }
90. return n * factorial(n - 1);
91. }
92.}
93.

You might also like