Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

EXPERIMENT-1
AIM: a) Write a program to accept two integer numbers from the standard input
and perform the following arithmetic operations: addition, subtraction and
multiplication.
PROGRAM
import java.util.Scanner;
public class ArithmaticOperations
{
public static void main(String[] args)
{

Scanner scanner = new Scanner(System.in);

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


int num1 = scanner.nextInt();

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

int num2 = scanner.nextInt();

int sum = num1 + num2;


System.out.println("Sum: " + sum);

int difference = num1 - num2;


System.out.println("Difference: " + difference);

int product = num1 * num2;


System.out.println("Product: " + product);

}
}

EXPECTED OUTPUT:
Enter the first integer: 3
Enter the second integer: -4
Sum: -1
Difference: 7
Product: -12

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 1


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

AIM: b) Write a program to calculate simple and compound interest.


PROGRAM
import java.util.Scanner;

public class SimpleInterest {


public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the principal amount: ");
double principal = scanner.nextDouble();
System.out.print("Enter the annual interest rate (as a decimal):");
double rate = scanner.nextDouble();
System.out.print("Enter the time (in years): ");
double time = scanner.nextDouble();

double simpleInterest = calcSmplInt(principal, rate, time);


System.out.println("Simple Interest: " + simpleInterest);

System.out.print("Enter the number of times interest is compounded per


year: ");
int n = scanner.nextInt();
double compoundInterest = calccompInt (principal, rate, time, n);
System.out.println("Compound Interest: " + compoundInterest);

}
public static double calcSmplInt(double principal, double rate, double
time)
{
return principal * rate * time;
}
public static double calccompInt(double principal, double rate, double
time, int n)
{
double compoundInterest = principal * Math.pow(1 + rate / n, n *
time) - principal;
return compoundInterest;
}
}
EXPECTED OUTPUT:
Enter the principal amount: 10000
Enter the annual interest rate (as a decimal):13
Enter the time (in years): 10
Simple Interest: 1300000.0
Enter the number of times interest is compounded per year: 5
Compound Interest: 6.533186235000717E31

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 2


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

AIM: c) Write a Program to Swap Two Numbers with and without temporary
variables.
PROGRAM
public class Swap
{
public static void main(String[] args)
{
int num1 = 5;
int num2 = 10;
System.out.println("Before swapping (with temporary variable):");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
int temp = num1;
num1 = num2;
num2 = temp;
System.out.println("\nAfter swapping (with temporary variable):");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
num1 = 15;
num2 = 20;
System.out.println("\nBefore swapping (without temporary variable):");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
System.out.println("\nAfter swapping (without temporary variable):");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
}
}
EXPECTED OUTPUT:
Before swapping (with temporary variable):
num1 = 5
num2 = 10
After swapping (with temporary variable):
num1 = 10
num2 = 5
Before swapping (without temporary variable):
num1 = 15
num2 = 20
After swapping (without temporary variable):
num1 = 20
num2 = 15

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 3


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

EXPERIMENT-2
AIM: a) Write a program that prints all real solutions to the quadratic equation
ax2+bx+c=0. Read in a, b, c and use the quadratic formula.
PROGRAM
import java.util.Scanner;
public class QuadraticEquation
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter coefficient a: ");
double a = scanner.nextDouble();
System.out.print("Enter coefficient b: ");
double b = scanner.nextDouble();
System.out.print("Enter coefficient c: ");
double c = scanner.nextDouble();
// Calculate the discriminant (b^2 - 4ac)
double discriminant = b * b - 4 * a * c;
// Check if the discriminant is non-negative (real solutions)
if (discriminant >= 0) {
// Calculate the real solutions using the quadratic formula
double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
// Print the real solutions
System.out.println("Real solutions:");
System.out.println("Root 1: " + root1);
System.out.println("Root 2: " + root2);
}
else {
// If the discriminant is negative, there are no real solutions
System.out.println("No real solutions. Discriminant is
negative.");
}

}
}

EXPECTED OUTPUT:

Case 1: Case 2:
Enter coefficient a: 3 Enter coefficient a: 1
Enter coefficient b: 7 Enter coefficient b: 2
Enter coefficient c: 2 Enter coefficient c: 3
Real solutions: No real solutions. Discriminant is negative.
Root 1: -0.3333333333333333
Root 2: -2.0

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 4


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

AIM: b) Write a Program to display All Prime Numbers from 1 to N.


PROGRAM
import java.util.Scanner;
public class PrimeNumber {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter the value of N: ");
int N = scanner.nextInt();
System.out.println("Prime numbers from 1 to " + N + ":");

// Iterate through numbers from 2 to N


for (int i = 2; i <= N; i++) {
if (isPrime(i))
{
System.out.print(i + " ");
}
}

// Function to check if a number is prime


private static boolean isPrime(int num) {
if (num <= 1) {
return false;
}

// Check for divisibility from 2 to the square root of num


for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}

return true;
}
}

EXPECTED OUTPUT:
Enter the value of N: 20
Prime numbers from 1 to 20:
2 3 5 7 11 13 17 19

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 5


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

AIM: c) Write a Program for factorial of a number.


PROGRAM
import java.util.Scanner;
public class FactorialOfNumber {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
long factorial = calculateFactorial(number);
System.out.println("Factorial of " + number + " is: " + factorial);
}

private static long calculateFactorial(int n) {


if (n < 0) {
System.out.println("Factorial is not defined for negative
numbers.");
return -1; // Return -1 to indicate an error
}

if (n == 0 || n == 1) {
return 1; // Factorial of 0 and 1 is 1
}

// Calculate factorial using a loop


long result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}

return result;
}
}

EXPECTED OUTPUT:
Enter a number: 3
Factorial of 3 is: 6

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 6


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

EXPERIMENT-3
AIM: a) Write a program to search a given element in the array using linear and
binary search techniques
PROGRAM
import java.util.Scanner;
import java.util.Arrays;
public class ArraySearch {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] array = { 2, 5, 8, 10, 7, 12, 38, 45, 56, 72 };
System.out.println("Array: " + Arrays.toString(array));

// Read the element to be searched


System.out.print("Enter the element to search: ");
int target = scanner.nextInt();

// Perform linear search


int linearIndex = linearSearch(array, target);
if (linearIndex != -1) {
System.out.println("Linear Search: Element found at index " +
linearIndex);
}
else {
System.out.println("Linear Search: Element not found");
}

// Perform binary search (Note: Binary search requires a sorted array)


Arrays.sort(array);
int binaryIndex = binarySearch(array, target);
if (binaryIndex != -1) {
System.out.println("Binary Search: Element found at index " +
binaryIndex);
} else {
System.out.println("Binary Search: Element not found");
}

scanner.close();
}

// Linear search function


private static int linearSearch(int[] array, int target) {
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
return i; // Element found, return its index
}
}

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 7


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

return -1; // Element not found


}

// Binary search function


private static int binarySearch(int[] array, int target) {
int low = 0;
int high = array.length - 1;

while (low <= high) {


int mid = (low + high) / 2;

if (array[mid] == target) {
return mid; // Element found, return its index
} else if (array[mid] < target) {
low = mid + 1; // Search the right half
} else {
high = mid - 1; // Search the left half
}
}

return -1; // Element not found


}
}

EXPECTED OUTPUT:
Array: [2, 5, 8, 10, 7, 12, 38, 45, 56, 72]
Enter the element to search: 45
Linear Search: Element found at index 7
Binary Search: Element found at index 7

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 8


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

AIM: b) Write a program to sort the elements in ascending and descending order
using bubble sort
PROGRAM
import java.util.Scanner;
import java.util.Arrays;
public class BubbleSort {

public static void main(String[] args) {


int[] array = {64, 25, 12, 22, 11};

// Display the original array


System.out.println("Original Array: " + Arrays.toString(array));

// Perform ascending bubble sort


array=bubbleSortAscending(array.clone());
System.out.println("Ascending Order: " + Arrays.toString(array));

// Perform descending bubble sort


array=bubbleSortDescending(array.clone());
System.out.println("Descending Order: " + Arrays.toString(array));
}

// Bubble sort for ascending order


private static int[] bubbleSortAscending(int[] arr) {
int n = arr.length;
boolean swapped;

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


swapped = false;

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


if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j + 1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;

swapped = true;
}
}

// If no two elements were swapped in inner loop, the array is


already sorted
if (!swapped) {
break;
}
}

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 9


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

return arr;
}

// Bubble sort for descending order


private static int[] bubbleSortDescending(int[] arr) {
int n = arr.length;
boolean swapped;
for (int i = 0; i < n - 1; i++) {
swapped = false;
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] < arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}

// If no two elements were swapped in inner loop, the array is


already sorted
if (!swapped) {
break;
}
}
return arr;
}
}

EXPECTED OUTPUT:
Original Array: [64, 25, 12, 22, 11]
Ascending Order: [11,12,22,25,64]
Descending Order: [64, 25,22,12,11]

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 10


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

AIM: c) Write a program to find the largest and smallest element in an array
PROGRAM
import java.util.Scanner;
import java.util.Arrays;
public class MaxMin {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Read the size of the array


System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();

// Read the elements of the array


int[] array = new int[size];
System.out.println("Enter the elements of the array:");

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


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

// Find the largest and smallest elements


int largest = findLargestElement(array);
int smallest = findSmallestElement(array);

// Display the results


System.out.println("Array: " + java.util.Arrays.toString(array));
System.out.println("Largest Element: " + largest);
System.out.println("Smallest Element: " + smallest);

scanner.close();
}

// Function to find the largest element in an array


private static int findLargestElement(int[] array) {
int largest = array[0];

for (int i = 1; i < array.length; i++) {


if (array[i] > largest) {
largest = array[i];
}
}

return largest;
}

// Function to find the smallest element in an array

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 11


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

private static int findSmallestElement(int[] array) {


int smallest = array[0];

for (int i = 1; i < array.length; i++) {


if (array[i] < smallest) {
smallest = array[i];
}
}

return smallest;
}
}

EXPECTED OUTPUT:
Enter the size of the array: 7
Enter the elements of the array:
1 0 8 -1 3 4 8
Array: [1, 0, 8, -1, 3, 4, 8]
Largest Element: 8
Smallest Element: -1

EXPERIMENT-4
AIM: Given two matrices A and B, write a program to: a) Add the matrices
PROGRAM
import java.util.Scanner;
import java.util.Arrays;
public class AddMtrix {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

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


int rowsA = scanner.nextInt();
int rowsB = scanner.nextInt();
System.out.print("Enter the number of columns for matrices A and B:");
int columnsA = scanner.nextInt();
int columnsB = scanner.nextInt();
if((rowsA==rowsB) && (columnsA==columnsB))
{
int[][] matrixA = new int[rowsA][columnsA];
int[][] matrixB = new int[rowsB][columnsB];

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 12


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

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


readMatrixElements(matrixA, scanner);

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


readMatrixElements(matrixB, scanner);

int[][] sumMatrix = addMatrices(matrixA, matrixB);

System.out.println("\nMatrix A:");
printMatrix(matrixA);

System.out.println("\nMatrix B:");
printMatrix(matrixB);

System.out.println("\nMatrix Sum (A + B):");


printMatrix(sumMatrix);

scanner.close();
}
else
{
System.out.println("Addition is not possible");
}
}

// Function to read elements of a matrix


private static void readMatrixElements(int[][] matrix, Scanner scanner) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
matrix[i][j] = scanner.nextInt();
}
}
}

// Function to add two matrices


private static int[][] addMatrices(int[][] matrixA, int[][] matrixB) {
int rows = matrixA.length;
int columns = matrixA[0].length;
int[][] sumMatrix = new int[rows][columns];

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


for (int j = 0; j < columns; j++) {
sumMatrix[i][j] = matrixA[i][j] + matrixB[i][j];
}
}

return sumMatrix;
}

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 13


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

// Function to print a matrix


private static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + "\t");
}
System.out.println();
}
}
}

EXPECTED OUTPUT:
Enter the number of rows for matrices A and B: 3 3
Enter the number of columns for matrices A and B: 2 2
Enter elements for matrix A:
123456
Enter elements for matrix B:
123456

Matrix A:
1 2
3 4
5 6

Matrix B:
1 2
3 4
5 6

Matrix Sum (A + B):


2 4
6 8
10 12

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 14


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

AIM: b) Multiply the matrices


PROGRAM
import java.util.Scanner;
import java.util.Arrays;
public class Matrixmul {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

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


int rowsA = scanner.nextInt();
System.out.print("Enter the number of columns for matrix A: ");
int columnsA = scanner.nextInt();

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


int rowsB = scanner.nextInt();
System.out.print("Enter the number of columns for matrix B: ");
int columnsB = scanner.nextInt();

if (columnsA == rowsB) {
int[][] matrixA = new int[rowsA][columnsA];
int[][] matrixB = new int[rowsB][columnsB];

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


readMatrixElements(matrixA, scanner);

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


readMatrixElements(matrixB, scanner);

int[][] productMatrix = multiplyMatrices(matrixA, matrixB);

System.out.println("\nMatrix A:");
printMatrix(matrixA);

System.out.println("\nMatrix B:");
printMatrix(matrixB);

System.out.println("\nMatrix Product (A * B):");


printMatrix(productMatrix);

scanner.close();
}

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 15


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

else {
System.out.println("Multiplication is not possible. The number of
columns in matrix A must be equal to the number of rows in matrix B.");
}
}

// Function to read elements of a matrix


private static void readMatrixElements(int[][] matrix, Scanner scanner) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
matrix[i][j] = scanner.nextInt();
}
}
}

// Function to multiply two matrices


private static int[][] multiplyMatrices(int[][] matrixA, int[][] matrixB)
{
int rowsA = matrixA.length;
int columnsA = matrixA[0].length;
int columnsB = matrixB[0].length;
int[][] productMatrix = new int[rowsA][columnsB];

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


for (int j = 0; j < columnsB; j++) {
for (int k = 0; k < columnsA; k++) {
productMatrix[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}

return productMatrix;
}

// Function to print a matrix


private static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + "\t");
}
System.out.println();
}
}
}
EXPECTED OUTPUT:
CASE 1:
Enter the number of rows for matrix A: 2
Enter the number of columns for matrix A: 3

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 16


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

Enter the number of rows for matrix B: 3


Enter the number of columns for matrix B: 1
Enter elements for matrix A:
123456
Enter elements for matrix B:
123

Matrix A:
1 2 3
4 5 6

Matrix B:
1
2
3

Matrix Product (A * B):


14
32

CASE 2:
Enter the number of rows for matrix A: 2
Enter the number of columns for matrix A: 3
Enter the number of rows for matrix B: 4
Enter the number of columns for matrix B: 2
Multiplication is not possible. The number of columns in matrix A must be equal to the number of
rows in matrix B.

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 17


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

AIM: c) Find the determinant of a matrix


PROGRAM
import java.util.Scanner;
import java.util.Arrays;
public class MatrixDet {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter the order of the square matrix: ");
int order = scanner.nextInt();
int[][] matrix = new int[order][order];
System.out.println("Enter elements for the square matrix:");
readMatrixElements(matrix, scanner);
int determinant = calculateDeterminant(matrix);
System.out.println("\nDeterminant of the matrix: " + determinant);

scanner.close();
}

// Function to read elements of a square matrix


private static void readMatrixElements(int[][] matrix, Scanner scanner) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
matrix[i][j] = scanner.nextInt();
}
}
}

// Function to calculate the determinant of a square matrix


private static int calculateDeterminant(int[][] matrix) {
int order = matrix.length;

// Base case: If the matrix is 1x1, return its only element as the
determinant
if (order == 1) {
return matrix[0][0];
}

int determinant = 0;

// Iterate through the first row to calculate the determinant using


Laplace expansion
for (int j = 0; j < order; j++) {
determinant += matrix[0][j] * Math.pow(-1, j) *
calculateDeterminant(getSubMatrix(matrix, 0, j));
}

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 18


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

return determinant;
}

// Function to get a submatrix by excluding the given row and column


private static int[][] getSubMatrix(int[][] matrix, int excludeRow, int
excludeCol) {
int order = matrix.length - 1;
int[][] subMatrix = new int[order][order];
int row = 0;
int col;

for (int i = 0; i < matrix.length; i++) {


if (i == excludeRow) {
continue;
}

col = 0;
for (int j = 0; j < matrix[0].length; j++) {
if (j == excludeCol) {
continue;
}

subMatrix[row][col] = matrix[i][j];
col++;
}

row++;
}

return subMatrix;
}
}
EXPECTED OUTPUT:
Enter the order of the square matrix: 3
Enter elements for the square matrix:
2 1 6 5 4 3 1 1 3

Determinant of the matrix: 12

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 19


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

EXPERIMENT-5
AIM: Write a program to perform the following: a) Reverse a string
PROGRAM
import java.util.Scanner;
import java.util.Arrays;
public class StringReverse {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a string: ");


String inputString = scanner.nextLine();

String reversedString = reverseString(inputString);

System.out.println("Reversed string: " + reversedString);

scanner.close();
}

// Function to reverse a string


private static String reverseString(String input) {
char[] charArray = input.toCharArray();

// Reverse the character array


for (int i = 0, j = charArray.length - 1; i < j; i++, j--) {
char temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
}

// Convert the character array back to a string


return new String(charArray);
}
}
EXPECTED OUTPUT:
Enter a string: My First string
Reversed string: gnirts tsriF yM

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 20


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

AIM: b) Check for palindrome


PROGRAM
import java.util.Scanner;
import java.util.Arrays;
public class StringPalindrome {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a string: ");


String inputString = scanner.nextLine();

// Check if the string is a palindrome


boolean isPalindrome = checkPalindrome(inputString);

if (isPalindrome) {
System.out.println("The entered string is a palindrome.");
} else {
System.out.println("The entered string is not a palindrome.");
}

scanner.close();
}

// Function to check if a string is a palindrome


private static boolean checkPalindrome(String input) {
// Remove spaces and convert to lowercase for case-insensitive
comparison
String cleanedInput = input.replaceAll("\\s", "").toLowerCase();

int length = cleanedInput.length();

for (int i = 0, j = length - 1; i < j; i++, j--) {


if (cleanedInput.charAt(i) != cleanedInput.charAt(j)) {
return false; // Characters don't match, not a palindrome
}
}
return true; // All characters matched, it's a palindrome
}
}
EXPECTED OUTPUT:
Case 1:
Enter a string: Malayalam
The entered string is a palindrome.
Case 2:
Enter a string: english
The entered string is not a palindrome.

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 21


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

AIM: c) Compare two strings


PROGRAM
import java.util.Scanner;
import java.util.Arrays;
public class StringCompare {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

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


String firstString = scanner.nextLine();

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


String secondString = scanner.nextLine();

int comparisonResult = compareStrings(firstString, secondString);

if (comparisonResult == 0) {
System.out.println("Both strings are equal.");
} else if (comparisonResult < 0) {
System.out.println("The first string is less than the second
string.");
} else {
System.out.println("The first string is greater than the second
string.");
}
scanner.close();
}

private static int compareStrings(String str1, String str2) {


int minLength = Math.min(str1.length(), str2.length());

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


char char1 = str1.charAt(i);
char char2 = str2.charAt(i);

if (char1 != char2) {
return char1 - char2;
}
}

// If all characters are the same up to the minimum length, compare lengths
return str1.length() - str2.length();
}
}

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 22


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

EXPECTED OUTPUT:
Case 1:
Enter the first string: hello
Enter the second string: hello
Both strings are equal.
Case 2:
Enter the first string: hai
Enter the second string: hello
The first string is less than the second string.
Case 3:
Enter the first string: hello
Enter the second string: hai
The first string is greater than the second string.

EXPERIMENT-6
AIM: Create a Java class called Student with the following details as variables
within it. USN Name Branch and Phone .Write a Java program to create n Student
objects and print the USN, Name, Branch, and Phone of these objects with suitable
headings.
PROGRAM
import java.util.Scanner;
class Student {
String USN;
String name;
String branch;
String phone;

// Parameterized constructor to initialize student details


public Student(String USN, String name, String branch, String phone) {
this.USN = USN;
this.name = name;
this.branch = branch;
this.phone = phone;
}
}

public class StudentDetails {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int n = scanner.nextInt();

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 23


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

// Create an array to store n Student objects


Student[] students = new Student[n];
// Input details for each student
for (int i = 0; i < n; i++) {
System.out.println("\nEnter details for Student " + (i + 1) +":");
System.out.print("Enter USN: ");
String USN = scanner.next();
System.out.print("Enter Name: ");
String name = scanner.next();
System.out.print("Enter Branch: ");
String branch = scanner.next();
System.out.print("Enter Phone: ");
String phone = scanner.next();
// Create a Student object and store it in the array
students[i] = new Student(USN, name, branch, phone);
}
// Display the details of all students
System.out.println("\nStudent Details:");
System.out.printf("%-10s %-20s %-15s %-15s\n", "USN", "Name",
"Branch", "Phone");
for (Student student : students) {
System.out.printf("%-10s %-20s %-15s %-15s\n", student.USN,
student.name, student.branch, student.phone);
}
}
}
EXPECTED OUTPUT:
Enter the number of students: 2

Enter details for Student 1:


Enter USN: 4KV04EC001
Enter Name: Abhi
Enter Branch: EC
Enter Phone: 9901730364

Enter details for Student 2:


Enter USN: 4KV04ME003
Enter Name: Akash
Enter Branch: ME
Enter Phone: 8105334517

Student Details:
USN Name Branch Phone
4KV04EC001 Abhi EC 9901730364
4KV04ME003 Akash ME 8105334517

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 24


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

EXPERIMENT-7
AIM: Write a Java program to create a class known as “BankAccount” with
methods called deposit() and withdraw(). Create a subclass called SBAccount that
overrides the withdraw() method to prevent withdrawals if the account balance
falls below one hundred.
PROGRAM
import java.util.Scanner;
class BankAccount {
protected double balance;
// Constructor to initialize the balance
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
// Method to deposit money
public void deposit(double amount) {
balance += amount;
System.out.println("Deposit of $" + amount + " successful.");
}
// Method to withdraw money
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("Withdrawal of $" + amount + "successful.");
}
else {
System.out.println("Insufficient funds. Withdrawal not allowed.");
}
}
// Method to get the current balance
public double getBalance() {
return balance;
}
}

class SBAccount extends BankAccount {


// Constructor to initialize the balance using the superclass constructor
public SBAccount(double initialBalance) {
super(initialBalance);
}

// Override withdraw method to prevent withdrawals below $100


@Override
public void withdraw(double amount) {
if (amount <= balance && (balance - amount) >= 100) {
balance -= amount;

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 25


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

System.out.println("Withdrawal of $" + amount + " successful.");


} else {
System.out.println("Withdrawal not allowed. Minimum balance of
$100 must be maintained.");
}
}
}

public class BankDetails {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Create a BankAccount object
System.out.print("Enter initial balance for BankAccount: ");
double initialBalanceBankAccount = scanner.nextDouble();
BankAccount bankAccount = new BankAccount(initialBalanceBankAccount);

// Deposit money
System.out.print("Enter deposit amount for BankAccount: ");
double depositAmountBankAccount = scanner.nextDouble();
bankAccount.deposit(depositAmountBankAccount);

// Withdraw money
System.out.print("Enter withdrawal amount for BankAccount: ");
double withdrawalAmountBankAccount = scanner.nextDouble();
bankAccount.withdraw(withdrawalAmountBankAccount);

// Display current balance


System.out.println("Current balance (BankAccount): $" +
bankAccount.getBalance());

// Create an SBAccount object


System.out.print("\nEnter initial balance for SBAccount: ");
double initialBalanceSBAccount = scanner.nextDouble();
SBAccount sbAccount = new SBAccount(initialBalanceSBAccount);

// Deposit money
System.out.print("Enter deposit amount for SBAccount: ");
double depositAmountSBAccount = scanner.nextDouble();
sbAccount.deposit(depositAmountSBAccount);

// Withdraw money from SBAccount


System.out.print("Enter withdrawal amount for SBAccount: ");
double withdrawalAmountSBAccount = scanner.nextDouble();
sbAccount.withdraw(withdrawalAmountSBAccount);

// Display current balance of SBAccount


System.out.println("Current balance (SBAccount): $" +
sbAccount.getBalance());

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 26


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

scanner.close();
}
}
EXPECTED OUTPUT:
Enter initial balance for BankAccount: 1000
Enter deposit amount for BankAccount: 5000
Deposit of $5000.0 successful.
Enter withdrawal amount for BankAccount: 5500
Withdrawal of $5500.0 successful.
Current balance (BankAccount): $500.0

Enter initial balance for SBAccount: 200


Enter deposit amount for SBAccount: 200
Deposit of $200.0 successful.
Enter withdrawal amount for SBAccount: 500
Withdrawal not allowed. Minimum balance of $100 must be maintained.
Current balance (SBAccount): $400.0

EXPERIMENT-8
AIM: Write a JAVA program demonstrating Method overloading and
Constructor overloading.
PROGRAM
import java.util.Scanner;
public class Overloading {
public static void main(String[] args) {
// Method overloading example
System.out.println("Method Overloading Example:");
System.out.println("Addition of two integers: " + add(5, 10));
System.out.println("Addition of three integers: " + add(5, 10, 15));
System.out.println("Concatenation of two strings: " + add("Hello",
"World"));
System.out.println();

// Constructor overloading example


System.out.println("Constructor Overloading Example:");
Student student1 = new Student(); // Default constructor
Student student2 = new Student("John"); // Constructor with one
parameter
Student student3 = new Student("Alice", 25); // Constructor with two
parameters

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 27


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

// Method overloading: Add two integers


private static int add(int a, int b) {
return a + b;
}

// Method overloading: Add three integers


private static int add(int a, int b, int c) {
return a + b + c;
}

// Method overloading: Concatenate two strings


private static String add(String a, String b) {
return a + " " + b;
}
}

class Student {
private String name;
private int age;

// Default constructor
public Student() {
System.out.println("Default Constructor - No parameters");
}

// Constructor with one parameter


public Student(String name) {
this.name = name;
System.out.println("Constructor with one parameter - Name: " + name);
}

// Constructor with two parameters


public Student(String name, int age) {
this.name = name;
this.age = age;
System.out.println("Constructor with two parameters - Name: " + name +
", Age: " + age);
}
}
EXPECTED OUTPUT:
Method Overloading Example:
Addition of two integers: 15
Addition of three integers: 30
Concatenation of two strings: Hello World

Constructor Overloading Example:

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 28


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

Default Constructor - No parameters


Constructor with one parameter - Name: John
Constructor with two parameters - Name: Alice, Age: 25

EXPERIMENT-9
AIM: Design a super class called Staff with details as StaffId, Name, Phone,
Salary. Extend this class by writing three subclasses namely Teaching
(domain, publications), Technical (skills), and Contract (period). Write a Java
program to read and display at least 3 staff objects of all three categories.
PROGRAM
import java.util.Scanner;
// Superclass
class Staff {
protected String staffId;
protected String name;
protected String phone;
protected double salary;

// Parameterized constructor for Staff


public Staff(String staffId, String name, String phone, double salary)
{
this.staffId = staffId;
this.name = name;
this.phone = phone;
this.salary = salary;
}

// Display method for Staff


public void display() {
System.out.println("Staff ID: " + staffId);
System.out.println("Name: " + name);
System.out.println("Phone: " + phone);
System.out.println("Salary: $" + salary);
}
}

// Subclass Teaching
class Teaching extends Staff {
private String domain;
private String publications;

// Parameterized constructor for Teaching

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 29


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

public Teaching(String staffId, String name, String phone, double


salary, String domain, String publications) {
super(staffId, name, phone, salary);
this.domain = domain;
this.publications = publications;
}

// Display method for Teaching


@Override
public void display() {
super.display();
System.out.println("Domain: " + domain);
System.out.println("Publications: " + publications);
System.out.println("--------------");
}
}

// Subclass Technical
class Technical extends Staff {
private String skills;

// Parameterized constructor for Technical


public Technical(String staffId, String name, String phone, double
salary, String skills) {
super(staffId, name, phone, salary);
this.skills = skills;
}

// Display method for Technical


@Override
public void display() {
super.display();
System.out.println("Skills: " + skills);
System.out.println("--------------");
}
}

// Subclass Contract
class Contract extends Staff {
private int period;

// Parameterized constructor for Contract


public Contract(String staffId, String name, String phone, double
salary, int period) {
super(staffId, name, phone, salary);
this.period = period;
}

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 30


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

// Display method for Contract


@Override
public void display() {
super.display();
System.out.println("Contract Period: " + period + " months");
System.out.println("--------------");
}
}

public class StaffDetails {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Create at least 3 staff objects of each category


Teaching teachingStaff1 = new Teaching("T101", "John Doe",
"1234567890", 60000, "Computer Science", "Research Papers");
Teaching teachingStaff2 = new Teaching("T102", "Alice Smith",
"9876543210", 55000, "Mathematics", "Books");
Teaching teachingStaff3 = new Teaching("T103", "Bob Johnson",
"1112233445", 65000, "Physics", "Articles");

Technical technicalStaff1 = new Technical("Tech101", "Emma White",


"3334445555", 70000, "Java, Python");
Technical technicalStaff2 = new Technical("Tech102", "Charlie
Brown", "6667778888", 75000, "C++, SQL");
Technical technicalStaff3 = new Technical("Tech103", "Ella Green",
"9990001111", 72000, "JavaScript, HTML");

Contract contractStaff1 = new Contract("C101", "David Lee",


"7778889999", 35000, 6);
Contract contractStaff2 = new Contract("C102", "Sophia Turner",
"2223334444", 40000, 9);
Contract contractStaff3 = new Contract("C103", "Liam Wilson",
"5556667777", 38000, 12);

// Display the information of each staff object


System.out.println("Teaching Staff:");
teachingStaff1.display();
teachingStaff2.display();
teachingStaff3.display();

System.out.println("Technical Staff:");
technicalStaff1.display();
technicalStaff2.display();
technicalStaff3.display();

System.out.println("Contract Staff:");
contractStaff1.display();

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 31


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

contractStaff2.display();
contractStaff3.display();
scanner.close();
}
}
EXPECTED OUTPUT:
Teaching Staff:
Staff ID: T101
Name: John Doe
Phone: 1234567890
Salary: $60000.0
Domain: Computer Science
Publications: Research Papers
--------------
Staff ID: T102
Name: Alice Smith
Phone: 9876543210
Salary: $55000.0
Domain: Mathematics
Publications: Books
--------------
Staff ID: T103
Name: Bob Johnson
Phone: 1112233445
Salary: $65000.0
Domain: Physics
Publications: Articles
--------------
Technical Staff:
Staff ID: Tech101
Name: Emma White
Phone: 3334445555
Salary: $70000.0
Skills: Java, Python
--------------
Staff ID: Tech102
Name: Charlie Brown
Phone: 6667778888
Salary: $75000.0
Skills: C++, SQL
--------------
Staff ID: Tech103
Name: Ella Green
Phone: 9990001111
Salary: $72000.0
Skills: JavaScript, HTML
--------------
Contract Staff:
Staff ID: C101

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 32


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

Name: David Lee


Phone: 7778889999
Salary: $35000.0
Contract Period: 6 months
--------------
Staff ID: C102
Name: Sophia Turner
Phone: 2223334444
Salary: $40000.0
Contract Period: 9 months
--------------
Staff ID: C103
Name: Liam Wilson
Phone: 5556667777
Salary: $38000.0
Contract Period: 12 months

EXPERIMENT-10
AIM: a) Write a JAVA program to read two integers a and b. Compute a/b
and print, when b is not zero. Raise an exception when b is equal to zero. Also
demonstrate working of ArrayIndexOutOfBound-Exception
PROGRAM
import java.util.Scanner;

public class ExceptionHandle {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

try
{
System.out.print("Enter integer a: ");
int a = scanner.nextInt();

System.out.print("Enter integer b: ");


int b = scanner.nextInt();

// Check if b is zero
if (b == 0) {
throw new RuntimeException("Cannot divide by zero.");
}

// Compute and print a/b


double result = (double) a / b;

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 33


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

System.out.println("Result of a/b: " + result);


}
catch (RuntimeException e) {
System.out.println("RuntimeException: " + e.getMessage());
}

// Exception handling for ArrayIndexOutOfBoundsException


try {
int[] numbers = {1, 2, 3};

// Attempt to access an index outside the array's bounds


int index = 2;
System.out.println("Value at index " + index + ": " +
numbers[index]);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException: " +
e.getMessage());
}

scanner.close();
}
}
EXPECTED OUTPUT:
Case 1:
Enter integer a: 2 3
Enter integer b: Result of a/b: 0.6666666666666666
ArrayIndexOutOfBoundsException: 5
Case 2:
Enter integer a: 2
Enter integer b: 0
RuntimeException: Cannot divide by zero.
ArrayIndexOutOfBoundsException: 5
Case 3:
Enter integer a: 2
Enter integer b: 0
RuntimeException: Cannot divide by zero.
Value at index 2: 3

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 34


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

AIM: b) Write a Java program to create a method that takes an integer as a


parameter and throws an exception if the number is odd
PROGRAM
import java.util.Scanner;
public class ExceptionEvenOdd {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

try
{
System.out.print("Enter an integer: ");
int number = scanner.nextInt();

// Call the method and handle the exception


checkEvenNumber(number);

// If the number is even, display a success message


System.out.println(number + " is an even number.");
}
catch (OddNumberException e)
{
// Catch and handle the custom exception
System.out.println("Exception: " + e.getMessage());
}
catch (Exception e)
{
// Catch any other exceptions
System.out.println("Unexpected Exception: " + e.getMessage());
} finally {
}
}

// Method to check if a number is even and throw an exception if it's


odd
private static void checkEvenNumber(int number) throws
OddNumberException
{
if (number % 2 != 0) {
// If the number is odd, throw a custom exception
throw new OddNumberException("Odd numbers are not allowed.");
}
}
}

// Custom exception class for odd numbers


class OddNumberException extends Exception {
public OddNumberException(String message) {

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 35


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

super(message);
}
}
EXPECTED OUTPUT:
Case 1:
Enter an integer: 8
8 is an even number.
Case 2:
Enter an integer: 11
Exception: Odd numbers are not allowed.

EXPERIMENT-11
AIM: Write a Java program to create an abstract class BankAccount with
abstract methods deposit() and withdraw(). Create subclasses: SavingsAccount
and CurrentAccount that extend the BankAccount class and implement the
respective methods to handle deposits and withdrawals for each account type.
PROGRAM
import java.util.Scanner;

// Abstract class BankAccount


abstract class BankAccount {
protected double balance;

// Constructor
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}

// Abstract method for deposit


public abstract void deposit(double amount);

// Abstract method for withdraw


public abstract void withdraw(double amount);

// Method to display the current balance


public void displayBalance() {
System.out.println("Current Balance: $" + balance);
}
}

// Subclass SavingsAccount
class SavingsAccount extends BankAccount {
private double interestRate;

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 36


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

// Constructor for SavingsAccount


public SavingsAccount(double initialBalance, double interestRate) {
super(initialBalance);
this.interestRate = interestRate;
}

// Implementation of deposit for SavingsAccount


@Override
public void deposit(double amount) {
balance += amount + (amount * interestRate / 100);
System.out.println("Deposit of $" + amount + " (including interest)
successful.");
}

// Implementation of withdraw for SavingsAccount


@Override
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("Withdrawal of $" + amount + "
successful.");
} else {
System.out.println("Insufficient funds. Withdrawal not
allowed.");
}
}
}

// Subclass CurrentAccount
class CurrentAccount extends BankAccount {
private double overdraftLimit;

// Constructor for CurrentAccount


public CurrentAccount(double initialBalance, double overdraftLimit) {
super(initialBalance);
this.overdraftLimit = overdraftLimit;
}

// Implementation of deposit for CurrentAccount


@Override
public void deposit(double amount) {
balance += amount;
System.out.println("Deposit of $" + amount + " successful.");
}

// Implementation of withdraw for CurrentAccount


@Override

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 37


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

public void withdraw(double amount) {


if (amount <= balance + overdraftLimit) {
balance -= amount;
System.out.println("Withdrawal of $" + amount + "
successful.");
} else {
System.out.println("Exceeds overdraft limit. Withdrawal not
allowed.");
}
}
}

public class JavaApplication6 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Create a SavingsAccount
System.out.print("Enter initial balance for SavingsAccount: $");
double initialBalanceSavings = scanner.nextDouble();
SavingsAccount savingsAccount = new
SavingsAccount(initialBalanceSavings, 2.5);

// Deposit and withdraw from SavingsAccount


savingsAccount.deposit(500);
savingsAccount.displayBalance();
savingsAccount.withdraw(200);
savingsAccount.displayBalance();

System.out.println();

// Create a CurrentAccount
System.out.print("Enter initial balance for CurrentAccount: $");
double initialBalanceCurrent = scanner.nextDouble();
CurrentAccount currentAccount = new
CurrentAccount(initialBalanceCurrent, 1000);

// Deposit and withdraw from CurrentAccount


currentAccount.deposit(1000);
currentAccount.displayBalance();
currentAccount.withdraw(1500);
currentAccount.displayBalance();

scanner.close();
}
}
EXPECTED OUTPUT:
Enter initial balance for SavingsAccount: $2000
Deposit of $500.0 (including interest) successful.

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 38


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

Current Balance: $2512.5


Withdrawal of $200.0 successful.
Current Balance: $2312.5

Enter initial balance for CurrentAccount: $20


Deposit of $1000.0 successful.
Current Balance: $1020.0
Withdrawal of $1500.0 successful.
Current Balance: $-480.0

EXPERIMENT-12
AIM: Create two packages P1 and P2. In package P1, create class A, class B
inherited from A, class C . In package P2, create class D inherited from class
A in package P1 and class E. Demonstrate working of access modifiers
(private, public, protected, default) in all these classes using JAVA
PROGRAM
A.java
package P1;
public class A
{
public void displayA()
{
System.out.println("class A");
}
}

B.java
package P1;
public class B extends A
{
public void displayB()
{
System.out.println("class B");
}
}

C.java
package P1;
public class C
{
public void displayC()
{
System.out.println("class C");

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 39


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

}
}

D.java
package P2;
import P1.A;
public class D extends A
{
public void displayD()
{
System.out.println("class D");
}
}

E.java
package P2;
public class E
{
public void displayE()
{
System.out.println("class E");
}
}

PackageDemo.java
import P1.A;
import P1.B;
import P1.C;
import P2.D;
import P2.E;
class PackageDemo
{
public static void main(String args[])
{
A a=new A();
B b=new B();
C c=new C();
D d=new D();
E e=new E();
a.displayA();
b.displayB();
c.displayC();
d.displayD();
e.displayE();

}
}

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 40


Ability Enhancement Course: JAVA Programming 5th Sem E&CE 21EC583

EXPECTED OUTPUT:
class A
class B
class C
class D
class E

Department of E&CE , K.V.G. College of Engineering Sullia, D.K 41

You might also like