21EC583
21EC583
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)
{
}
}
EXPECTED OUTPUT:
Enter the first integer: 3
Enter the second integer: -4
Sum: -1
Difference: 7
Product: -12
}
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
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
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
return true;
}
}
EXPECTED OUTPUT:
Enter the value of N: 20
Prime numbers from 1 to 20:
2 3 5 7 11 13 17 19
if (n == 0 || n == 1) {
return 1; // Factorial of 0 and 1 is 1
}
return result;
}
}
EXPECTED OUTPUT:
Enter a number: 3
Factorial of 3 is: 6
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));
scanner.close();
}
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
}
}
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
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 {
swapped = true;
}
}
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]
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);
scanner.close();
}
return largest;
}
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 {
System.out.println("\nMatrix A:");
printMatrix(matrixA);
System.out.println("\nMatrix B:");
printMatrix(matrixB);
scanner.close();
}
else
{
System.out.println("Addition is not possible");
}
}
return sumMatrix;
}
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
if (columnsA == rowsB) {
int[][] matrixA = new int[rowsA][columnsA];
int[][] matrixB = new int[rowsB][columnsB];
System.out.println("\nMatrix A:");
printMatrix(matrixA);
System.out.println("\nMatrix B:");
printMatrix(matrixB);
scanner.close();
}
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.");
}
}
return productMatrix;
}
Matrix A:
1 2 3
4 5 6
Matrix B:
1
2
3
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.
scanner.close();
}
// Base case: If the matrix is 1x1, return its only element as the
determinant
if (order == 1) {
return matrix[0][0];
}
int determinant = 0;
return determinant;
}
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
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);
scanner.close();
}
if (isPalindrome) {
System.out.println("The entered string is a palindrome.");
} else {
System.out.println("The entered string is not a palindrome.");
}
scanner.close();
}
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();
}
if (char1 != char2) {
return char1 - char2;
}
}
// If all characters are the same up to the minimum length, compare lengths
return str1.length() - str2.length();
}
}
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;
Student Details:
USN Name Branch Phone
4KV04EC001 Abhi EC 9901730364
4KV04ME003 Akash ME 8105334517
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;
}
}
// 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);
// Deposit money
System.out.print("Enter deposit amount for SBAccount: ");
double depositAmountSBAccount = scanner.nextDouble();
sbAccount.deposit(depositAmountSBAccount);
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
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();
class Student {
private String name;
private int age;
// Default constructor
public Student() {
System.out.println("Default Constructor - No parameters");
}
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;
// Subclass Teaching
class Teaching extends Staff {
private String domain;
private String publications;
// Subclass Technical
class Technical extends Staff {
private String skills;
// Subclass Contract
class Contract extends Staff {
private int period;
System.out.println("Technical Staff:");
technicalStaff1.display();
technicalStaff2.display();
technicalStaff3.display();
System.out.println("Contract Staff:");
contractStaff1.display();
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
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;
try
{
System.out.print("Enter integer a: ");
int a = scanner.nextInt();
// Check if b is zero
if (b == 0) {
throw new RuntimeException("Cannot divide by zero.");
}
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
try
{
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
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;
// Constructor
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
// Subclass SavingsAccount
class SavingsAccount extends BankAccount {
private double interestRate;
// Subclass CurrentAccount
class CurrentAccount extends BankAccount {
private double overdraftLimit;
// Create a SavingsAccount
System.out.print("Enter initial balance for SavingsAccount: $");
double initialBalanceSavings = scanner.nextDouble();
SavingsAccount savingsAccount = new
SavingsAccount(initialBalanceSavings, 2.5);
System.out.println();
// Create a CurrentAccount
System.out.print("Enter initial balance for CurrentAccount: $");
double initialBalanceCurrent = scanner.nextDouble();
CurrentAccount currentAccount = new
CurrentAccount(initialBalanceCurrent, 1000);
scanner.close();
}
}
EXPECTED OUTPUT:
Enter initial balance for SavingsAccount: $2000
Deposit of $500.0 (including interest) successful.
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");
}
}
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();
}
}
EXPECTED OUTPUT:
class A
class B
class C
class D
class E