java programs
java programs
import java.util.Scanner;
public class Fibonacci {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of terms: ");
int n = scanner.nextInt();
scanner.close();
int t1 = 0, t2 = 1;
System.out.println("Fibonacci Series up to " + n + " terms:");
for (int i = 1; i <= n; i++) {
System.out.print(t1 + " ");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
}
}
}
Output:
Enter the number of terms:
20
Fibonacci Series up to 20 terms:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
—-----------------------------------------------------------------------------------------------------------------------------------------------
2. Write a Java program to calculate multiplication of 2 matrices
import java.util.Scanner;
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of rows for Matrix A: ");
int rowsA = scanner.nextInt();
System.out.println("Enter the number of columns for Matrix A: ");
int colsA = scanner.nextInt();
System.out.println("Enter the number of rows for Matrix B: ");
int rowsB = scanner.nextInt();
System.out.println("Enter the number of columns for Matrix B: ");
int colsB = scanner.nextInt();
if (colsA != rowsB) {
System.out.println("Error: Matrices cannot be multiplied");
return;
}
int[][] matrixA = new int[rowsA][colsA];
int[][] matrixB = new int[rowsB][colsB];
int[][] result = new int[rowsA][colsB];
System.out.println("Enter elements for Matrix A: ");
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsA; j++) {
matrixA[i][j] = scanner.nextInt();
}
}
System.out.println("Enter elements for Matrix B: ");
for (int i = 0; i < rowsB; i++) {
for (int j = 0; j < colsB; j++) {
matrixB[i][j] = scanner.nextInt();
}
}
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
for (int k = 0; k < colsA; k++) {
result[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}
System.out.println("Resultant Matrix: ");
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
System.out.print(result[i][j] + " ");
}
System.out.println();
}
}
}
Output:
Enter the number of rows for Matrix A:
2
Enter the number of columns for Matrix A:
2
Enter the number of rows for Matrix B:
2
Enter the number of columns for Matrix B:
2
Enter elements for Matrix A:
1
2
3
4
Enter elements for Matrix B:
5
6
7
8
Resultant Matrix:
19 22
43 50
—-----------------------------------------------------------------------------------------------------------------------------------------------
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
import java.util.Scanner;
public class Rectangle {
private double length;
private double width;
Output :
30
31.2
60
—-----------------------------------------------------------------------------------------------------------------------------------------------
5. Write a Java program for sorting a given list of names in ascending order.
// Java Program to Sort Names in an Alphabetical Order
import java.io.*;
import java.util.*;
class SortingNamesEX {
public static void main(String[] args)
{
// storing input in variable
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of names: ");
int n = scanner.nextInt();
String[] names = new String[n];
System.out.println("Enter the names: ");
for (int i = 0; i < n; i++) {
names[i] = scanner.next();
}
String temp;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// to compare one string with other strings
if (names[i].compareTo(names[j]) > 0) {
// swapping
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
// print output array
System.out.println("The names in alphabetical order are: ");
for (int i = 0; i < n; i++) {
System.out.println(names[i]);
}
}
}
Output:
Enter the number of names:
8
Enter the names:
c
o
m
p
u
t
e
r
The names in alphabetical order are:
c
e
m
o
p
r
t
u
output 2 :
Enter the number of names:
8
Enter the names:
computer
The names in alphabetical order are:
c e m o p r t u
—-----------------------------------------------------------------------------------------------------------------------------------------------
6. Write a Java program that displays the number of characters, lines and words in a text file.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TextFileAnalyzer {
public static void main(String[] args) {
try {
File file = new File("Fibonaci.java");
Scanner scanner = new Scanner(file);
int characters = 0;
int lines = 0;
int words = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lines++;
characters += line.length() + 1; // +1 for newline character
String[] wordArray = line.split("\\s+");
words += wordArray.length;
}
scanner.close();
System.out.println("Characters: " + characters);
System.out.println("Lines: " + lines);
System.out.println("Words: " + words);
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
}
}
Output 1:
File not found!
Output 2:
Characters: 540
Lines: 22
Words: 93
—-----------------------------------------------------------------------------------------------------------------------------------------------
7. Write a Java program to implement various types of inheritance
i. Single ii. Multi-Level iii. Hierarchical iv. Hybrid
class Animal {
void eat() {
System.out.println("Eating...");
}
}
// Derived class
class Dog extends Animal {
void bark() {
System.out.println("Barking...");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Inherited method from Animal class
myDog.bark(); // Method of Dog class
}
}
Output :
Eating...
Barking…
—-----------------------------------------------------------------------------------------------------------------------------------------------
// Base class
class Animal {
void eat() {
System.out.println("Eating...");
}
}
// Intermediate class
class Mammal extends Animal {
void walk() {
System.out.println("Walking...");
}
}
// Derived class
class Dog extends Mammal {
void bark() {
System.out.println("Barking...");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Inherited method from Animal class
myDog.walk(); // Inherited method from Mammal class
myDog.bark(); // Method of Dog class
}
}
Output :
Eating...
Walking...
Barking…
—-----------------------------------------------------------------------------------------------------------------------------------------------
// Base class
class Animal {
void eat() {
System.out.println("Eating...");
}
}
// Derived class 1
class Mammal extends Animal {
void walk() {
System.out.println("Walking...");
}
}
// Derived class 2
class Bird extends Animal {
void fly() {
System.out.println("Flying...");
}
}
public class Main {
public static void main(String[] args) {
Mammal myMammal = new Mammal();
myMammal.eat(); // Inherited method from Animal class
myMammal.walk(); // Method of Mammal class
// Base class
class Animal {
void eat() {
System.out.println("Eating...");
}
}
// Intermediate class
class Mammal extends Animal {
void walk() {
System.out.println("Walking...");
}
}
// Derived class 1
class Dog extends Mammal {
void bark() {
System.out.println("Barking...");
}
}
// Derived class 2
class Cat extends Mammal {
void meow() {
System.out.println("Meowing...");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Inherited method from Animal class
myDog.walk(); // Inherited method from Mammal class
myDog.bark(); // Method of Dog class
// Base class
class Animal {
void sound() {
System.out.println("The animal makes a sound");
}
}
// Derived class 1
class Dog extends Animal {
@Override
void sound() {
System.out.println("The dog barks");
}
}
// Derived class 2
class Cat extends Animal {
@Override
void sound() {
System.out.println("The cat meows");
}
}
public class Main {
public static void main(String[] args) {
// Create an array of animals
Animal[] animals = new Animal[2];
animals[0] = new Dog();
animals[1] = new Cat();
import java.util.Scanner;
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
public class InsufficientEx {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter available amount: ");
double availableAmount = scanner.nextDouble();
System.out.println("Enter withdraw amount: ");
double withdrawAmount = scanner.nextDouble();
try {
if (withdrawAmount > availableAmount) {
throw new InsufficientFundsException("Insufficient Funds");
} else {
System.out.println("Withdrawal successful");
}
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage());
}
}
}
Output 1:
Enter available amount:
10000
Enter withdraw amount:
100
Withdrawal successful
Output 2:
Enter available amount:
10000
Enter withdraw amount:
100000
Insufficient Funds
—-----------------------------------------------------------------------------------------------------------------------------------------------
10. Write a Java program to create three threads and that displays “good morning”, for every one second,
“hello” for every 2 seconds and “welcome” for every 3 seconds by using extending Thread class.
goodMorningThread.start();
helloThread.start();
welcomeThread.start();
}
}
Output :
Hello
Welcome
Good morning
Good morning
Hello
Good morning
Welcome
Good morning
Hello
Good morning
Good morning
Hello
Welcome
Good morning
Good morning
Hello
Good morning
Good morning
—-----------------------------------------------------------------------------------------------------------------------------------------------
11.Write a Java program that creates three threads. First thread displays “OOPS”, the second thread
displays “Through” and the third thread Displays “JAVA” by using Runnable interface.
oopsThread.start();
throughThread.start();
javaThread.start();
}
}
Output :
OOPS
Through
JAVA
OOPS
Through
OOPS
JAVA
OOPS
Through
OOPS
JAVA
Through
Through
JAVA
JAVA
—-----------------------------------------------------------------------------------------------------------------------------------------------
12. Implement a Java program for handling mouse events when the mouse entered, exited, clicked, pressed,
released, dragged and moved in the client area.
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MouseEventHandler extends JFrame implements MouseListener, MouseMotionListener {
public MouseEventHandler() {
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked at (" + e.getX() + "," + e.getY() + ")");
}
public void mousePressed(MouseEvent e) {
System.out.println("Mouse pressed at (" + e.getX() + "," + e.getY() + ")");
}
public void mouseReleased(MouseEvent e) {
System.out.println("Mouse released at (" + e.getX() + "," + e.getY() + ")");
}
public void mouseEntered(MouseEvent e) {
System.out.println("Mouse entered at (" + e.getX() + "," + e.getY() + ")");
}
public void mouseExited(MouseEvent e) {
System.out.println("Mouse exited at (" + e.getX() + "," + e.getY() + ")");
}
public void mouseDragged(MouseEvent e) {
System.out.println("Mouse dragged at (" + e.getX() + "," + e.getY() + ")");
}
public void mouseMoved(MouseEvent e) {
System.out.println("Mouse moved at (" + e.getX() + "," + e.getY() + ")");
}
public static void main(String[] args) {
MouseEventHandler frame = new MouseEventHandler();
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output :
Mouse entered at (277,285)
Mouse moved at (277,285)
Mouse moved at (275,278)
Mouse moved at (273,272)
Mouse moved at (273,268)
Mouse moved at (273,265)
Mouse moved at (273,263)
Mouse moved at (274,263)
Mouse moved at (279,266)
Mouse moved at (289,273)
Mouse exited at (427,402)
—-----------------------------------------------------------------------------------------------------------------------------------------------
13. Implement a Java program for handling key events when the key board is pressed, released, typed.
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class KeyEventHandler {
public static void main(String[] args) {
JFrame frame = new JFrame("Key Event Handler");
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField textField = new JTextField();
textField.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
System.out.println("Key pressed: " + e.getKeyChar());
}
public void keyReleased(KeyEvent e) {
System.out.println("Key released: " + e.getKeyChar());
}
public void keyTyped(KeyEvent e) {
System.out.println("Key typed: " + e.getKeyChar());
}
});
frame.add(textField);
frame.setVisible(true);
}
}
Output :
Key pressed: c
Key typed: c
Key released: c
—-----------------------------------------------------------------------------------------------------------------------------------------------
14.Write a Java swing program that reads two numbers from two separate text fields and display sum of two
numbers in third text field when button “add” is pressed.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SumCalculator {
public static void main(String[] args) {
JFrame frame = new JFrame("Sum Calculator");
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField num1Field = new JTextField(10);
JTextField num2Field = new JTextField(10);
JTextField sumField = new JTextField(10);
JButton addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());
int sum = num1 + num2;
sumField.setText(String.valueOf(sum));
}
});
JPanel panel = new JPanel();
panel.add(new JLabel("Number 1:"));
panel.add(num1Field);
panel.add(new JLabel("Number 2:"));
panel.add(num2Field);
panel.add(addButton);
System.out.println("\n");
panel.add(new JLabel("Sum:"));
panel.add(sumField);
frame.add(panel);
frame.setVisible(true);
}
}
Output :
—-----------------------------------------------------------------------------------------------------------------------------------------------
15. Write a Java program to design student registration form using Swing Controls. The form which having the
following fields and button SAVE
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class StudentRegistrationForm {
public static void main(String[] args) {
JFrame frame = new JFrame("Student Registration Form");
frame.setSize(250, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create form fields
JTextField nameField = new JTextField(20);
JTextField rnoField = new JTextField(20);
JTextField mailidField = new JTextField(20);
JRadioButton maleButton = new JRadioButton("Male");
JRadioButton femaleButton = new JRadioButton("Female");
ButtonGroup genderGroup = new ButtonGroup();
genderGroup.add(maleButton);
genderGroup.add(femaleButton);
JComboBox<String> branchCombo = new JComboBox<>(new String[]{"CS", "AI", "GEOLOGY",
"CHEMISTRY","PHYSICS","STATISTICS"});
JTextArea addressField = new JTextArea(5, 20);
// Create SAVE button
JButton saveButton = new JButton("SAVE");
saveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Get form data
String name = nameField.getText();
System.out.println("\n");
String rno = rnoField.getText();
String mailid = mailidField.getText();
String gender = maleButton.isSelected() ? "Male" : "Female";
String branch = (String) branchCombo.getSelectedItem();
String address = addressField.getText();
// Display form data
JOptionPane.showMessageDialog(frame, "Name: " + name + "\nRNO: " + rno + "\nMailid: " + mailid +
"\nGender: " + gender + "\nBranch: " + branch + "\nAddress: " + address);
}
});
// Add form fields and button to panel
JPanel panel = new JPanel();
panel.add(new JLabel("Name:"));
panel.add(nameField);
panel.add(new JLabel("RNO:"));
panel.add(rnoField);
panel.add(new JLabel("Mailid:"));
panel.add(mailidField);
panel.add(new JLabel("Gender:"));
panel.add(maleButton);
panel.add(femaleButton);
panel.add(new JLabel("Branch:"));
panel.add(branchCombo);
panel.add(new JLabel("Address:"));
panel.add(new JScrollPane(addressField));
panel.add(saveButton);
frame.add(panel);
frame.setVisible(true);
}
}
Output :