Java Programs: Fibonacci, Matrix, Rectangle
Java Programs: Fibonacci, Matrix, Rectangle
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},
[Link]("Fibonacci Series up to " + n + " terms:"); {9, 10},
for (int i = 1; i <= n; ++i) { {11, 12}
[Link](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
} [Link]("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 = [Link];
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 [Link] 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 = "[Link]"; o The program reads each line of the file using [Link]().
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 [Link]("\\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 = [Link]()) != null) {
[Link].
lineCount++;
Example:
charCount += [Link]();
Suppose [Link] contains the following text:
// Split the line into words based on whitespace Hello world!
String[] words = [Link]("\\s+"); This is a test file.
wordCount += [Link]; It contains multiple lines.
} Sample Output:
} catch (IOException e) { Compile: javac FileStatistics. java
[Link]("An error occurred while reading the file: " + Run: java FileStatistics
[Link]()); 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
[Link]("Number of lines: " + lineCount); i. Single
[Link]("Number of words: " + wordCount); ii. Multi-Level
[Link]("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 = "[Link]";: 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. [Link]("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 [Link].*;
import [Link].*;
// Start the threads
[Link](); public class MouseEventExample extends JFrame implements MouseListener,
[Link](); MouseMotionListener {
[Link]();
} 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 [Link](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
[Link](2000) to wait for 2 seconds between prints. textArea = new JTextArea();
o WelcomeThread: This thread prints "Welcome" every 3 seconds. [Link](false);
It uses [Link](3000) to wait for 3 seconds between prints. [Link](this);
2. Main Method: [Link](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 [Link]("Mouse Clicked at (" + [Link]() + ", " + [Link]() + ")\n");
Hello }
Welcome
Good Morning @Override
Hello public void mousePressed(MouseEvent e) {
Good Morning [Link]("Mouse Pressed at (" + [Link]() + ", " + [Link]() + ")\n");
Hello }
Welcome
Good Morning @Override
public void mouseReleased(MouseEvent e) {
[Link]("Mouse Released at (" + [Link]() + ", " + [Link]() + ")\n");
}