0% found this document useful (0 votes)
63 views13 pages

Java Programs: Fibonacci, Matrix, Rectangle

Uploaded by

sujanak0203
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views13 pages

Java Programs: Fibonacci, Matrix, Rectangle

Uploaded by

sujanak0203
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1

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

[Link] Reddy MCA


Lec in Computer Science
2

public static void printMatrix(int[][] matrix) {


for (int[] row : matrix) { // Constructor
for (int element : row) { public Rectangle() {
[Link](element + " "); [Link] = 0;
} [Link] = 0;
[Link](); }
}
} // Method to read attributes from the user
} public void readAttributes() {
Explanation Scanner scanner = new Scanner([Link]);
1. Matrices Definition: [Link]("Enter the length of the rectangle: ");
o matrix1 and matrix2 are the two matrices to be multiplied. [Link] = [Link]();
2. Multiplication Method: [Link]("Enter the width of the rectangle: ");
o The multiplyMatrices method performs the matrix multiplication. [Link] = [Link]();
It takes two matrices as input and returns their product. }
o The product matrix is initialized with dimensions based on the
number of rows of the first matrix and the number of columns of // Method to calculate the perimeter
the second matrix. public double calculatePerimeter() {
o Nested loops iterate through the rows of the first matrix, columns return 2 * (length + width);
of the second matrix, and columns of the first matrix (which }
equals the number of rows of the second matrix).
o The multiplication of corresponding elements and summation are // Method to calculate the area
performed to fill the product matrix. public double calculateArea() {
3. Printing the Matrix: return length * width;
o The printMatrix method prints the resulting product matrix row by }
row.
Sample Output: // Method to display the rectangle's properties
Compile: javac MatrixMultiplication java public void displayProperties() {
Run: java MatrixMultiplication [Link]("Length: " + length);
Product of the matrices: [Link]("Width: " + width);
58 64 [Link]("Perimeter: " + calculatePerimeter());
139 154 [Link]("Area: " + calculateArea());
3 . Create a class Rectangle. The class has attributes length and width. It }
should have methods that calculate the perimeter and area of the rectangle. It
should have read Attributes method to read length and width from user. public static void main(String[] args) {
Source code: Rectangle rectangle = new Rectangle();
import [Link]; [Link]();
class Rectangle { [Link]();
private double length; }
private double width; }
Explanation

[Link] Reddy MCA


Lec in Computer Science
3

1. Attributes: // Overloaded method to add three integers


o length and width: These are private attributes of the Rectangle public int add(int a, int b, int c) {
class. return a + b + c;
2. Constructor: }
o Initializes length and width to 0.
3. Method readAttributes: // Overloaded method to add two double values
o Uses a Scanner object to read length and width from the user public double add(double a, double b) {
input. return a + b;
4. Method calculatePerimeter: }
o Calculates the perimeter of the rectangle using the formula 2 *
(length + width). // Overloaded method to add three double values
5. Method calculateArea: public double add(double a, double b, double c) {
o Calculates the area of the rectangle using the formula length * return a + b + c;
width. }
6. Method displayProperties:
o Prints the length, width, perimeter, and area of the rectangle. public static void main(String[] args) {
7. Main Method: MethodOverloadingExample example = new MethodOverloadingExample();
o Creates an instance of Rectangle.
o Calls the readAttributes method to get user input for length and // Calling overloaded methods
width. [Link]("Sum of 2 integers (10 + 20): " + [Link](10, 20));
o Calls the displayProperties method to display the rectangle's [Link]("Sum of 3 integers (10 + 20 + 30): " + [Link](10,
properties. 20, 30));
Sample Output: [Link]("Sum of 2 doubles (10.5 + 20.5): " + [Link](10.5,
Compile: javac Rectangle. java 20.5));
Run: java Rectangle [Link]("Sum of 3 doubles (10.5 + 20.5 + 30.5): " +
Enter the length of the rectangle: 5 [Link](10.5, 20.5, 30.5));
Enter the width of the rectangle: 3 }
Length: 5.0 }
Width: 3.0 Explanation
Perimeter: 16.0 1. Method Overloading:
o First Method: public int add(int a, int b)
Area: 15.0
4 . Write a Java program that implements method overloading.  Takes two integers and returns their sum.
Source code: o Second Method: public int add(int a, int b, int c)
class MethodOverloadingExample {  Takes three integers and returns their sum.
o Third Method: public double add(double a, double b)
// Method to add two integers  Takes two double values and returns their sum.
public int add(int a, int b) { o Fourth Method: public double add(double a, double b, double c)
return a + b;  Takes three double values and returns their sum.
} 2. Main Method:
o Creates an instance of MethodOverloadingExample.

[Link] Reddy MCA


Lec in Computer Science
4

o Calls the overloaded add methods with different parameters. Explanation


o Prints the results. 1. Import Statements:
3. Sample Output: o import [Link];: Imports the Arrays class which contains
Sample Output: the sort method.
Compile: javac MethodOverloadingExample. java o import [Link];: Imports the Scanner class for reading
Run: java MethodOverloadingExample user input.
Sum of 2 integers (10 + 20): 30 2. Main Method:
Sum of 3 integers (10 + 20 + 30): 60 o Creates a Scanner object to read input from the user.
Sum of 2 doubles (10.5 + 20.5): 31.0 o Reads the number of names from the user.
Sum of 3 doubles (10.5 + 20.5 + 30.5): 61.5 o Initializes an array of String to store the names.
5 . Write a Java program for sorting a given list of names in ascending order. o Uses a loop to read each name and store it in the array.
Source code: o Sorts the array of names using [Link].
import [Link]; o Prints the sorted names.
import [Link]; Sample Output:
Compile: javac SortNames. java
class SortNames { Run: java SortNames
public static void main(String[] args) { Enter the number of names: 5
Scanner scanner = new Scanner([Link]); Enter the names:
John
// Read the number of names Alice
[Link]("Enter the number of names: "); Bob
int numberOfNames = [Link](); Eve
[Link](); // Consume newline Charlie
// Read the names Names in ascending order:
String[] names = new String[numberOfNames]; Alice
[Link]("Enter the names:"); Bob
for (int i = 0; i < numberOfNames; i++) { Charlie
names[i] = [Link](); Eve
} John
6 . Write a Java program that displays the number of characters, lines and
// Sort the names
[Link](names); words in a text file.
Source code:
// Display the sorted names import [Link];
[Link]("Names in ascending order:"); import [Link];
for (String name : names) { import [Link];
[Link](name);
} class FileStatistics {
} public static void main(String[] args) {
} // Specify the file path

[Link] Reddy MCA


Lec in Computer Science
5

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

[Link] Reddy MCA


Lec in Computer Science
6

class Dog extends Animal { [Link]();


void bark() { [Link]();
[Link]("The dog barks."); [Link]();
} }
} }
iii. Hierarchical Inheritance
class SingleInheritance { In Hierarchical Inheritance, multiple classes inherit from a single parent class.
public static void main(String[] args) { Source code:
Dog dog = new Dog(); // Parent class
[Link](); class Animal {
[Link](); void eat() {
} [Link]("This animal eats food.");
} }
ii. Multi-Level Inheritance }
In Multi-Level Inheritance, a class is derived from another class which is also
derived from another class. // Child class 1
Source code: class Dog extends Animal {
// Grandparent class void bark() {
class Animal { [Link]("The dog barks.");
void eat() { }
[Link]("This animal eats food."); }
}
} // Child class 2
class Cat extends Animal {
// Parent class void meow() {
class Dog extends Animal { [Link]("The cat meows.");
void bark() { }
[Link]("The dog barks."); }
}
} class HierarchicalInheritance {
public static void main(String[] args) {
// Child class Dog dog = new Dog();
class Puppy extends Dog { [Link]();
void play() { [Link]();
[Link]("The puppy plays.");
} Cat cat = new Cat();
} [Link]();
[Link]();
class MultiLevelInheritance { }
public static void main(String[] args) { }
Puppy puppy = new Puppy(); iv. Hybrid Inheritance

[Link] Reddy MCA


Lec in Computer Science
7

Hybrid Inheritance is a combination of two or more types of inheritance. However, Explanation


Java does not support multiple inheritance directly to avoid complexity and 1. Single Inheritance:
simplify the language. But we can achieve Hybrid Inheritance using interfaces. o Animal is the parent class.
Source code: o Dog is the child class that inherits from Animal.
// Interface 2. Multi-Level Inheritance:
interface CanFly { o Animal is the grandparent class.
void fly(); o Dog is the parent class that inherits from Animal.
} o Puppy is the child class that inherits from Dog.
3. Hierarchical Inheritance:
// Base class o Animal is the parent class.
class Animal { o Dog and Cat are child classes that inherit from Animal.
void eat() { 4. Hybrid Inheritance:
[Link]("This animal eats food."); o Animal is the base class.
} o CanFly is an interface.
} o Bird inherits from Animal and implements the CanFly interface.
o Dog inherits from Animal.
// Derived class 1
8 . Write a java program to implement runtime polymorphism.
class Bird extends Animal implements CanFly {
Source code:
public void fly() {
// Parent class
[Link]("The bird flies.");
Class Animal {
}
void sound() {
}
[Link]("Animal makes a sound");
}
// Derived class 2
}
class Dog extends Animal {
void bark() {
// Child class 1
[Link]("The dog barks.");
class Dog extends Animal {
}
@Override
}
void sound() {
[Link]("Dog barks");
class HybridInheritance {
}
public static void main(String[] args) {
}
Bird bird = new Bird();
[Link]();
// Child class 2
[Link]();
class Cat extends Animal {
@Override
Dog dog = new Dog();
void sound() {
[Link]();
[Link]("Cat meows");
[Link]();
}
}
}
}

[Link] Reddy MCA


Lec in Computer Science
8

public void run() {


public class RuntimePolymorphism { try {
public static void main(String[] args) { while (true) {
// Parent reference, child object [Link]("Good Morning");
Animal myAnimal; [Link](1000); // Sleep for 1 second
}
// Dog object } catch (InterruptedException e) {
myAnimal = new Dog(); [Link](e);
[Link](); // Calls Dog's sound method }
}
// Cat object }
myAnimal = new Cat();
[Link](); // Calls Cat's sound method // Thread to display "Hello" every 2 seconds
} class HelloThread extends Thread {
} public void run() {
Explanation try {
1. Parent Class: while (true) {
o Animal class has a method sound which prints a generic sound. [Link]("Hello");
2. Child Classes: [Link](2000); // Sleep for 2 seconds
o Dog class overrides the sound method to print "Dog barks". }
o Cat class overrides the sound method to print "Cat meows". } catch (InterruptedException e) {
3. Main Method: [Link](e);
o An Animal reference is created. }
o The Animal reference is assigned to a Dog object and the sound }
method is called. This demonstrates runtime polymorphism as the }
Dog class's sound method is executed.
o The Animal reference is then assigned to a Cat object and the // Thread to display "Welcome" every 3 seconds
sound method is called. This demonstrates runtime polymorphism class WelcomeThread extends Thread {
as the Cat class's sound method is executed. public void run() {
Sample Output: try {
Compile: javac Animal. java while (true) {
Run: java Animal [Link]("Welcome");
Dog barks [Link](3000); // Sleep for 3 seconds
Cat meows }
9 . Write a Java program to create three threads and that displays “good } catch (InterruptedException e) {
morning”, for every one second, “hello” for every 2 seconds and “welcome” [Link](e);
for every 3 seconds by using extending Thread class. }
Source code: }
// Thread to display "Good Morning" every 1 second }
class GoodMorningThread extends Thread {
class MultiThreadExample {

[Link] Reddy MCA


Lec in Computer Science
9

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");
}

[Link] Reddy MCA


Lec in Computer Science
10

o mouseClicked(MouseEvent e): Handles mouse click events.


@Override o mousePressed(MouseEvent e): Handles mouse press events.
public void mouseEntered(MouseEvent e) { o mouseReleased(MouseEvent e): Handles mouse release events.
[Link]("Mouse Entered the client area\n"); o mouseEntered(MouseEvent e): Handles when the mouse enters the
} client area.
o mouseExited(MouseEvent e): Handles when the mouse exits the
@Override client area.
public void mouseExited(MouseEvent e) { 4. MouseMotionListener Methods:
[Link]("Mouse Exited the client area\n"); o mouseDragged(MouseEvent e): Handles mouse drag events.
} o mouseMoved(MouseEvent e): Handles mouse move events.
5. Main Method:
// MouseMotionListener methods o Uses [Link] to ensure the GUI is created and
@Override updated on the Event Dispatch Thread (EDT).
public void mouseDragged(MouseEvent e) { Running the Program
[Link]("Mouse Dragged at (" + [Link]() + ", " + [Link]() + ")\n"); When you run this program, a window will appear with a text area. As you interact
} with the text area using the mouse, different messages will be appended to the text
area based on the mouse events.
@Override This program provides a practical demonstration of handling various mouse events
public void mouseMoved(MouseEvent e) { and updates the user interface accordingly.
[Link]("Mouse Moved at (" + [Link]() + ", " + [Link]() + ")\n"); 11 . Write a Java program to design student registration form using Swing
} Controls. The form which having the following fields and button SAVE
Here's a Java Swing program that creates a student registration form with the
public static void main(String[] args) { following fields and a "Save" button:
[Link](() -> {  Name
MouseEventExample frame = new MouseEventExample();  Age
[Link](true);  Gender (using radio buttons)
});  Address
}  Email
}  Phone Number
Explanation The form will have a "Save" button that, when clicked, prints the collected data to
1. Class Definition: the console.
o MouseEventExample extends JFrame and implements Source code:
MouseListener and MouseMotionListener. import [Link].*;
2. Constructor: import [Link].*;
o Sets up the frame, including the title, size, default close operation, import [Link];
and layout. import [Link];
o Initializes a JTextArea to display mouse events and adds it to a
JScrollPane. public class StudentRegistrationForm extends JFrame implements ActionListener
o Registers the frame to listen to mouse events using {
addMouseListener and addMouseMotionListener.
3. MouseListener Methods:
[Link] Reddy MCA
Lec in Computer Science
11

// Define form components


private JTextField nameField; JLabel phoneLabel = new JLabel("Phone Number:");
private JTextField ageField; phoneField = new JTextField(20);
private JRadioButton maleRadioButton;
private JRadioButton femaleRadioButton; saveButton = new JButton("Save");
private JTextArea addressArea; [Link](this);
private JTextField emailField;
private JTextField phoneField; // Add components to the frame
private JButton saveButton; [Link] = 0;
[Link] = 0;
public StudentRegistrationForm() { add(nameLabel, gbc);
// Set up the frame
setTitle("Student Registration Form"); [Link] = 1;
setSize(400, 300); add(nameField, gbc);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); [Link] = 0;
setLayout(new GridBagLayout()); [Link] = 1;
GridBagConstraints gbc = new GridBagConstraints(); add(ageLabel, gbc);
[Link] = new Insets(5, 5, 5, 5);
[Link] = 1;
// Initialize form components add(ageField, gbc);
JLabel nameLabel = new JLabel("Name:");
nameField = new JTextField(20); [Link] = 0;
[Link] = 2;
JLabel ageLabel = new JLabel("Age:"); add(genderLabel, gbc);
ageField = new JTextField(20);
[Link] = 1;
JLabel genderLabel = new JLabel("Gender:"); [Link] = 2;
maleRadioButton = new JRadioButton("Male"); add(maleRadioButton, gbc);
femaleRadioButton = new JRadioButton("Female");
ButtonGroup genderGroup = new ButtonGroup(); [Link] = 2;
[Link](maleRadioButton); add(femaleRadioButton, gbc);
[Link](femaleRadioButton);
[Link] = 0;
JLabel addressLabel = new JLabel("Address:"); [Link] = 3;
addressArea = new JTextArea(3, 20); add(addressLabel, gbc);
[Link](true);
[Link](true); [Link] = 1;
[Link] = 2;
JLabel emailLabel = new JLabel("Email:"); add(new JScrollPane(addressArea), gbc);
emailField = new JTextField(20);

[Link] Reddy MCA


Lec in Computer Science
12

[Link] = 0; [Link](this, "Registration details saved


[Link] = 4; successfully!");
add(emailLabel, gbc); }
}
[Link] = 1;
add(emailField, gbc); public static void main(String[] args) {
[Link](() -> {
[Link] = 0; StudentRegistrationForm form = new StudentRegistrationForm();
[Link] = 5; [Link](true);
add(phoneLabel, gbc); });
}
[Link] = 1; }
add(phoneField, gbc); Explanation
1. Class Definition:
[Link] = 1; o StudentRegistrationForm extends JFrame and implements
[Link] = 6; ActionListener to handle button clicks.
[Link] = 2; 2. Constructor:
add(saveButton, gbc); o Sets up the frame properties (title, size, layout).
} o Initializes and configures all form components (labels, text fields,
radio buttons, text area, button).
@Override o Adds components to the frame using GridBagLayout for better
public void actionPerformed(ActionEvent e) { control of component positioning.
if ([Link]() == saveButton) { 3. ActionListener:
// Collect data from form fields o Implements actionPerformed method to handle the "Save" button
String name = [Link](); click event.
String age = [Link](); o Collects data from the form fields and prints it to the console.
String gender = [Link]() ? "Male" : "Female"; o Shows a confirmation dialog using JOptionPane.
String address = [Link](); 4. Main Method:
String email = [Link](); o Uses [Link] to ensure the GUI is created and
String phone = [Link](); updated on the Event Dispatch Thread (EDT).
Running the Program
// Print data to the console When you run this program, a registration form window will appear. After filling
[Link]("Name: " + name); in the form and clicking the "Save" button, the entered data will be printed to the
[Link]("Age: " + age); console, and a confirmation message will be shown.
[Link]("Gender: " + gender); This program provides a basic example of how to create and manage a form with
[Link]("Address: " + address); Swing controls in Java.
[Link]("Email: " + email);
[Link]("Phone Number: " + phone);

// Show a confirmation message

[Link] Reddy MCA


Lec in Computer Science
13

[Link] Reddy MCA


Lec in Computer Science

You might also like