Java Practical Programs
Java Practical Programs
1 . Write a Java program to print Fibonacci series using for loop. int[][] matrix1 = {
Source code: {1, 2, 3},
class FibonacciSeries { {4, 5, 6}
public static void main(String[] args) { };
int n = 10; // Number of terms to print
int firstTerm = 0; int[][] matrix2 = {
int secondTerm = 1; {7, 8},
System.out.println("Fibonacci Series up to " + n + " terms:"); {9, 10},
for (int i = 1; i <= n; ++i) { {11, 12}
System.out.print(firstTerm + " "); };
// Compute the next term
int nextTerm = firstTerm + secondTerm; // Calculate the product of the matrices
firstTerm = secondTerm; int[][] product = multiplyMatrices(matrix1, matrix2);
secondTerm = nextTerm;
} // Print the resulting product matrix
} System.out.println("Product of the matrices:");
} printMatrix(product);
Explanation }
1. Variables Initialization:
o n: The number of terms in the Fibonacci series to print. // Method to multiply two matrices
o firstTerm: Initialized to 0, the first term in the Fibonacci series. public static int[][] multiplyMatrices(int[][] firstMatrix, int[][] secondMatrix) {
o secondTerm: Initialized to 1, the second term in the Fibonacci int rows1 = firstMatrix.length;
series. int cols1 = firstMatrix[0].length;
2. For Loop: int cols2 = secondMatrix[0].length;
o Loop runs from 1 to n.
o Prints the current firstTerm. // Initialize the product matrix
o Computes the next term in the series by adding the current int[][] product = new int[rows1][cols2];
firstTerm and secondTerm.
o Updates firstTerm to the current secondTerm and secondTerm to // Perform matrix multiplication
the computed next term. for (int i = 0; i < rows1; i++) {
Sample Output: for (int j = 0; j < cols2; j++) {
Compile: javac FibonacciSeries.java for (int k = 0; k < cols1; k++) {
Run: java FibonacciSeries product[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
Fibonacci Series up to 10 terms: }
0 1 1 2 3 5 8 13 21 34 }
2 . Write a Java program to calculate multiplication of 2 matrices. }
Source code:
class MatrixMultiplication { return product;
public static void main(String[] args) { }
// Define two matrices
// Method to print a matrix
String filePath = "example.txt"; o The program reads each line of the file using reader.readLine().
o For each line, the lineCount is incremented.
// Variables to hold counts o The charCount is incremented by the length of the line.
int lineCount = 0; o The line is split into words using line.split("\\s+"), which splits the
int wordCount = 0; line based on whitespace. The number of words in the line is
int charCount = 0; added to wordCount.
5. Exception Handling:
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) o The try-with-resources statement ensures that the BufferedReader
{ is closed automatically after the block is executed.
String line; o If an IOException occurs, an error message is printed.
6. Displaying the Counts:
// Read the file line by line
o The counts of lines, words, and characters are displayed using
while ((line = reader.readLine()) != null) {
System.out.println.
lineCount++;
Example:
charCount += line.length();
Suppose example.txt contains the following text:
// Split the line into words based on whitespace Hello world!
String[] words = line.split("\\s+"); This is a test file.
wordCount += words.length; It contains multiple lines.
} Sample Output:
} catch (IOException e) { Compile: javac FileStatistics. java
System.out.println("An error occurred while reading the file: " + Run: java FileStatistics
e.getMessage()); Number of lines: 3
} Number of words: 9
Number of characters: 55
// Display the counts 7 . Write a Java program to implement various types of inheritance
System.out.println("Number of lines: " + lineCount); i. Single
System.out.println("Number of words: " + wordCount); ii. Multi-Level
System.out.println("Number of characters: " + charCount); iii. Hierarchical
} iv. Hybrid
} i. Single Inheritance
Explanation In Single Inheritance, a class inherits from one parent class.
1. File Path: Source code:
o String filePath = "example.txt";: Specifies the path to the text file. // Parent class
You can change this to the path of your text file. class Animal {
2. Counts Initialization: void eat() {
o lineCount, wordCount, and charCount are initialized to 0. System.out.println("This animal eats food.");
3. BufferedReader: }
o A BufferedReader wrapped around a FileReader is used to read }
the file line by line.
4. Reading the File: // Child class
public static void main(String[] args) { 10 . Implement a Java program for handling mouse events when the mouse
// Create thread instances entered, exited, clicked, pressed, released, dragged and moved in the client
GoodMorningThread goodMorningThread = new GoodMorningThread(); area.
HelloThread helloThread = new HelloThread(); Source code:
WelcomeThread welcomeThread = new WelcomeThread(); import javax.swing.*;
import java.awt.event.*;
// Start the threads
goodMorningThread.start(); public class MouseEventExample extends JFrame implements MouseListener,
helloThread.start(); MouseMotionListener {
welcomeThread.start();
} private JTextArea textArea;
}
Explanation public MouseEventExample() {
1. Thread Classes: setTitle("Mouse Event Example");
o GoodMorningThread: This thread prints "Good Morning" every setSize(400, 300);
1 second. It uses Thread.sleep(1000) to wait for 1 second between setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
prints. setLocationRelativeTo(null);
o HelloThread: This thread prints "Hello" every 2 seconds. It uses
Thread.sleep(2000) to wait for 2 seconds between prints. textArea = new JTextArea();
o WelcomeThread: This thread prints "Welcome" every 3 seconds. textArea.setEditable(false);
It uses Thread.sleep(3000) to wait for 3 seconds between prints. textArea.addMouseListener(this);
2. Main Method: textArea.addMouseMotionListener(this);
o Creates instances of each thread class.
o Starts each thread using the start() method. This invokes the run() add(new JScrollPane(textArea));
method of each thread, which contains the logic for printing the }
messages at specified intervals.
Sample Output: // MouseListener methods
Compile: javac MultiThreadExample java @Override
Run: java MultiThreadExample public void mouseClicked(MouseEvent e) {
Good Morning textArea.append("Mouse Clicked at (" + e.getX() + ", " + e.getY() + ")\n");
Hello }
Welcome
Good Morning @Override
Hello public void mousePressed(MouseEvent e) {
Good Morning textArea.append("Mouse Pressed at (" + e.getX() + ", " + e.getY() + ")\n");
Hello }
Welcome
Good Morning @Override
public void mouseReleased(MouseEvent e) {
textArea.append("Mouse Released at (" + e.getX() + ", " + e.getY() + ")\n");
}