Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
55 views

practical 2025 java mca

Uploaded by

arthurboyhoo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views

practical 2025 java mca

Uploaded by

arthurboyhoo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

Program – 1

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 (celsius * 9/5) + 32;


}

public static double fahrenheitToCelsius(double fahrenheit)

{
return (fahrenheit - 32) * 5/9;

}
public static double getValidTemperatureInput(Scanner scanner)

while (!scanner.hasNextDouble())
{

System.out.println("Invalid input. Please enter a valid number:"); scanner.next();


}

return scanner.nextDouble();

}
public static void main(String[] args)

Scanner scanner = new


Scanner(System.in); booleankeepRunning
= true; while (keepRunning)
{
System.out.println("Temperature Converter");
System.out.println("1. Celsius to Fahrenheit");
System.out.println("2. Fahrenheit to Celsius");
System.out.println("3. Exit");

System.out.print("Select an option (1, 2, or 3): ");


int choice = scanner.nextInt(); switch (choice)
{

case 1:

System.out.print("Enter temperature in Celsius: "); double


celsius = getValidTemperatureInput(scanner); double
fahrenheitResult = celsiusToFahrenheit(celsius);
System.out.println(celsius + " °C = " + fahrenheitResult + " °F");
break; case 2:

System.out.print("Enter temperature in Fahrenheit: ");


double fahrenheit = getValidTemperatureInput(scanner);
double celsiusResult = fahrenheitToCelsius(fahrenheit);
System.out.println(fahrenheit + " °F = " + celsiusResult + " °C");
break; case 3:
keepRunning = false;
System.out.println("Exiting the
program."); break; default:

System.out.println("Invalid choice. Please select 1, 2, or 3.");


break;

}
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
{

public static int[][] addMatrices(int[][] matrix1, int[][] matrix2)

{
int rows = matrix1.length; int cols

= matrix1[0].length; int[][] result


= new int[rows][cols]; for (int i =
0; i< rows; i++)
{
for (int j = 0; j < cols; j++)

{
result[i][j] = matrix1[i][j] + matrix2[i][j];

}
return result;

}
public static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2)

int rows1 = matrix1.length; int cols1


= matrix1[0].length; int cols2 =
matrix2[0].length; int[][] result =
new int[rows1][cols2]; for (int i = 0;
i< rows1; i++)

{
for (int j = 0; j < cols2; j++)

result[i][j] = 0;
for (int k = 0; k < cols1; k++)

result[i][j] += matrix1[i][k] * matrix2[k][j];


}

}
return result;

public static int[][] transposeMatrix(int[][] matrix)


{

int rows = matrix.length; int cols =


matrix[0].length; int[][] result =
new int[cols][rows]; for (int i = 0;
i< rows; i++)
{

for (int j = 0; j < cols; j++)

{
result[j][i] = matrix[i][j];

}
}

return result;

}
public static int[][] getMatrixInput(Scanner scanner, int rows, int cols)

int[][] matrix = new int[rows][cols];

System.out.println("Enter matrix elements:");

for (int i = 0; i< rows; i++)

for (int j = 0; j < cols; j++)

matrix[i][j] = scanner.nextInt();

}
}

return matrix;
}
public static void printMatrix(int[][] matrix)

for (int[] row : matrix)


{

for (int element : row)

{
System.out.print(element + " ");

}
System.out.println();

}
public static void main(String[] args)

{
Scanner scanner = new Scanner(System.in);

System.out.print("Enter number of rows for the matrices: ");

int rows = scanner.nextInt();

System.out.print("Enter number of columns for the matrices:


"); int cols = scanner.nextInt(); System.out.println("Matrix 1:");
int[][] matrix1 = getMatrixInput(scanner, rows, cols);
System.out.println("Matrix 2:"); int[][] matrix2 =
getMatrixInput(scanner, rows, cols); System.out.println("Matrix
Addition:"); int[][] additionResult = addMatrices(matrix1,
matrix2); printMatrix(additionResult);
System.out.println("Matrix Multiplication:"); if
(matrix1[0].length == matrix2.length)
{
int[][] multiplicationResult = multiplyMatrices(matrix1, matrix2);
printMatrix(multiplicationResult);
}

else
{

System.out.println("Matrix multiplication is not possible with the given dimensions.");

}
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
{

public static String decimalToBinary(int num)

{
StringBuilder binary = new StringBuilder();

while (num> 0)

binary.insert(0, num % 2);


num = num / 2;
}

return binary.length() > 0 ? binary.toString() : "0";


}

public static String decimalToOctal(int num)

{
StringBuilder octal = new StringBuilder();
while (num> 0) { octal.insert(0, num % 8);
num = num / 8;
}

return octal.length() > 0 ? octal.toString() : "0";


}

public static String decimalToHexadecimal(int num)

{
StringBuilder hex = new StringBuilder(); char[]
hexDigits = "0123456789ABCDEF".toCharArray();
while (num> 0)

{
hex.insert(0, hexDigits[num % 16]);
num = num / 16;
}

return hex.length() > 0 ? hex.toString() : "0";


}

public static void main(String[] args)

{
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));

System.out.println("Hexadecimal: " + decimalToHexadecimal(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;

public double getBalance()


{

return balance;

}
public void deposit(double amount)

if (amount > 0)
{

balance += amount;

System.out.println("Deposit successful! Current balance: $" + balance);


}

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
{

System.out.println("Insufficient balance or invalid amount.");

}
}

public void balanceInquiry()


{

System.out.println("Account Balance: $" + balance);

}
}

public class BankSystem

{
public static void main(String[] args)

Scanner scanner = new Scanner(System.in);


System.out.print("Enter account number: ");

String accountNumber = scanner.nextLine();

System.out.print("Enter initial balance: "); double


initialBalance = scanner.nextDouble();
BankAccount account = new BankAccount(accountNumber, initialBalance);
boolean exit = false; while (!exit)

System.out.println("\nBank Account Management System");


System.out.println("1. Deposit");

System.out.println("2. Withdraw");

System.out.println("3. Balance Inquiry");


System.out.println("4. Exit");

System.out.print("Choose an option:
"); int choice = scanner.nextInt();
switch (choice)

{
case 1:

System.out.print("Enter deposit amount: ");

double depositAmount = scanner.nextDouble();


account.deposit(depositAmount);
break;

case 2:

System.out.print("Enter withdrawal amount: ");

double withdrawalAmount = scanner.nextDouble();


account.withdraw(withdrawalAmount);
break; case 3:
account.balanceInquiry()
; break; case 4: exit =
true;
System.out.println("Exiting system.
Goodbye!"); break; default:
System.out.println("Invalid choice. Please try again.");
}

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
{

Map<String, Integer>wordMap = new HashMap<>();


Scanner fileScanner = new Scanner(new File(fileName));

while (fileScanner.hasNext())

String word = fileScanner.next().toLowerCase().replaceAll("[^a-zA-Z]", "");

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)

List<Entry<String, Integer>>sortedList = new ArrayList<>(wordMap.entrySet());


sortedList.sort((entry1, entry2) ->
entry2.getValue().compareTo(entry1.getValue())); System.out.println("Top " + N + "

most frequent words:"); for (int i = 0; i< N &&i<sortedList.size(); i++)


{
Entry<String, Integer> entry = sortedList.get(i);
System.out.println(entry.getKey() + ": " + entry.getValue());

}
public static void main(String[] args)

{
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the file name: ");

String fileName = scanner.nextLine();


System.out.print("Enter the number of top frequent words to display: ");

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)

List<Integer> primes = new ArrayList<>(); int


limit = N * 15;
boolean[] isPrime = new boolean[limit + 1];

for (int i = 2; i<= limit; i++)

{
isPrime[i] = true;

} for (int p = 2; p * p <= limit; p++)

{
if (isPrime[p])

for(int multiple = p * p; multiple <= limit;


multiple+=p)

{
isPrime[multiple] = false; // Mark multiples of p as non-prime

}
}

for (int i = 2; primes.size() < N &&i<= limit; i++)


{

if (isPrime[i])

primes.add(i);

}
}

return primes;

}
public static void main(String[] args)

Scanner scanner = new Scanner(System.in);


System.out.print("Enter the number of prime numbers to generate: ");

int N = scanner.nextInt();

List<Integer> primes = generatePrimes(N);

System.out.println("The first " + N + " prime numbers are:");


for (int prime : primes)

System.out.print(prime + " ");

}
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
{

public static int getDaysInMonth(int month, int year)


{
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)

{
return 31;

else if (month == 4 || month == 6 || month == 9 || month == 11)


{

return 30;

}
else

if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))


{

return 29;

}
else

{
return 28;
}
}

public static int getStartingDay(int month, int year)

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 = {

"January", "February", "March", "April", "May", "June",

"July", "August", "September", "October", "November", "December"


};

String[] weekDays = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};


int daysInMonth = getDaysInMonth(month, year); int startDay =
getStartingDay(month, year);

System.out.println(" " + monthNames[month - 1] + " " + year);


for (String day : weekDays)

{
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

(currentDay <= daysInMonth)

{
for (int i = 0; i < 7; i++)

{
if (currentDay <= daysInMonth)

System.out.printf("%3d ", currentDay++);


}

else

{
System.out.print(" ");

}
System.out.println();

}
public static void main(String[] args)

Scanner scanner = new Scanner(System.in);


System.out.print("Enter the month (1-12): ");
int month = scanner.nextInt();
System.out.print("Enter the year: "); int year
= scanner.nextInt();

if (month < 1 || month > 12)

{
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)

for (int i = 1; i<= height; i++)


{

for (int j = height; j >i; j--)

{
System.out.print(" ");

}
for (int j = 1; j <= i; j++)

System.out.print(j + " ");


}

System.out.println();

}
}

public static void printLeftAlignedPyramid(int height)

{
for (int i = 1; i<= height; i++)

for (int j = 1; j <= i; j++)


{

System.out.print(j + " ");

}
System.out.println();

}
}

public static void printInvertedPyramid(int height)

{
for (int i = height; i>= 1; i--)

{
for (int j = 1; j <= i; j++)

System.out.print(j + " ");


}

System.out.println();

}
}

public static void printFullPyramid(int height)

{
for (int i = 1; i<= height; i++)

for (int j = height; j >i; j--)


{

System.out.print(" ");

}
for (int j = 1; j <= i; j++)

System.out.print(j + " ");


}

for (int j = i - 1; j >= 1; j--)


{

System.out.print(j + " ");

}
System.out.println();

}
}

public static void main(String[] args)

{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the height of the pyramid: "); int
height = scanner.nextInt();

System.out.println("\nRight-Aligned Pyramid:"); printRightAlignedPyramid(height);


System.out.println("\nLeft-Aligned Pyramid:"); printLeftAlignedPyramid(height);

System.out.println("\nInverted Pyramid:"); printInvertedPyramid(height);


System.out.println("\nFull Pyramid:"); printFullPyramid(height);
scanner.close();
}

}
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 {

protected String name; protected int id; public

Employee(String name, int id) { this.name = name;

this.id = id;

}
// Abstract method to calculate salary

public abstract double calculateSalary();


// Method to generate pay slip public
void generatePaySlip() {

System.out.println("Pay Slip for: " + name);


System.out.println("Employee ID: " + id);

System.out.println("Salary: $" + calculateSalary());

System.out.println("--------------------------");
}

// Class for Hourly Employee


class HourlyEmployee extends Employee { private
double hourlyRate; private int hoursWorked;
public HourlyEmployee(String name, int id, double hourlyRate, int hoursWorked)

{ super(name, id); this.hourlyRate = hourlyRate; this.hoursWorked = hoursWorked;

}
@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;
}

@Override public double calculateSalary() { return


monthlySalary;
}
}

// Main class to manage the payroll system public class


PayrollSystem { private List<Employee> employees; public

PayrollSystem() { employees = new ArrayList<>();

}
public void addEmployee(Employee employee) { employees.add(employee);

public void generatePaySlips() {


for (Employee employee : employees) { employee.generatePaySlip();

}
public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


PayrollSystempayrollSystem = new
PayrollSystem(); boolean running = true; while
(running) {
System.out.println("1. Add Hourly Employee");
System.out.println("2. Add Salaried Employee"); System.out.println("3. Generate Pay Slips");

System.out.println("4. Exit");

System.out.print("Choose an option: ");


int choice = scanner.nextInt();
switch (choice) {

case 1:

System.out.print("Enter name: ");

String hourlyName =
scanner.next();
System.out.print("Enter ID: "); int
hourlyId = scanner.nextInt();
System.out.print("Enter hourly rate: ");

double hourlyRate = scanner.nextDouble(); System.out.print("Enter hours worked: "); int


hoursWorked = scanner.nextInt(); payrollSystem.addEmployee(new HourlyEmployee(hourlyName,
hourlyId, hourlyRate, hoursWorked));
break;

case 2:

System.out.print("Enter name: ");


String salariedName =
scanner.next();
System.out.print("Enter ID: "); int
salariedId = scanner.nextInt();
System.out.print("Enter monthly salary: ");
double monthlySalary = scanner.nextDouble();

payrollSystem.addEmployee(new SalariedEmployee(salariedName, salariedId, monthlySalary));

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
{

public static void quicksort(int[] arr, int low, int high)

{
if (low < high)

{
int pivotIndex = partition(arr, low, high);
quicksort(arr, low, pivotIndex - 1);
quicksort(arr, pivotIndex + 1, high);
}
}

private static int partition(int[] arr, int low, int high)

{
int pivot = arr[high];

int i = low - 1;

for (int j = low; j < high; j++)

{
if (arr[j] < pivot)

i++; swap(arr, i, j);


}

swap(arr, i + 1, high);

return i + 1;
}

private static void swap(int[] arr, int i, int j)

{
int temp = arr[i]; arr[i] = arr[j];
arr[j] = temp;
}

public static void mergesort(int[] arr)


{

if (arr.length< 2) return; int mid =


arr.length / 2; int[] left = new
int[mid]; int[] right = new
int[arr.length - mid];
System.arraycopy(arr, 0, left, 0, mid);

System.arraycopy(arr, mid, right, 0, arr.length - mid); mergesort(left);

mergesort(right); merge(arr, left, right);

}
private static void merge(int[] arr, int[] left, int[] right)

int i = 0, j = 0, k = 0;
while (i<left.length&& j <right.length)

if (left[i] <= right[j])


{

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++];
}

public static void heapsort(int[] arr)


{

int n = arr.length; for (int i =

n / 2 - 1; i>= 0; i--)

{
heapify(arr, n, i);

for (int i = n - 1; i> 0; i--)


{

swap(arr, 0, i);
heapify(arr, i, 0);
}
}

private static void heapify(int[] arr, int n, int i)

{
int largest = i; int left = 2 * i + 1; int
right = 2 * i + 2; if (left < n
&&arr[left] >arr[largest])
{
largest = left;
}

if (right < n &&arr[right] >arr[largest])


{

largest = right;

}
if (largest != i)
{
swap(arr, i, largest);
heapify(arr, n, largest);
}

}
public static int[] generateRandomArray(int size)

Random random = new Random();


int[] arr = new int[size];

for (int i = 0; i< size; i++)

arr[i] = random.nextInt(100000);
}

return arr;

}
public static long measureTime(Runnable sortingAlgorithm)

long startTime = System.nanoTime();


sortingAlgorithm.run(); long endTime =
System.nanoTime(); return (endTime -
startTime) / 1_000_000;
}

public static void main(String[] args)


{

int size = 100000; int[] originalArray = generateRandomArray(size); int[] quicksortArray =


originalArray.clone(); long quicksortTime = measureTime(() -> quicksort(quicksortArray, 0,
quicksortArray.length - 1)); System.out.println("Quicksort time: " + quicksortTime + " ms");
int[] mergesortArray = originalArray.clone(); long mergesortTime = measureTime(() -
>mergesort(mergesortArray)); System.out.println("Mergesort time: " + mergesortTime + "
ms"); int[] heapsortArray = originalArray.clone(); long heapsortTime = measureTime(() ->
heapsort(heapsortArray));
System.out.println("Heapsort time: " + heapsortTime + " ms");

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)

File[] files = directory.listFiles();


if (files != null)

{ for (File file :

files)

if (file.isDirectory())

{
searchFiles(file, pattern);

}
else

if (pattern.matcher(file.getName()).matches())
{

System.out.println(file.getAbsolutePath());
}
}

}
}

public static void main(String[] args)


{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the directory path: ");

String directoryPath = scanner.nextLine();

System.out.print("Enter the file pattern (e.g., *.txt): ");


String filePattern = scanner.nextLine().replace("*", ".*");

Pattern pattern = Pattern.compile(filePattern);


File directory = new File(directoryPath); if
(directory.exists() &&directory.isDirectory())
{

System.out.println("Searching for files matching pattern: " + filePattern);

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
{

public static void main(String[] args)

{
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the first large number: ");

BigInteger num1 = new BigInteger(scanner.nextLine());


System.out.print("Enter the second large number: ");

BigInteger num2 = new BigInteger(scanner.nextLine());

System.out.println("Addition: " + add(num1, num2));


System.out.println("Subtraction: " + subtract(num1, num2));

System.out.println("Multiplication: " + multiply(num1, num2));

try

{
System.out.println("Division: " + divide(num1, num2));

catch (ArithmeticException e)
{
System.out.println("Error: Division by zero is not allowed.");
}

scanner.close();
}

public static BigIntegeradd(BigInteger a, BigInteger b)

return a.add(b);
}

public static BigIntegersubtract(BigInteger a, BigInteger b)

{
return a.subtract(b);
}

public static BigIntegermultiply(BigInteger a, BigInteger b)


{

return a.multiply(b);
}

public static BigIntegerdivide(BigInteger a, BigInteger 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);

solveTowerOfHanoi(n - 1, auxiliary, target, source);

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

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();

int largest = array[0];


int smallest = array[0];

for (int i = 1; i< size; i++)

{
if (array[i] > largest)
{

largest = array[i];

}
if (array[i] < smallest)

smallest = array[i];
}

}
System.out.println("Largest element: " + largest);

System.out.println("Smallest element: " + smallest);

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;

for (int i = 0; i< n - 1; i++)

{
swapped = false;
for (int j = 0; j < n - 1 - i; j++)

{
if (array[j] >array[j + 1])

int temp = array[j];


array[j] = array[j + 1];
array[j + 1] = temp;
swapped = true;
}

}
if (!swapped)

break;
}

}
public static void main(String[] args)

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();

}
bubbleSort(array);

System.out.println("Sorted array:"); for


(int num : array)
{
System.out.print(num + " ");
}

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
{

public static void main(String[] args)

{
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();
}

HashMap<Integer, Integer>frequencyMap = new HashMap<>();

for (int num : array)


{

frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);

}
System.out.println("Element frequencies:"); for

(HashMap.Entry<Integer, Integer>entry :frequencyMap.entrySet())

System.out.println(entry.getKey() + ": " + entry.getValue());


}

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
{

public static void main(String[] args)


{
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();

reverseArray(array);
System.out.println("Reversed array:");
for (int num : array)
{

System.out.print(num + " ");


}

scanner.close();
}

public static void reverseArray(int[] array)

{
int start = 0; int end =

array.length - 1; while

(start < end)

int temp = array[start];

array[start] =
array[end]; array[end] =

temp; start++; 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)

Scanner scanner = new Scanner(System.in);


System.out.print("Enter the size of the first sorted array: ");
int size1 = scanner.nextInt(); int[] array1 = new int[size1];
System.out.println("Enter elements of the first sorted array:");
for (int i = 0; i< size1; i++)

array1[i] = scanner.nextInt();
}

System.out.print("Enter the size of the second sorted array:

"); int size2 = scanner.nextInt(); int[] array2 = new int[size2];

System.out.println("Enter elements of the second sorted array:");


for (int i = 0; i< size2; i++)

array2[i] = scanner.nextInt();
}

int[] mergedArray = mergeArrays(array1, array2);


System.out.println("Merged sorted array:"); for
(int num :mergedArray)
{

System.out.print(num + " ");


}

scanner.close();

}
public static int[] mergeArrays(int[] array1, int[] array2)

int n1 = array1.length; int n2 =


array2.length; int[] merged =
new int[n1 + n2];

int i = 0, j = 0, k = 0;

while (i< n1 && j < n2)


{

if (array1[i] <= array2[j])


{
merged[k++] = array1[i++];
}

else

{
merged[k++] = array2[j++];

}
}

while (i< n1)

{
merged[k++] = array1[i++];

while (j < n2)


{

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
{

private String name; private int studentId; private

int age; public Student(String name, int

studentId, int age)

this.name = name; this.studentId


= studentId; this.age = age;
}

public String getName()

{
return name;

public void setName(String name)


{
this.name = name;

}
public int getStudentId()

return studentId;
}
public void setStudentId(int studentId)

{
this.studentId = studentId;

public int getAge()


{

return age;
}

public void setAge(int age)

{
if (age >= 0)

this.age = age;
}

else

{
System.out.println("Age cannot be negative.");

}
public void displayInfo()

System.out.println("Student Name: " + name);


System.out.println("Student ID: " + studentId);

System.out.println("Age: " + age);

}
}

public class Main


{

public static void main(String[] args)

{
Student student = new Student("Alice", 101,

20); student.displayInfo();
student.setName("Alice Johnson");

student.setAge(21);

System.out.println("\nUpdated Student Information:"); student.displayInfo();


}

}
Output:-

Program – 20
Aim :- Create a Java program to demonstrate constructor overloading in a class.
Code :- class Book
{

private String title;


private String author;
private double price;
public Book(String title)
{
this.title = title;
this.author = "Unknown";
this.price = 0.0;

public Book(String title, String author)


{ this.title =
title;

this.author = author;
this.price = 0.0;
}

public Book(String title, String author, double price)

{
this.title = title;

this.author = author;

this.price = price;

}
public void displayInfo()

System.out.println("Title: " + title);


System.out.println("Author: " + author);

System.out.println("Price: $" + price);

}
}

public class Main

{
public static void main(String[] args)

{
Book book1 = new Book("The Great Gatsby");

Book book2 = new Book("1984", "George Orwell");

Book book3 = new Book("To Kill a Mockingbird", "Harper Lee",


15.99); System.out.println("Book 1:"); book1.displayInfo();
System.out.println();
System.out.println("Book 2:");
book2.displayInfo();
System.out.println();
System.out.println("Book 3:");
book3.displayInfo();
}

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)
{

this.length = length; this.width


= width;
}
public double calculateArea()
{

return length * width;


}

public double calculatePerimeter()

{
return 2 * (length + width);

}
public class Main

public static void main(String[] args)


{

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the length of the rectangle: "); double


length = scanner.nextDouble(); System.out.print("Enter the
width of the rectangle: "); double width =
scanner.nextDouble();
Rectangle rectangle = new Rectangle(length, width);
double area = rectangle.calculateArea();
double perimeter = rectangle.calculatePerimeter();
System.out.println("Area of the rectangle: " + area);

System.out.println("Perimeter of the rectangle: " + perimeter);

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
{

protected String name;

public Animal(String name)

this.name = name;
}

public void makeSound()

{
System.out.println(name + " makes a sound.");

}
}
class Dog extends Animal

{
public Dog(String name)

super(name);
}

@Override public void makeSound()


{

System.out.println(name + " barks.");

}
public void fetch()
{
System.out.println(name + " is fetching the ball.");

}
}

class Cat extends Animal


{

public Cat(String name)

{
super(name);

@Override public void makeSound()


{

System.out.println(name + " meows.");

}
public void scratch()

System.out.println(name + " is scratching the post.");


}

public class Main


{

public static void main(String[] args)


{

Dog dog = new Dog("Buddy"); Cat

cat = new Cat("Whiskers");

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
{

public double calculateArea()

{
return 0;

}
public void display()
{

System.out.println("This is a shape.");
}

Shape
{

private double radius;

public Circle(double radius)

{
this.radius = radius;
}

@Override public double calculateArea()


{

return Math.PI * radius * radius;

}
@Override public void display() {

System.out.println("This is a Circle.");
}

extends Shape
{

private double length; private double width;


public Rectangle(double length, double width)
{

this.length = length; this.width


= width;
}

@Override public double calculateArea()

{
return length * width;

@Override
public void display()

{
System.out.println("This is a Rectangle.");
}

public class Main


{

public static void main(String[] args)


{
Shape circle = new Circle(5); Shape
rectangle = new Rectangle(4, 6);
circle.display();

System.out.println("Area: " + circle.calculateArea());


rectangle.display();

System.out.println("Area: " + rectangle.calculateArea());

Output:-

You might also like