Java Lab Internal Questions
Java Lab Internal Questions
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.
// 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 {
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@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;
try {
System.out.print("Enter the dividend: ");
int dividend = scanner.nextInt();
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;
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());
}
}
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;