practical 2025 java mca
practical 2025 java mca
Aim :- Write a Java program that converts temperatures between Celsius and Fahrenheit based on
user input using methods for conversion and input validation.
Code:- import java.util.Scanner;
public class TemperatureConverter
{
public static double celsiusToFahrenheit(double celsius)
{
return (fahrenheit - 32) * 5/9;
}
public static double getValidTemperatureInput(Scanner scanner)
while (!scanner.hasNextDouble())
{
return scanner.nextDouble();
}
public static void main(String[] args)
case 1:
}
System.out.println();
scanner.close();
}
}
Output :-
Program - 2
Aim:- Implement a Java program to perform matrix addition, multiplication, and transpose
operations using arrays and methods. Code:- import java.util.Scanner; public class
MatrixOperations
{
{
int rows = matrix1.length; int cols
{
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
return result;
}
public static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2)
{
for (int j = 0; j < cols2; j++)
result[i][j] = 0;
for (int k = 0; k < cols1; k++)
}
return result;
{
result[j][i] = matrix[i][j];
}
}
return result;
}
public static int[][] getMatrixInput(Scanner scanner, int rows, int cols)
matrix[i][j] = scanner.nextInt();
}
}
return matrix;
}
public static void printMatrix(int[][] matrix)
{
System.out.print(element + " ");
}
System.out.println();
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
else
{
}
System.out.println("Transpose of Matrix 1:"); int[][] transposeMatrix1 =
transposeMatrix(matrix1); printMatrix(transposeMatrix1);
System.out.println("Transpose of Matrix 2:"); int[][] transposeMatrix2 =
transposeMatrix(matrix2); printMatrix(transposeMatrix2) scanner.close();
}
}
Output :-
Program - 3
Aim:- Develop a Java program that converts a decimal number to its binary, octal,
and hexadecimal equivalents using loops and methods. Code:- import java.util.Scanner;
public class DecimalConverter
{
{
StringBuilder binary = new StringBuilder();
while (num> 0)
{
StringBuilder octal = new StringBuilder();
while (num> 0) { octal.insert(0, num % 8);
num = num / 8;
}
{
StringBuilder hex = new StringBuilder(); char[]
hexDigits = "0123456789ABCDEF".toCharArray();
while (num> 0)
{
hex.insert(0, hexDigits[num % 16]);
num = num / 16;
}
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
int decimal = scanner.nextInt();
System.out.println("Binary: " + decimalToBinary(decimal));
System.out.println("Octal: " + decimalToOctal(decimal));
scanner.close();
}
Output :-
Program - 4
Aim:- Create a Java program to simulate a simple bank account management system with
features like deposit, withdrawal, and balance inquiry using classes, objects, and encapsulation.
Code:- import java.util.Scanner; class BankAccount
{
private double balance; private String accountNumber; public
BankAccount(String accountNumber, double initialBalance)
{
this.accountNumber = accountNumber;
this.balance = initialBalance;
return balance;
}
public void deposit(double amount)
if (amount > 0)
{
balance += amount;
else
{
System.out.println("Invalid deposit amount.");
}
public void withdraw(double amount)
{
if (amount > 0 && amount <= balance)
balance -= amount;
System.out.println("Withdrawal successful! Current balance: $" + balance);
}
else
{
}
}
}
}
{
public static void main(String[] args)
System.out.println("2. Withdraw");
System.out.print("Choose an option:
"); int choice = scanner.nextInt();
switch (choice)
{
case 1:
case 2:
scanner.close();
}
}
Output :-
Program - 5
Aim:- Write a Java program that reads a text file, counts the occurrences of each word,
and displays the top N most frequent words using HashMap for storage and sorting.
Code:- import java.io.File; import java.io.FileNotFoundException; import java.util.*; import
java.util.Map.Entry; public class WordFrequencyCounter
{
public static Map<String, Integer>countWordOccurrences(String fileName) throws FileNotFoundException
{
while (fileScanner.hasNext())
if (!word.isEmpty())
{
wordMap.put(word, wordMap.getOrDefault(word, 0) + 1);
}
fileScanner.close();
return wordMap;
}
public static void displayTopNWords(Map<String, Integer>wordMap, int N)
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
try
{
Map<String, Integer>wordMap = countWordOccurrences(fileName);
displayTopNWords(wordMap, N);
}
catch (FileNotFoundException e)
{
System.out.println("File not found. Please make sure the file path is correct.");
}
scanner.close();
Output:-
Program - 6
Aim:- Implement a Java program to generate the first N prime numbers using a combination of
loops, methods, and optimizations like the Sieve of Eratosthenes algorithm. Code:- import
java.util.ArrayList; import java.util.List; import java.util.Scanner; public class PrimeGenerator
{
public static List<Integer>generatePrimes(int N)
{
isPrime[i] = true;
{
if (isPrime[p])
{
isPrime[multiple] = false; // Mark multiples of p as non-prime
}
}
if (isPrime[i])
primes.add(i);
}
}
return primes;
}
public static void main(String[] args)
int N = scanner.nextInt();
}
System.out.println();
scanner.close();
}
}
Output :-
Program - 7
Aim:- Develop a Java program that takes a month and year as input and prints the calendar for
that month using control flow statements and loops for date calculation. Code:- import
java.util.Scanner public class CalendarPrinter
{
{
return 31;
return 30;
}
else
return 29;
}
else
{
return 28;
}
}
if (month <= 2)
{
month += 12;
year--;
}
int k = year % 100; int j = year / 100; int day = (1 + (13 * (month
+ 1)) / 5 + k + k / 4 + j / 4 + 5 * j) % 7; return (day + 5) % 7;
}
public static void printCalendar(int month, int year)
{
String[] monthNames = {
{
System.out.print(day + " ");
System.out.println();
int currentDay = 1;
for (int i = 0; i < startDay; i++)
{
System.out.print(" ");
}
for (int i = startDay; i < 7; i++)
{
System.out.printf("%3d ", currentDay++);
System.out.println(); while
{
for (int i = 0; i < 7; i++)
{
if (currentDay <= daysInMonth)
else
{
System.out.print(" ");
}
System.out.println();
}
public static void main(String[] args)
{
System.out.println("Invalid month! Please enter a value between 1 and 12.");
return;
printCalendar(month, year);
scanner.close();
Output :-
Program - 8
Aim:- Write a Java program that generates different number patterns like pyramid patterns
using nested loops and methods for pattern printing. Code:- import java.util.Scanner; public
class NumberPyramidPatterns
{
public static void printRightAlignedPyramid(int height)
{
System.out.print(" ");
}
for (int j = 1; j <= i; j++)
System.out.println();
}
}
{
for (int i = 1; i<= height; i++)
}
System.out.println();
}
}
{
for (int i = height; i>= 1; i--)
{
for (int j = 1; j <= i; j++)
System.out.println();
}
}
{
for (int i = 1; i<= height; i++)
System.out.print(" ");
}
for (int j = 1; j <= i; j++)
}
System.out.println();
}
}
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the height of the pyramid: "); int
height = scanner.nextInt();
}
Output :-
Program - 9
Aim:- Create a Java program to manage an employee payroll system with features for adding
employees, calculating salaries based on hours worked or monthly salary, and generating pay
slips using classes, inheritance, and polymorphism. Code:- import java.util.ArrayList; import
java.util.List; import java.util.Scanner;
// Base class for Employee abstract class Employee {
this.id = id;
}
// Abstract method to calculate salary
System.out.println("--------------------------");
}
}
@Override public double
calculateSalary() {
return hourlyRate * hoursWorked;
}
}
// Class for Salaried Employee class
SalariedEmployee extends Employee {
private double monthlySalary;
public SalariedEmployee(String name, int id, double monthlySalary) { super(name, id); this.monthlySalary =
monthlySalary;
}
}
public void addEmployee(Employee employee) { employees.add(employee);
}
public static void main(String[] args) {
System.out.println("4. Exit");
case 1:
String hourlyName =
scanner.next();
System.out.print("Enter ID: "); int
hourlyId = scanner.nextInt();
System.out.print("Enter hourly rate: ");
case 2:
break;
case 3:
payrollSystem.generatePaySlips();
break;
case 4:
running = false;
break;
default:
System.out.println("Invalid option. Please try again.");
}
scanner.close();
}
Output:-
Program - 10
Aim:- Implement Java programs to compare the performance of different sorting algorithms
(like quicksort, mergesort, and heapsort) on large arrays of integers, measuring and analyzing
time complexity. Code:- import java.util.Random; public class SortingComparison
{
{
if (low < high)
{
int pivotIndex = partition(arr, low, high);
quicksort(arr, low, pivotIndex - 1);
quicksort(arr, pivotIndex + 1, high);
}
}
{
int pivot = arr[high];
int i = low - 1;
{
if (arr[j] < pivot)
swap(arr, i + 1, high);
return i + 1;
}
{
int temp = arr[i]; arr[i] = arr[j];
arr[j] = temp;
}
}
private static void merge(int[] arr, int[] left, int[] right)
int i = 0, j = 0, k = 0;
while (i<left.length&& j <right.length)
arr[k++] = left[i++];
}
else
arr[k++] = right[j++];
}
}
while (i<left.length)
arr[k++] = left[i++];
}
while (j <right.length)
{
arr[k++] = right[j++];
}
n / 2 - 1; i>= 0; i--)
{
heapify(arr, n, i);
swap(arr, 0, i);
heapify(arr, i, 0);
}
}
{
int largest = i; int left = 2 * i + 1; int
right = 2 * i + 2; if (left < n
&&arr[left] >arr[largest])
{
largest = left;
}
largest = right;
}
if (largest != i)
{
swap(arr, i, largest);
heapify(arr, n, largest);
}
}
public static int[] generateRandomArray(int size)
arr[i] = random.nextInt(100000);
}
return arr;
}
public static long measureTime(Runnable sortingAlgorithm)
Output:-
Program -11
Aim:- Develop a Java program that recursively searches a directory for files matching a
given pattern and displays the file paths using recursion and file handling classes. Code :-
import java.io.File; import java.util.Scanner; import java.util.regex.Pattern; public class
DirectorySearch
{
public static void searchFiles(File directory, Pattern pattern)
files)
if (file.isDirectory())
{
searchFiles(file, pattern);
}
else
if (pattern.matcher(file.getName()).matches())
{
System.out.println(file.getAbsolutePath());
}
}
}
}
searchFiles(directory, pattern);
}
else
{
System.out.println("Invalid directory path.");
scanner.close();
}
Output :-
Program :- 12
Aim:- Write a Java program to perform arithmetic operations (addition, subtraction,
multiplication, division) on large numbers using BigInteger class and exception handling
for division by zero. Code:- import java.math.BigInteger; import java.util.Scanner; public class
BigIntegerArithmetic
{
{
Scanner scanner = new Scanner(System.in);
try
{
System.out.println("Division: " + divide(num1, num2));
catch (ArithmeticException e)
{
System.out.println("Error: Division by zero is not allowed.");
}
scanner.close();
}
return a.add(b);
}
{
return a.subtract(b);
}
return a.multiply(b);
}
{
if(b.equals(BigInteger.ZERO)){ throw new
ArithmeticException("Division by zero");
return a.divide(b);
}
}
Output :-
Program - 13
Aim:- Implement a Java program to solve the Tower of Hanoi problem for N disks using
recursion, demonstrating the steps and movements required. Code:- public class
TowerOfHanoi
{
public static void solveTowerOfHanoi(int n, char source, char target, char auxiliary)
if (n == 1)
{
System.out.println("Move disk 1 from rod " + source + " to rod " + target);
return;
}
solveTowerOfHanoi(n - 1, source, auxiliary, target);
System.out.println("Move disk " + n + " from rod " + source + " to rod " + target);
}
public static void main(String[] args)
int numberOfDisks = 3;
System.out.println("Steps to solve Tower of Hanoi for " + numberOfDisks + " disks:");
solveTowerOfHanoi(numberOfDisks, 'A', 'C', 'B');
}
}
Output:-
Program - 14
Aim:- Write a Java program to find the largest and smallest elements in an array.
Code:- import java.util.Scanner; public class LargestAndSmallestInArray
{
public static void main(String[] args)
{
array[i] = scanner.nextInt();
{
if (array[i] > largest)
{
largest = array[i];
}
if (array[i] < smallest)
smallest = array[i];
}
}
System.out.println("Largest element: " + largest);
scanner.close();
Output:-
Program – 15
Aim :- Implement a Java program to sort an array of integers using bubble sort.
Code:- import java.util.Scanner; public class BubbleSort
{
public static void bubbleSort(int[] array)
int n = array.length;
boolean swapped;
{
swapped = false;
for (int j = 0; j < n - 1 - i; j++)
{
if (array[j] >array[j + 1])
}
if (!swapped)
break;
}
}
public static void main(String[] args)
new int[size];
System.out.println("Enter " + size + " elements:");
array[i] = scanner.nextInt();
}
bubbleSort(array);
scanner.close();
}
}
Output:-
Program – 16
Aim:- Create a Java program to find the frequency of each element in an array.
Code:- import java.util.HashMap; import
java.util.Scanner; public class
ElementFrequency
{
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the array:
"); int size = scanner.nextInt(); int[] array =
new int[size];
System.out.println("Enter " + size + " elements:");
for (int i = 0; i< size; i++)
array[i] = scanner.nextInt();
}
}
System.out.println("Element frequencies:"); for
scanner.close();
}}
Output:-
Program -17
Aim : - Develop a Java program to reverse an array without using an additional array.
Code:- import java.util.Scanner; public class ReverseArray
{
new int[size];
System.out.println("Enter " + size + " elements:");
for (int i = 0; i< size; i++)
{
array[i] = scanner.nextInt();
reverseArray(array);
System.out.println("Reversed array:");
for (int num : array)
{
scanner.close();
}
{
int start = 0; int end =
array.length - 1; while
array[start] =
array[end]; array[end] =
}
Output :-
Program – 18
Aim :- Write a Java program to merge two sorted arrays into a single sorted
array. Code:- import java.util.Scanner; public class MergeSortedArrays
{
public static void main(String[] args)
array1[i] = scanner.nextInt();
}
array2[i] = scanner.nextInt();
}
scanner.close();
}
public static int[] mergeArrays(int[] array1, int[] array2)
int i = 0, j = 0, k = 0;
else
{
merged[k++] = array2[j++];
}
}
{
merged[k++] = array1[i++];
merged[k++] = array2[j++];
}
return merged;
Output:-
Program - 19
Aim :- Define a Java class representing a Student with private instance variables and public
getter and setter methods. Code :- public class Student
{
{
return name;
}
public int getStudentId()
return studentId;
}
public void setStudentId(int studentId)
{
this.studentId = studentId;
return age;
}
{
if (age >= 0)
this.age = age;
}
else
{
System.out.println("Age cannot be negative.");
}
public void displayInfo()
}
}
{
Student student = new Student("Alice", 101,
20); student.displayInfo();
student.setName("Alice Johnson");
student.setAge(21);
}
Output:-
Program – 20
Aim :- Create a Java program to demonstrate constructor overloading in a class.
Code :- class Book
{
this.author = author;
this.price = 0.0;
}
{
this.title = title;
this.author = author;
this.price = price;
}
public void displayInfo()
}
}
{
public static void main(String[] args)
{
Book book1 = new Book("The Great Gatsby");
Output:-
Program - 21
Aim :- Implement a Java program to calculate the area and perimeter of a rectangle using a class
and object. Code:- import java.util.Scanner; class Rectangle
{
private double length; private double width;
public Rectangle(double length, double width)
{
{
return 2 * (length + width);
}
public class Main
scanner.close();
}
}
Output:-
Program :- 22
Aim:- Develop a Java program to implement inheritance by creating a base class Animal and
derived classes like Dog and Cat.
class Animal
{
this.name = name;
}
{
System.out.println(name + " makes a sound.");
}
}
class Dog extends Animal
{
public Dog(String name)
super(name);
}
}
public void fetch()
{
System.out.println(name + " is fetching the ball.");
}
}
{
super(name);
}
public void scratch()
dog.makeSound();
barks. dog.fetch();
cat.makeSound();
cat.scratch();
}
Output :-
Program :- 23
Aim :- Write a Java program to demonstrate method overriding by implementing a base class
Shape and derived classes like Circle and Rectangle. Code:- class Shape
{
{
return 0;
}
public void display()
{
System.out.println("This is a shape.");
}
Shape
{
{
this.radius = radius;
}
}
@Override public void display() {
System.out.println("This is a Circle.");
}
extends Shape
{
{
return length * width;
@Override
public void display()
{
System.out.println("This is a Rectangle.");
}
Output:-