1.a) Write a program to accept two integer numbers from the standard input and
perform the following arithmetic operations: addition, subtraction, and
multiplication public class ArithmeticOperations { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Input first number System.out.print("Enter the first number: "); int num1 = scanner.nextInt(); // Input second number System.out.print("Enter the second number: "); int num2 = scanner.nextInt(); // Addition int sum = num1 + num2; System.out.println("Sum: " + sum); // Subtraction int difference = num1 - num2; System.out.println("Difference: " + difference); // Multiplication int product = num1 * num2; System.out.println("Product: " + product); // Close the scanner to avoid resource leak scanner.close(); 1b)Write a program to calculate simple and compound interest
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Input principal amount System.out.print("Enter the principal amount: "); double principal = scanner.nextDouble(); // Input rate of interest System.out.print("Enter the rate of interest (in percentage): "); double rate = scanner.nextDouble(); // Input time in years System.out.print("Enter the time (in years): "); // Calculate simple interest double simpleInterest = (principal * rate * time) / 100; // Calculate compound interest double compoundInterest = principal * Math.pow((1 + rate / 100), time) - principal; // Display the results System.out.println("Simple Interest: " + simpleInterest); System.out.println("Compound Interest: " + compoundInterest); // Close the scanner to avoid resource leak scanner.close(); 1c)Write a Program to Swap Two Numbers with and without temporary variables.
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Input principal amount System.out.print("Enter the principal amount: "); double principal = scanner.nextDouble(); // Input rate of interest System.out.print("Enter the rate of interest (in percentage): "); double rate = scanner.nextDouble(); // Input time in years System.out.print("Enter the time (in years): "); double time = scanner.nextDouble(); // Calculate simple interest double simpleInterest = (principal * rate * time) / 100; // Calculate compound interest double compoundInterest = principal * Math.pow((1 + rate / 100), time) - principal; // Display the results System.out.println("Simple Interest: " + simpleInterest); System.out.println("Compound Interest: " + compoundInterest); // Close the scanner to avoid resource leak scanner.close(); 1.Swapping with a Temporary Variable public class SwapWithTempVariable { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Input the two numbers System.out.print("Enter the first number: "); int num1 = scanner.nextInt(); System.out.print("Enter the second number: "); int num2 = scanner.nextInt(); // Swapping with a temporary variable int temp; temp = num1; num1 = num2; num2 = temp; // Display the swapped numbers System.out.println("After swapping (with temporary variable):"); System.out.println("First number: " + num1); System.out.println("Second number: " + num2); // Close the scanner to avoid resource leak scanner.close(); 2.Swapping without a Temporary Variable public class SwapWithoutTempVariable { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Input the two numbers System.out.print("Enter the first number: "); int num1 = scanner.nextInt(); System.out.print("Enter the second number: "); int num2 = scanner.nextInt(); // Swapping without a temporary variable num1 = num1 + num2; num2 = num1 - num2; num1 = num1 - num2; // Display the swapped numbers System.out.println("After swapping (without temporary variable):"); System.out.println("First number: " + num1); System.out.println("Second number: " + num2); 2a)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. import java.util.Scanner; public class QuadraticSolver { public static void main(String[] args) { // Create a Scanner object to read input from the user Scanner scanner = new Scanner(System.in); // Read coefficients a, b, and c from the user 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 double discriminant = b * b - 4 * a * c; // Check if the discriminant is non-negative for 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, no real solutions exist System.out.println("No real solutions."); 2b)Write a Program to display All Prime Numbers from 1 to N.
import java.util.Scanner; public class PrimeNumbers { public static void main(String[] args) { // Create a Scanner object to read input from the user Scanner scanner = new Scanner(System.in); // Read the value of N from the user 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++) { boolean isPrime = true; // Check if i is divisible by any number from 2 to the square root of i for (int j = 2; j <= Math.sqrt(i); j++) { if (i % j == 0) { isPrime = false; break; } } // If i is not divisible by any number, it is prime if (isPrime) { System.out.print(i + " "); 2c)Write a Program for factorial of a number.
import java.util.Scanner; public class Factorial { public static void main(String[] args) { // Create a Scanner object to read input from the user Scanner scanner = new Scanner(System.in); // Read the number for which factorial is to be calculated System.out.print("Enter a non-negative integer: "); int number = scanner.nextInt(); // Close the scanner to prevent resource leak scanner.close(); // Calculate and display the factorial long factorial = 1; if (number < 0) { System.out.println("Factorial is not defined for negative numbers."); } else { // Calculate factorial without using additional methods for (int i = 1; i <= number; i++) { factorial *= i; } System.out.println("Factorial of " + number + " is: " + factorial);
Experiment 1
Experiment 2
Experiment 3
3a)Write a program to search a given element in the array using linear and binary search techniques.
linear Search
public class LinearSearch {
public static int linearSearch(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i; // Return the index if the element is found
}
}
return -1; // Return -1 if the element is not found
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int target = 5;
int result = linearSearch(arr, target);
if (result != -1) {
System.out.println("Element " + target + " found at index " + result + ".");
} else {
System.out.println("Element " + target + " not found in the array."); } } }
Binary Search
public class BinarySearch {
public static int binarySearch(int[] arr, int target) {
int low = 0, high = arr.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
int midElement = arr[mid];
if (midElement == target) {
return mid; // Return the index if the element is found
} else if (midElement < target) {
low = mid + 1; // Search in the right half
} else {
high = mid - 1; // Search in the left half
} }return -1; // Return -1 if the element is not found
}public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int target = 5;
int result = binarySearch(arr, target);
if (result != -1) {
System.out.println("Element " + target + " found at index " + result + ".");
} else {
System.out.println("Element " + target + " not found in the array.");
} } }3b) Write a program to sort the elements in ascending and descending order using bubble sort.
bubbleSortAscending
public class BubbleSort {
public static void bubbleSortAscending(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
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;
} } } }public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
System.out.println("Original array: " + Arrays.toString(arr));
// Sort in ascending order
bubbleSortAscending(arr);
System.out.println("Array in ascending order: " + Arrays.toString(arr));
} }bubbleSortDescending
public class BubbleSort {
public static void bubbleSortDescending(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
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;
} } } }public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
System.out.println("Original array: " + Arrays.toString(arr));
// Sort in descending order
bubbleSortDescending(arr);
System.out.println("Array in descending order: " + Arrays.toString(arr));
} }3c)Write a program to find the largest and smallest element in an array.
public class FindMinMax {
public static void findMinMax(int[] arr) {
if (arr == null || arr.length == 0) {
System.out.println("Array is empty.");
return;
}int min = arr[0];
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
} else if (arr[i] > max) {
max = arr[i];
} }System.out.println("Smallest element: " + min);
System.out.println("Largest element: " + max);
}public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
System.out.println("Array: " + Arrays.toString(arr));
findMinMax(arr); } }
Experiment 4
4)Given two matrices A and B, write a program to: a) Add the matrices b) Multiply the matrices c) Find the determinant of a matrix
import java.util.Scanner;
public class MatrixOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter details for Matrix A:");
double[][] matrixA = readMatrix(scanner);
System.out.println("Enter details for Matrix B:");
double[][] matrixB = readMatrix(scanner);
System.out.println("Matrix A:");
printMatrix(matrixA);
System.out.println("Matrix B:");
printMatrix(matrixB);
// a) Add Matrices
double[][] sumMatrix = addMatrices(matrixA, matrixB);
System.out.println("Sum of Matrices A and B:");
printMatrix(sumMatrix);
// b) Multiply Matrices
double[][] productMatrix = multiplyMatrices(matrixA, matrixB);
System.out.println("Product of Matrices A and B:");
printMatrix(productMatrix);
// c) Find Determinant of Matrix A
double determinantA = findDeterminant(matrixA);
System.out.println("Determinant of Matrix A: " + determinantA);
scanner.close();
}// Method to read a matrix from the user
private static double[][] readMatrix(Scanner scanner) {
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int columns = scanner.nextInt();
double[][] matrix = new double[rows][columns];
System.out.println("Enter matrix elements:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print("Enter element at position (" + (i + 1) + "," + (j + 1) + "): ");
matrix[i][j] = scanner.nextDouble();
} }return matrix;
}// Method to print a matrix
private static void printMatrix(double[][] matrix) {
for (double[] row : matrix) {
for (double element : row) {
System.out.print(element + " ");
}System.out.println();
} }// Method to add two matrices
private static double[][] addMatrices(double[][] matrixA, double[][] matrixB) {
int rows = matrixA.length;
int columns = matrixA[0].length;
double[][] sumMatrix = new double[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;
}// Method to multiply two matrices
private static double[][] multiplyMatrices(double[][] matrixA, double[][] matrixB) {
int rowsA = matrixA.length;
int columnsA = matrixA[0].length;
int columnsB = matrixB[0].length;
double[][] productMatrix = new double[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;
}// Method to find determinant of a 2x2 or 3x3 matrix
private static double findDeterminant(double[][] matrix) {
if (matrix.length != matrix[0].length) {
throw new IllegalArgumentException("Determinant can only be calculated for square matrices.");
}int size = matrix.length;
if (size == 2) {
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
} else if (size == 3) {
return matrix[0][0] * (matrix[1][1] * matrix[2][2] - matrix[1][2] * matrix[2][1])
- matrix[0][1] * (matrix[1][0] * matrix[2][2] - matrix[1][2] * matrix[2][0])
+ matrix[0][2] * (matrix[1][0] * matrix[2][1] - matrix[1][1] * matrix[2][0]);
} else {
throw new UnsupportedOperationException("Determinant calculation is not supported for matrices larger than 3x3.");
} } }5)Write a java program to perform the following: a) Reverse a string b) Check for palindrome c) Compare two strings
a) Reverse a string
import java.io.*;
import java.util.Scanner;
class GFG {
public static void main (String[] args) {
String str= "Geeks", nstr="";
char ch;
System.out.print("Original word:
System.out.println("Geeks"); //Example word
for (int i=0; i ch= str.charAt(i); //extracts each character nstr= ch+nstr; //adds each character in front of the existing string } System.out.println("Reversed word: "+ nstr); }} b) Check for palindrome class PalindromeExample{ public static void main(String args[]){ int r,sum=0,temp; int n=454;//It is the number variable to be checked for palindrome temp=n; while(n>0){ r=n%10; //getting remainder sum=(sum*10)+r; n=n/10; } if(temp==sum) System.out.println("palindrome number "); else System.out.println("not palindrome"); } } c) Compare two strings Public class StringComparison { Public static void main(String[] args) { String str1 = "Hello"; String str2 = "Hello"; // Using equals() System.out.println("Using equals():"); System.out.println(str1.equals(str2)); // true } } 6)Create a Java class called Student with the following details as variables within it. USNName 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.
import java.util.Scanner;
class Student {
String usn;
String name;
String branch;
String phone;
}
public class StudentDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get the number of students
System.out.print("Enter the number of students: ");
int n = scanner.nextInt();
// 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++) {
students[i] = new Student();
System.out.println("Enter details for Student " + (i + 1) + ":");
System.out.print("USN: ");
students[i].usn = scanner.next();
System.out.print("Name: ");
students[i].name = scanner.next();
System.out.print("Branch: ");
students[i].branch = scanner.next();
System.out.print("Phone: ");
students[i].phone = scanner.next();
}
// Display details of each student
System.out.println("\nDetails of Students:");
for (int i = 0; i < n; i++) {
System.out.println("Student " + (i + 1) + " -");
System.out.println("USN: " + students[i].usn);
System.out.println("Name: " + students[i].name);
System.out.println("Branch: " + students[i].branch);
System.out.println("Phone: " + students[i].phone);
System.out.println("-----------------------------");
}
// Close the scanner
scanner.close();
}
}
Experiment 7:
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.
class BankAccount {
protected double balance;
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
public void deposit(double amount) {
balance += amount;
System.out.println("Deposited: $" + amount);
}
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: $" + amount);
} else {
System.out.println("Insufficient funds. Withdrawal canceled.");
}
displayBalance();
}
public void displayBalance() {
System.out.println("Current Balance: $" + balance);
}
}
class SBAccount extends BankAccount {
public SBAccount(double initialBalance) {
super(initialBalance);
}
@Override
public void withdraw(double amount) {
if (balance - amount >= 100) {
super.withdraw(amount);
} else {
System.out.println("Withdrawal canceled. Minimum balance requirement not met.");
}
}
}
public class Main {
public static void main(String[] args) {
// Create a regular BankAccount
BankAccount regularAccount = new BankAccount(500);
regularAccount.deposit(200);
regularAccount.withdraw(50);
System.out.println("\n------------------------\n");
// Create an SBAccount (Savings Bank Account)
SBAccount savingsAccount = new SBAccount(300);
savingsAccount.deposit(100);
savingsAccount.withdraw(50); // Will succeed
savingsAccount.withdraw(250); // Will fail due to minimum balance requirement
}
}
Experiment 8:
Write a JAVA program demonstrating Method overloading and Constructor Overloading.
Public class OverloadingExample {
// Constructor overloading
OverloadingExample() {
System.out.println("Default constructor called");
}
OverloadingExample(int num) {
System.out.println("Parameterized constructor with one int parameter called. Value: " + num);
}
OverloadingExample(int num1, int num2) {
System.out.println("Parameterized constructor with two int parameters called. Values: " + num1 + ", " + num2);
}
// Method overloading
void display() {
System.out.println("Method without parameters called");
}
void display(int num) {
System.out.println("Method with one int parameter called. Value: " + num);
}
void display(int num1, int num2) {
System.out.println("Method with two int parameters called. Values: " + num1 + ", " + num2);
}
public static void main(String[] args) {
// Creating objects with different constructors
OverloadingExample obj1 = new OverloadingExample();
OverloadingExample obj2 = new OverloadingExample(10);
OverloadingExample obj3 = new OverloadingExample(20, 30);
// Invoking methods with different parameters
obj1.display();
obj2.display(50);
obj3.display(100, 200);
}
}
Experiment 9:
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..import java.util.Scanner;
//Superclass
class BaseStaff {
private int staffId;
private String name;
private String phone;
private double salary;
public BaseStaff(int staffId, String name, String phone, double salary) {
this.staffId = staffId;
this.name = name;
this.phone = phone;
this.salary = salary;
}
public void displayDetails() {
System.out.println("Staff ID: " + staffId);
System.out.println("Name: " + name);
System.out.println("Phone: " + phone);
System.out.println("Salary: $" + salary);
}
}
//Subclass 1: TeachingStaff
class TeachingStaff extends BaseStaff {
private String domain;
private String publications;
public TeachingStaff(int staffId, String name, String phone, double salary, String domain, String publications) {
super(staffId, name, phone, salary);
this.domain = domain;
this.publications = publications;
}
@Override
public void displayDetails() {
super.displayDetails();
System.out.println("Domain: " + domain);
System.out.println("Publications: " + publications);
}
}
//Subclass 2: Technical
class TechnicalStaff extends BaseStaff {
private String skills;
public TechnicalStaff(int staffId, String name, String phone, double salary, String skills) {
super(staffId, name, phone, salary);
this.skills = skills;
}
@Override
public void displayDetails() {
super.displayDetails();
System.out.println("Skills: " + skills);
}
}
//Subclass 3: Contract
class ContractStaff extends BaseStaff {
private int period;
public ContractStaff(int staffId, String name, String phone, double salary, int period) {
super(staffId, name, phone, salary);
this.period = period;
}
@Override
public void displayDetails() {
super.displayDetails();
System.out.println("Contract Period (months): " + period);
}
}
public class StaffManagementSystem2 {
public static void main(String[] args) {
// Creating Teaching staff objects
TeachingStaff teaching1 = new TeachingStaff(101, "John Doe", "123-456-7890", 60000, "Computer Science", "Research Papers");
TeachingStaff teaching2 = new TeachingStaff(102, "Jane Smith", "987-654-3210", 70000, "Mathematics", "Books on Algebra");
TeachingStaff teaching3 = new TeachingStaff(103, "Bob Johnson", "111-222-3333", 55000, "Physics", "Scientific Journals");
// Creating Technical staff objects
TechnicalStaff technical1 = new TechnicalStaff(201, "Alice Brown", "555-666-7777", 80000, "Java, Python, SQL");
TechnicalStaff technical2 = new TechnicalStaff(202, "Charlie Wilson", "444-333-2222", 75000, "C++, Linux");
TechnicalStaff technical3 = new TechnicalStaff(203, "Eva Davis", "888-999-0000", 90000, "Web Development, JavaScript");
// Creating Contract staff objects
ContractStaff contract1 = new ContractStaff(301, "Sam Green", "123-999-8888", 50000, 6);
ContractStaff contract2 = new ContractStaff(302, "Lisa White", "777-666-5555", 48000, 4);
ContractStaff contract3 = new ContractStaff(303, "David Lee", "333-444-5555", 55000, 8);
// Displaying details of Teaching staff
System.out.println("Teaching Staff Details:");
teaching1.displayDetails();
System.out.println("------------------------");
teaching2.displayDetails();
System.out.println("------------------------");
Steaching3.displayDetails();
System.out.println();
// Displaying details of Technical staff
System.out.println("Technical Staff Details:");
technical1.displayDetails();
System.out.println("------------------------");
technical2.displayDetails();
System.out.println("------------------------");
technical3.displayDetails();
System.out.println();
// Displaying details of Contract staff
System.out.println("Contract Staff Details:");
contract1.displayDetails();
System.out.println("------------------------");
contract2.displayDetails();
System.out.println("------------------------");
contract3.displayDetails();
}
}
Experiment 10:
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-Exceptionimport java.util.Scanner;
public class ExceptionDemo {
public static void main(String[] args) {
try {
// Read two integers a and b
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the value of a: ");
int a = scanner.nextInt();
System.out.print("Enter the value of b: ");
int b = scanner.nextInt();
// Check if b is not zero
if (b != 0) {
// Compute a/b
int result = a / b;
System.out.println("Result of a/b: " + result);
} else {
// Raise an exception if b is zero
throw new ArithmeticException("Cannot divide by zero.");
}
// Demonstrate ArrayIndexOutOfBoundsException
int[] array = { 1, 2, 3 };
System.out.println("Demonstrating ArrayIndexOutOfBoundsException:");
System.out.println("Value at index 3: " + array[3]);
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " + e.getMessage());
} catch (Exception e) {
System.out.println("Generic exception caught: " + e.getMessage());
}
}
}
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
public class OddNumberExceptionDemo {
// Method that throws an exception if the number is odd
static void checkIfEven(int number) throws OddNumberException {
if (number % 2 != 0) {
throw new OddNumberException("Number is odd: " + number);
} else {
System.out.println("Number is even: " + number);
}
}
public static void main(String[] args) {
try {
// Test the method with different numbers
checkIfEven(4); // Even number
checkIfEven(7); // Odd number, will throw an exception
checkIfEven(10); // Even number
} catch (OddNumberException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}
// Custom exception class for odd numbers
class OddNumberException extends Exception {
public OddNumberException(String message) {
super(message);
}
}
EXPT 11.
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
abstract class BankAccount {
protected double balance;
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
public abstract void deposit(double amount);
public abstract void withdraw(double amount);
public double getBalance() {
return balance;
}
}
class SavingsAccount extends BankAccount {
private double interestRate;
public SavingsAccount(double initialBalance, double interestRate) {
super(initialBalance);
this.interestRate = interestRate;
}
@Override
public void deposit(double amount) {
balance += amount;
applyInterest();
}
@Override
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
applyInterest();
} else {
System.out.println("Insufficient funds");
}
}
private void applyInterest() { balance += balance * interestRate; } }class CurrentAccount extends BankAccount {
private double overdraftLimit;
public CurrentAccount(double initialBalance, double overdraftLimit) {
super(initialBalance);
this.overdraftLimit = overdraftLimit;
}
@Override
public void deposit(double amount) {
balance += amount;
}
@Override
public void withdraw(double amount) {
if (amount <= balance + overdraftLimit) {
balance -= amount;
} else {
System.out.println("Exceeded overdraft limit");
}
}
}
public class BankAccountExample {
public static void main(String[] args) {
// Example usage
SavingsAccount savingsAccount = new SavingsAccount(1000, 0.05);
CurrentAccount currentAccount = new CurrentAccount(500, 200);
System.out.println("Savings Account Balance: " + savingsAccount.getBalance());
savingsAccount.deposit(200);
System.out.println("After deposit: " + savingsAccount.getBalance());
savingsAccount.withdraw(150);
System.out.println("After withdrawal: " + savingsAccount.getBalance());
System.out.println("\nCurrent Account Balance: " + currentAccount.getBalance());
currentAccount.withdraw(700);
System.out.println("After withdrawal: " + currentAccount.getBalance());
currentAccount.withdraw(300);
System.out.println("After withdrawal: " + currentAccount.getBalance());
}
}
EXPT 12.
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
// P1/A.java
package P1;
public class A {
private int privateVar;
int defaultVar;
protected int protectedVar;
public int publicVar;
public A() {
privateVar = 10;
defaultVar = 20;
protectedVar = 30;
publicVar = 40;
}
private void privateMethod() {
System.out.println("Private method in class A");
}
void defaultMethod() {
System.out.println("Default method in class A");
}
protected void protectedMethod() {
System.out.println("Protected method in class A");
}
public void publicMethod() {
System.out.println("Public method in class A");
}
}
// P1/B.java
package P1;
public class B extends A {
public void accessVariablesAndMethods() {
// Accessing variables and methods of class A in class B
// privateVar and privateMethod are not accessible here
System.out.println("Inherited Variables: defaultVar=" + defaultVar +
", protectedVar=" + protectedVar + ", publicVar=" + publicVar);
defaultMethod();
protectedMethod();
publicMethod();
}
}
// P1/C.java
package P1;
public class C {
public void accessVariablesAndMethods() {
A a = new A();
// Accessing variables and methods of class A in class C
// privateVar and privateMethod are not accessible here
System.out.println("Variables in class A: defaultVar=" + a.defaultVar +
", protectedVar=" + a.protectedVar + ", publicVar=" + a.publicVar);
a.defaultMethod();
a.protectedMethod();
a.publicMethod();
}
Package P2:
// P2/D.java
package P2;
import P1.A;
public class D extends A {
public void accessVariablesAndMethods() {
// Accessing variables and methods of class A in class D
// privateVar and privateMethod are not accessible here
System.out.println("Inherited Variables: defaultVar=" + defaultVar +
", protectedVar=" + protectedVar + ", publicVar=" + publicVar);
defaultMethod();
protectedMethod();
publicMethod();
}
}
// P2/E.java
package P2;
public class E {
public void accessClassAVariablesAndMethods() {
A a = new A();
// Accessing variables and methods of class A from a different package in class E
// Only publicVar and publicMethod are accessible here
System.out.println("Public Variables and Methods in class A: publicVar=" + a.publicVar);
a.publicMethod();
}
}
Main Program (outside the packages):
import P1.A;
import P1.B;
import P1.C;
import P2.D;
import P2.E;
public class AccessModifiersDemo {
public static void main(String[] args) {
A a = new A();
// Accessing variables and methods of class A from a different package
// Only publicVar and publicMethod are accessible here
System.out.println("Public Variables and Methods in class A: publicVar=" + a.publicVar);
a.publicMethod();
B b = new B();
b.accessVariablesAndMethods();
C c = new C();
c.accessVariablesAndMethods();
D d = new D();
d.accessVariablesAndMethods();
E e = new E();
e.accessClassAVariablesAndMethods();
}
}
Total Visitors: 0
Total Visitors: 0