Posted in

ENCAPSULATION PROGRAMS AND ALGORITHMS

1. Write a Java program to implement encapsulation in a class Employee with private fields name, age, and salary. Provide getters and setters and add validation for age and salary?

Algorithm :

  • Start
  • Define a class Employee.
  • Declare private fields: name (String), age (int), and salary (double).
  • Create public getter and setter methods for each field.
    • In the setter for age, check if age > 0.
    • If valid, assign it.
  • Else, print “Age must be a positive integer.”
    • In the setter for salary, check if salary >= 0.
    • If valid, assign it.
  • Else, print “Salary cannot be negative.”
  • Define a method displayEmployeeDetails() to print name, age, and salary.
  • In the Main class, create an object of Employee.
  • Use setter methods to assign valid values.
  • Try to assign invalid values to test validation.
  • Call displayEmployeeDetails() to print the stored employee data.
  • End

Program :

class Employee {
    private String name;
    private int age;
    private double salary;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        if (age > 0) { 
            this.age = age;
        } else {
            System.out.println(“Age must be a positive integer.”);
        }
    }
    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        if (salary >= 0) { 
            this.salary = salary;
        } else {
            System.out.println(“Salary cannot be negative.”);
        }
    }
    public void displayEmployeeDetails() {
        System.out.println(“Employee Name: ” + name);
        System.out.println(“Employee Age: ” + age);
        System.out.println(“Employee Salary: ” + salary);
    }
}
public class Main {
    public static void main(String[] args) {
        Employee emp = new Employee();
        emp.setName(“John Doe”);
        emp.setAge(30);     
        emp.setSalary(50000);
        // Attempting to set invalid values
        emp.setAge(-5);       // Invalid age
        emp.setSalary(-2000); // Invalid salary
        emp.displayEmployeeDetails();
    }

Output :

Employee Name: John Doe
Employee Age: 30
Employee Salary: 50000.0
Age must be a positive integer.
Salary cannot be negative.

Explanation :

             This Java program demonstrates encapsulation by using private fields (name, age, salary) in the Employee class and accessing them through public getter and setter methods. It includes validation in the setters to ensure age is positive and salary is non-negative. This protects the data from invalid inputs and maintains the integrity of the object’s state.

2. Write a program to design a class BankAccount using encapsulation. The class should have private fields accountNumber, balance, and accountHolderName. Implement methods to deposit, withdraw, and check the balance, ensuring that the withdrawal amount does not exceed the balance?

Algorithm :

  • Start
  • Class Definition
  • A class named BankAccount is defined with three private attributes:
    • accountNumber (String)
    • accountHolderName (String)
    • balance (double)
  • Constructor
    • The constructor initializes a new BankAccount object with:
      • accountNumber as a string
      • accountHolderName as a string
      • initialBalance as a double
    • If initialBalance is less than 0, balance is set to 0; otherwise, it is set to initialBalance.
  • deposit() Method
    • This method increases the balance by a given amount if the amount is positive.
  • withdraw() Method
    • This method subtracts the amount from balance only if:
      • amount is greater than 0
      • amount is less than or equal to balance
    • If not, it prints “Insufficient balance or invalid amount.”
  • checkBalance() Method
    • Prints the current balance of the account.
  • Main Method Execution
    • A new BankAccount object is created with:
      • accountNumber = “123456”
      • accountHolderName = “John Doe”
      • initialBalance = 5000
  • checkBalance() prints the initial balance.
  • deposit(2000) adds 2000 to the balance → balance becomes 7000.
  • withdraw(1500) subtracts 1500 from the balance → balance becomes 5500.
  • withdraw(6000) fails (6000 > 5500), prints error.
  • Final checkBalance() prints the final balance (still 5500).
  • End

Program :

class BankAccount {
    private String accountNumber;
    private double balance;
    private String accountHolderName;
    public BankAccount(String accountNumber, String accountHolderName, double initialBalance) {
        this.accountNumber = accountNumber;
        this.accountHolderName = accountHolderName;
        this.balance = initialBalance >= 0 ? initialBalance : 0;
    }
    public void deposit(double amount) {
        if (amount > 0) balance += amount;
    }
    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance)
        {
          balance -= amount;
         }
        else
       {
       System.out.println(“Insufficient balance or invalid amount.”);
    }
    public void checkBalance() {
        System.out.println(“Balance: $” + balance);
    }
}
public class Main {
    public static void main(String[] args) {
        BankAccount account = new BankAccount(“123456”, “John Doe”, 5000);
        account.checkBalance();
        account.deposit(2000);
        account.withdraw(1500);
        account.withdraw(6000);
        account.checkBalance();
    }
}

Output :

Balance: $5000.0
Balance: $7000.0
Balance: $5500.0
Insufficient balance or invalid amount.
Balance: $5500.0

Explanation :

           This Java program simulates a simple bank account system. It allows depositing and withdrawing money with checks to ensure only valid amounts are processed. The account starts with $5000, deposits $2000 (making it $7000), withdraws $1500 (leaving $5500), then fails to withdraw $6000 due to insufficient funds. It prints the balance before and after the transactions.

3. Write a program to create a class Student using encapsulation where the fields name, rollNumber, and marks are private. Implement a constructor to initialize the student details, and ensure that the marks field is always within a valid range (0-100)?

 Algorithm :

  • Start
  • Class Student Definition
    • Has three private attributes: name, rollNumber, and marks.
  • Constructor
    • Initializes the name, rollNumber, and calls setMarks(marks) to validate marks.
  • setMarks(int marks) Method
    • Sets marks to the given value only if it’s between 0 and 100; otherwise, sets it to 0.
  • displayDetails() Method
    • Prints the student’s name, roll number, and marks.
  • Main Method Execution
    • Creates student1 with valid marks (85).
    • Creates student2 with invalid marks (110), so marks are set to 0.
    • Creates student3 with valid marks (95).
    • Calls displayDetails() on each student to print their details.
  • End

Program :

   class Student {
    private String name;
    private int rollNumber;
    private int marks;
    public Student(String name, int rollNumber, int marks) {
        this.name = name;
        this.rollNumber = rollNumber;
        setMarks(marks);  // Ensure valid marks
    }
    public void setMarks(int marks) {
        this.marks = (marks >= 0 && marks <= 100) ? marks : 0;
    }
    public void displayDetails() {
        System.out.println(“Name: ” + name);
        System.out.println(“Roll Number: ” + rollNumber);
        System.out.println(“Marks: ” + marks);
    }
}
public class Main {
    public static void main(String[] args) {
        Student student1 = new Student(“John Doe”, 101, 85);
        Student student2 = new Student(“Jane Smith”, 102, 110); // Invalid marks
        Student student3 = new Student(“Alice Johnson”, 103, 95);
        student1.displayDetails();
        student2.displayDetails(); 
        student3.displayDetails();
    }
}

Output :          

Name: John Doe
Roll Number: 101
Marks: 85
Name: Jane Smith
Roll Number: 102
Marks: 0
Name: Alice Johnson
Roll Number: 103
Marks: 95

Explanation :

This program defines a Student class that stores and displays a student’s name, roll number, and marks. It ensures marks are valid (0–100), otherwise sets them to 0. Three student objects are created, and their details are printed. One student has invalid marks (110), so their marks default to 0 when displayed.

4. Write a program to a class Rectangle where the private fields width and height are encapsulated implement methods to calculate the area and perimeter, and ensure that the width and height can only be positive values?

Algorithm :

  • Start
  • Class Rectangle Definition
    • Has two private attributes: width and height.
  • Constructor
    • Takes width and height as parameters.
  • Calls setWidth(width) and setHeight(height) to initialize them with validation.
  • setWidth(double width) Method
    • Sets width only if it’s greater than 0.
    • Else, prints “Width must be positive.”
    • setHeight(double height) Method
    • Sets height only if it’s greater than 0.
    • Else, prints “Height must be positive.”
  • getArea() Method
    • Returns the area as width * height.
  • getPerimeter() Method
    • Returns the perimeter as 2 * (width + height).
  • displayDetails() Method
  • Prints width, height, area, and perimeter.
  • Main Method ExecutionCreates rect with valid dimensions (5, 10), then displays its details.
  • Creates invalidRect with invalid dimensions (-5, -10), so both width and height are not set and error messages are shown.
  • End

Program :

    class Rectangle {
    private double width;
    private double height;
    public Rectangle(double width, double height) {
        setWidth(width);
        setHeight(height);
    }
    public void setWidth(double width) {
        if (width > 0) this.width = width;
        else System.out.println(“Width must be positive.”);
    }
    public void setHeight(double height) {
        if (height > 0) this.height = height;
        else System.out.println(“Height must be positive.”);
    }
    public double getArea() {
        return width * height;
    }
    public double getPerimeter() {
        return 2 * (width + height);
    }
    public void displayDetails() {
        System.out.println(“Width: ” + width);
        System.out.println(“Height: ” + height);
        System.out.println(“Area: ” + getArea());
        System.out.println(“Perimeter: ” + getPerimeter());
    }
}
public class Main {
    public static void main(String[] args) {
        // Create a Rectangle object
        Rectangle rect = new Rectangle(5, 10);
        rect.displayDetails();
        Rectangle invalidRect = new Rectangle(-5, -10); // Invalid width and height
    }
}  

Output :    

      Width: 5.0
      Height: 10.0
      Area: 50.0
      Perimeter: 30.0
     Width must be positive.
     Height must be positive.

Explanation :

This program defines a Rectangle class that calculates and displays the area and perimeter of a rectangle only if valid dimensions are provided. It checks that both width and height are positive. A valid rectangle (5, 10) is created and displayed. When trying to create a rectangle with negative values, the program prints error messages and does not set those dimensions.

5. Write a program to implement encapsulation in a class Product with private fields productId, productName, and price. Provide getters and setters for each field, and ensure that the price cannot be set to a negative value?

Algorithm :

  • Start Program Execution from the main method in the Main class.
  • Create product1 using the Product constructor with:
    • productId = 101
    • productName = “Laptop”
    • price = 899.99
  • In the constructor:
    • Set productId to 101.
    • Set productName to “Laptop”.
    • Call setPrice(899.99) → since it is non-negative, set price to 899.99.
  • Call displayDetails() for product1:
    • Print product details with price $899.99.
  • Create product2 using the Product constructor with:
    • productId = 102
    • productName = “Smartphone”
    • price = -500
  • In the constructor:
    • Set productId to 102.
    • Set productName to “Smartphone”.
    • Call setPrice(-500) → invalid price, print “Price cannot be negative.” and do not update the price (remains 0.0).
  • Call displayDetails() for product2:
    • Print product details with price $0.0 (default value).
  • End

Program :

    class Product {
    private int productId;
    private String productName;
    private double price;
      public Product(int productId, String productName, double price) {
        this.productId = productId;
        this.productName = productName;
        setPrice(price); // Use setter to ensure valid price
    }
    public int getProductId() {
        return productId;
    }
    public void setProductId(int productId) {
        this.productId = productId;
    }
    public String getProductName() {
        return productName;
    }
    public void setProductName(String productName) {
        this.productName = productName;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        if (price >= 0) {
            this.price = price;
        } else {
            System.out.println(“Price cannot be negative.”);
        }
    }
    public void displayDetails() {
        System.out.println(“Product ID: ” + productId);
        System.out.println(“Product Name: ” + productName);
        System.out.println(“Price: $” + price);
    }
}
public class Main {
    public static void main(String[] args) {
        Product product1 = new Product(101, “Laptop”, 899.99);
        product1.displayDetails();
        Product product2 = new Product(102, “Smartphone”, -500);
        product2.displayDetails();  // Price will not be set due to validation
    }
}

Output :    

      Product ID: 101
      Product Name: Laptop
      Price: $899.99
      Price cannot be negative.
      Product ID: 102
      Product Name: Smartphone
      Price: $0.0

Explanation :

This program creates a Product class with fields for ID, name, and price. It includes validation to prevent setting a negative price. In the main method, two products are created—one with a valid price and one with a negative price. The first product displays its correct details, while the second shows a price of 0.0 because the negative price was rejected.

6. Write a program to design a class PhoneNumber with a private field number. Write a setter method to validate that the phone number is exactly 10 digits long. If it’s invalid, throw an exception or return an error message?

Algorithm :

  • Start
  • Class Definition:
    • A class PhoneNumber is defined with a private string field number.
    • It includes:
      • setNumber(String number): Sets the number if it’s exactly 10 digits using regex (\\d{10}); else throws an IllegalArgumentException.
      • getNumber(): Returns the stored number.
  • Main Class Execution:
    • A PhoneNumber object phone is created.
    • Inside a try block:
      • phone.setNumber(“1234567890”) is called.
        • The number is valid (10 digits), so it is accepted and stored.
      • System.out.println(…) prints the stored number: “Phone Number: 1234567890”.
      • phone.setNumber(“12345”) is called.
        • The number is invalid (only 5 digits), so an IllegalArgumentException is thrown.
    • The catch block catches the exception and prints: “Invalid phone number! It must be exactly 10 digits.”
  • End

 Program :

    class PhoneNumber {
    private String number;
    public void setNumber(String number) throws IllegalArgumentException {
        if (number != null && number.matches(“\\d{10}”)) {
            this.number = number;
        } else {
            throw new IllegalArgumentException(“Invalid phone number! It must be exactly 10 digits.”);
        }
    }
    public String getNumber() {
        return number;
    }
}
public class Main {
    public static void main(String[] args) {
        PhoneNumber phone = new PhoneNumber();
        try {
            phone.setNumber(“1234567890”);
            System.out.println(“Phone Number: ” + phone.getNumber());
            phone.setNumber(“12345”); // Invalid, should throw exception
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

Output :      

 Phone Number: 1234567890
 Invalid phone number! It must be exactly 10 digits.

Explanation :

       This Java program defines a PhoneNumber class that only accepts phone numbers of exactly 10 digits. The setNumber method validates input using a regular expression and throws an exception for invalid input. In the main method, a valid number is set and displayed, followed by an attempt to set an invalid number, which is caught and reported with a descriptive error message. This demonstrates basic input validation and exception handling in Java.

7. Write a class Circle with a private field radius. Implement a method to calculate the area of the circle and make sure that the radius is non-negative?

Algorithm :

  • Start
  • Class Definition (Circle)
  • Private field radius is declared.
  • Constructor Circle(double radius):
    1. Calls setRadius(radius) to initialize the radius.
  • Method setRadius(double radius):
    1. If radius >= 0, assigns the value to this.radius.
    2. If radius < 0, prints a warning and sets this.radius = 0.
  • Method getArea():
    1. Returns area using formula π * r².
  • Method getRadius():
    1. Returns the value of radius.
  • Main Class Execution:
  • Create circle1 with radius 5:
    1. Constructor calls setRadius(5) → radius is valid, set to 5.
    2. Print radius → Output: Radius: 5.0
    3. Print area → Output: Area: 78.53981633974483 (since π * 25)
  • Create circle2 with radius -3:
    1. Constructor calls setRadius(-3) → radius invalid, prints warning, sets radius to 0.
    2. Print radius → Output: Radius: 0.0
    3. Print area → Output: Area: 0.0
  • End

Program :

     class Circle {
    private double radius;
    public Circle(double radius) {
        setRadius(radius);
    }
    public void setRadius(double radius) {
        if (radius >= 0) {
            this.radius = radius;
        } else {
            System.out.println(“Radius cannot be negative.”);
            this.radius = 0;  // Set radius to 0 if invalid
        }
    }
    public double getArea() {
        return Math.PI * radius * radius;
    }
    public double getRadius() {
        return radius;
    }
}
public class Main {
    public static void main(String[] args) {
        Circle circle1 = new Circle(5);
        System.out.println(“Radius: ” + circle1.getRadius());
        System.out.println(“Area: ” + circle1.getArea());
        Circle circle2 = new Circle(-3);
        System.out.println(“Radius: ” + circle2.getRadius());
        System.out.println(“Area: ” + circle2.getArea());
    }
}

Output :    

   Radius: 5.0
   Area: 78.53981633974483
   Radius cannot be negative.
   Radius: 0.0
   Area: 0.0

Explanation :

This Java program defines a Circle class that ensures a circle’s radius is non-negative. If a negative radius is given, it defaults to 0 and notifies the user. It demonstrates constructor-based object initialization, input validation, and simple geometric computation. The main method creates two Circle instances — one with a valid radius and another with an invalid one and prints their radii and areas accordingly.

8. Write a program to create a class Car using encapsulation with private fields model, year, and price implement a method to update the price, but ensure the price can only be updated by authorized personnel ?

Algorithm :

  • Start
  • Class Definition – Car:
    • Fields: model (String), year (int), price (double).
    • Constructor Car(String, int, double):
      • Initializes model, year, and price with the given arguments.
    • Getter Methods:
      • getModel(), getYear(), and getPrice() return their respective values.
    • Method updatePrice(double newPrice, String authorizedPerson):
      • If authorizedPerson equals “admin”, update price to newPrice and print success message.
      • Else, print unauthorized access message.
    • Method displayDetails():
      • Prints the current model, year, and price of the car.
  • Main Class Execution:
    • Create a Car object with “Toyota Corolla”, 2020, and 20000 as initial values.
    • Call car.displayDetails():
      • Output:
        •    Model: Toyota Corolla
        • Year: 2020
        • Price: $20000.0
      • Call car.updatePrice(22000, “guest”):
  • “guest” is not “admin” → print: Unauthorized person. Price update failed.
    • car.updatePrice Call (22000, “admin”):
  • “admin” is authorized → price is updated to 22000, print: Price updated successfully.
    • Call car.displayDetails() again:
  • Output:
    • Model: Toyota Corolla
    • Year: 2020
    • Price: $22000.0
  • End

Program :

class Car {
    private String model;
    private int year;
    private double price;
    // Constructor to initialize car details
    public Car(String model, int year, double price) {
        this.model = model;
        this.year = year;
        this.price = price;
    }
    public String getModel() {
        return model;
    }
    public int getYear() {
        return year;
    }
    public double getPrice() {
        return price;
    }
    public void updatePrice(double newPrice, String authorizedPerson) {
        if (“admin”.equals(authorizedPerson)) {
            this.price = newPrice;
            System.out.println(“Price updated successfully.”);
        } else {
            System.out.println(“Unauthorized person. Price update failed.”);
        }
    }
    public void displayDetails() {
        System.out.println(“Model: ” + model);
        System.out.println(“Year: ” + year);
        System.out.println(“Price: $” + price);
    }
}
public class Main {
    public static void main(String[] args) {
        // Create a Car object
        Car car = new Car(“Toyota Corolla”, 2020, 20000);
        car.displayDetails();
        car.updatePrice(22000, “guest”);
        car.updatePrice(22000, “admin”); 
        // Display updated details
        car.displayDetails();
    }
}

Output :  

Model: Toyota Corolla
Year: 2020
Price: $20000.0
Unauthorized person. Price update failed.
Price updated successfully.
Model: Toyota Corolla
Year: 2020
Price: $22000.0

Explanation :

This Java program defines a Car class that models a car’s details, including its model, year, and price. It allows price updates only when the request comes from an authorized person (specifically, “admin”). In the main method, a Car object is created, its details are displayed, and two attempts are made to update the price — one by an unauthorized person (which fails) and one by an admin (which succeeds). This demonstrates object-oriented design with encapsulation and basic access control logic.

9. Write a program to a design a class Customer with private fields customerId, name, and address implement encapsulation to allow the address to be updated only if a certain condition (such as a valid customer ID) is met?

Algorithm :

  • Start the Program: Execution begins in the main method of the Main class.
  • Create Customer Object:
    • Customer customer = new Customer(101, “John Doe”, “123 Main St”);
    • Calls the constructor of Customer class.
    • Initializes:
      • customerId = 101
      • name = “John Doe”
      • address = “123 Main St”
  • Display Initial Customer Details:
  • customer.displayDetails();
  • Prints:
    ID: 101, Name: John Doe, Address: 123 Main St
  • Try to Update Address with Invalid ID:
  • customer.updateAddress(102, “456 Elm St”);
  • Compares 102 with internal customerId (101) → not equal.
  • Prints:
    Invalid customer ID. Address update failed.
  • Update Address with Valid ID:
    • customer.updateAddress(101, “456 Elm St”);
    • Compares 101 with internal customerId (101) → match.
    • Updates address to “456 Elm St”
    • Prints:
      Address updated successfully.
  •  Display Updated Customer Details:
    • customer.displayDetails();
    • Prints:
      ID: 101, Name: John Doe, Address: 456 Elm St
  •   Program Ends

Program :

    class Customer {
    private int customerId;
    private String name;
    private String address;
    public Customer(int customerId, String name, String address) {
        this.customerId = customerId;
        this.name = name;
        this.address = address;
    }
    public void updateAddress(int customerId, String newAddress) {
        if (this.customerId == customerId) {
            address = newAddress;
            System.out.println(“Address updated successfully.”);
        } else {
            System.out.println(“Invalid customer ID. Address update failed.”);
        }
    }
    public void displayDetails() {
        System.out.println(“ID: ” + customerId + “, Name: ” + name + “, Address: ” + address);
    }
}
public class Main {
    public static void main(String[] args) {
        Customer customer = new Customer(101, “John Doe”, “123 Main St”);
        customer.displayDetails();
        customer.updateAddress(102, “456 Elm St”);  // Invalid ID
        customer.updateAddress(101, “456 Elm St”);  // Valid ID
        customer.displayDetails();
    }
}

Output :  

    ID: 101, Name: John Doe, Address: 123 Main St
    Invalid customer ID. Address update failed.
    Address updated successfully.
    ID: 101, Name: John Doe, Address: 456 Elm St

Explanation :

  This Java program defines a Customer class with methods to display details and update the address if the correct customer ID is provided. In the main method, a customer is created and their details are displayed. An attempt to update the address with an incorrect ID fails, while a second attempt with the correct ID succeeds. The updated details are then displayed, demonstrating how object attributes can be securely modified through conditional logic.

10. Write a program to implement a class Book with private fields title, author, and price. Write methods to get and set the values, ensuring that the price is always greater than 0 and that the title and author cannot be empty?

Algorithm :

  • Start Program – Execution begins in the main method of the Main class.
  • Create First Book Object:
    • Book book = new Book(); creates a new Book object.
  • Set Valid Details for book:
    • book.setTitle(“Java Programming”);
      •  Valid title → set successfully.
    • book.setAuthor(“John Doe”);
      • Valid author → set successfully.
    • book.setPrice(29.99);
      • Positive price → set successfully.
  • Display First Book Details:
    • book.displayDetails();
       Prints:
      Title: Java Programming, Author: John Doe, Price: $29.99
  • Create Second Book Object:
    • Book invalidBook = new Book(); creates another Book object.
  • Set Invalid Details for invalidBook:
    • invalidBook.setTitle(“”);
      •   Empty title → error message: “Title cannot be empty.”
    • invalidBook.setAuthor(“”);
      • Empty author → error message: “Author cannot be empty.”
    • invalidBook.setPrice(-10);
      •   Negative price → error message: “Price must be greater than 0.”
  • Display Second Book Details:
    • invalidBook.displayDetails();
        Prints default (null/0.0) values:
      Title: null, Author: null, Price: $0.0
  • End Program

Program :

    class Book {
    private String title;
    private String author;
    private double price;
    public void setTitle(String title) {
        if (title != null && !title.trim().isEmpty()) this.title = title;
        else System.out.println(“Title cannot be empty.”);
    }
    public void setAuthor(String author) {
        if (author != null && !author.trim().isEmpty()) this.author = author;
        else System.out.println(“Author cannot be empty.”);
    }
    public void setPrice(double price) {
        if (price > 0) this.price = price;
        else System.out.println(“Price must be greater than 0.”);
    }
    public String getTitle() {
         return title;
    }
    public String getAuthor() {
       return author;
     }
    public double getPrice() {
         return price;
      }
    public void displayDetails() {
        System.out.println(“Title: ” + title + “, Author: ” + author + “, Price: $” + price);
    }
}
public class Main {
    public static void main(String[] args) {
        Book book = new Book();
        book.setTitle(“Java Programming”);
        book.setAuthor(“John Doe”);
        book.setPrice(29.99);
        book.displayDetails();
        Book invalidBook = new Book();
        invalidBook.setTitle(“”);
        invalidBook.setAuthor(“”);
        invalidBook.setPrice(-10);
        invalidBook.displayDetails();
    }
}

Output :   

   Title: Java Programming, Author: John Doe, Price: $29.99
    Title cannot be empty.
    Author cannot be empty.
    Price must be greater than 0.
    Title: null, Author: null, Price: $0.0

Explanation :

This Java program defines a Book class with attributes for title, author, and price, along with setter methods that validate input before assigning values. In the main method, a valid book is created and its details are set and displayed correctly. A second book is created with invalid inputs—empty strings and a negative price—triggering validation errors and preventing the values from being set. When its details are displayed, default values (null and 0.0) are shown, demonstrating the importance of input validation in object-oriented programming.

11. Write a program to design a class Employee with private fields employeeId, name, and salary implement encapsulation and write methods to update the employee salary only if the new salary is higher than the old one?

Algorithm :

  • Start the Program – Execution begins in the main method of the Main class.
  • Create an Employee Object:
    • Employee emp = new Employee(101, “John Doe”, 50000);
      → Constructor sets:
      • employeeId = 101
      • name = “John Doe”
      • salary = 50000
  • Display Initial Employee Details:
    • emp.displayDetails();
      → Prints:
      ID: 101, Name: John Doe, Salary: $50000.0
  • Attempt to Update Salary with Lower Value:
    • emp.updateSalary(45000);
      → 45000 is less than current salary → not updated.
      → Prints:
      “New salary must be higher.”
  • Attempt to Update Salary with Higher Value:
    • emp.updateSalary(55000);
      → 55000 is greater than current salary → updated.
      → Prints:
      “Salary updated.”
  • Display Updated Employee Details:
    1. emp.displayDetails();
      → Prints:
      ID: 101, Name: John Doe, Salary: $55000.0
  • End Program

Program :

class Employee {
    private int employeeId;
    private String name;
    private double salary;
    public Employee(int employeeId, String name, double salary) {
        this.employeeId = employeeId;
        this.name = name;
        this.salary = salary;
    }
    public void updateSalary(double newSalary) {
        if (newSalary > salary) {
            salary = newSalary;
            System.out.println(“Salary updated.”);
        } else {
            System.out.println(“New salary must be higher.”);
        }
    }
    public void displayDetails() {
        System.out.println(“ID: ” + employeeId + “, Name: ” + name + “, Salary: $” + salary);
    }
}
public class Main {
    public static void main(String[] args) {
        Employee emp = new Employee(101, “John Doe”, 50000);
        emp.displayDetails();
        emp.updateSalary(45000);  // Invalid
        emp.updateSalary(55000);  // Valid
        emp.displayDetails();
    }
}

Output :

     ID: 101, Name: John Doe, Salary: $50000.0
     New salary must be higher.
     Salary updated.
     ID: 101, Name: John Doe, Salary: $55000.0

Explanation :

                      This Java program defines an Employee class that stores employee details and allows salary updates only if the new salary is higher than the current one. In the main method, an employee object is created with an initial salary of 50,000. When attempting to update the salary with a lower amount (45,000), the update is rejected with a message. A subsequent attempt with a higher salary (55,000) succeeds, and the updated details are displayed. This illustrates conditional logic for safely updating class attributes.

12. Write a class Library with private fields bookName, author, and availabilityStatus implement encapsulation and a method to mark a book as checked out or returned?

Algorithm :

  • Start Program – Execution begins in the main method of the Main class.
  • Create a Book Object:
    • Library book = new Library(“Java Programming”, “John Doe”, true);
    • Initializes:
      • bookName = “Java Programming”
      • author = “John Doe”
      • availabilityStatus = true (book is available)
  • Display Book Details:
    • book.displayDetails();
      Prints:
      Java Programming by John Doe – Available
  • First Checkout Attempt:
    • book.checkOut();
      Book is available → sets availabilityStatus to false
      Prints:
      “Java Programming checked out.”
  • Second Checkout Attempt:
    • book.checkOut();
      Book is already checked out (availabilityStatus = false)
      Prints:
      “Java Programming already checked out.”
  • First Return Attempt:
    • book.returnBook();
      Book is currently checked out → sets availabilityStatus to true
      Prints:
      “Java Programming returned.”
  • Second Return Attempt:
    • book.returnBook();
      Book is already available (availabilityStatus = true)
      Prints:
      “Java Programming was not checked out.”
  • Display Final Book Details:
    • book.displayDetails();
      Prints:
      Java Programming by John Doe – Available
  • End Program

Program :

    class Library {
    private String bookName;
    private String author;
    private boolean availabilityStatus;
    public Library(String bookName, String author, boolean availabilityStatus) {
        this.bookName = bookName;
        this.author = author;
        this.availabilityStatus = availabilityStatus;
    }
    public void checkOut() {
        if (availabilityStatus) {
            availabilityStatus = false;
            System.out.println(bookName + ” checked out.”);
        } else {
            System.out.println(bookName + ” already checked out.”);
        }
    }
    public void returnBook() {
        if (!availabilityStatus) {
            availabilityStatus = true;
            System.out.println(bookName + ” returned.”);
        } else {
            System.out.println(bookName + ” was not checked out.”);
        }
    }
    public void displayDetails() {
        System.out.println(bookName + ” by ” + author + ” – ” + (availabilityStatus ? “Available” : “Checked Out”));
    }
}
public class Main {
    public static void main(String[] args) {
        Library book = new Library(“Java Programming”, “John Doe”, true);
        book.displayDetails();
        book.checkOut();
        book.checkOut();  // Already checked out
        book.returnBook();
        book.returnBook();  // Already returned
        book.displayDetails();
    }
}

Output :       

Java Programming by John Doe – Available
Java Programming checked out.
Java Programming already checked out.
Java Programming returned.
Java Programming was not checked out.
Java Programming by John Doe – Available

Explanation :

This Java program defines a Library class that manages a book’s details and its availability status. In the main method, a book titled “Java Programming” is created as available. The book is first checked out successfully, but a second checkout attempt is denied since it’s already checked out. Then, the book is returned, and another return attempt is rejected because it’s already available. The program displays the book’s details before and after these operations, demonstrating how object state is managed through conditional checks on availability.

13. Write a program to create a class MovieTicket with private fields movieName, showTime, and ticketPrice. Write methods to update the ticket price and ensure that the price cannot be negative?

Algorithm :

  • Start Program – Execution begins in the main method of the Main class.
  • Create a MovieTicket Object:
    • MovieTicket ticket = new MovieTicket(“Inception”, “7:00 PM”, 12.50);
    • Constructor sets:
      • movieName = “Inception”
      • showTime = “7:00 PM”
      • Calls setTicketPrice(12.50) → valid → sets ticketPrice = 12.50
  • Display Initial Ticket Details:
    • ticket.displayDetails();
      Prints:
      Movie: Inception, Show Time: 7:00 PM, Ticket Price: $12.5
  • Attempt to Set Invalid Ticket Price:
    • ticket.setTicketPrice(-5);
      → Invalid (negative) → rejected
      → Prints:
      “Ticket price cannot be negative.”
      → ticketPrice remains unchanged.
  • Set Valid Ticket Price:
    1. ticket.setTicketPrice(15.00);
      → Valid → updates ticketPrice to 15.00
  • Display Updated Ticket Details:
    1. ticket.displayDetails();
      → Prints:
      Movie: Inception, Show Time: 7:00 PM, Ticket Price: $15.0
  • End Program

Program :

  class MovieTicket {
    private String movieName;
    private String showTime;
    private double ticketPrice;
    public MovieTicket(String movieName, String showTime, double ticketPrice) {
        this.movieName = movieName;
        this.showTime = showTime;
        setTicketPrice(ticketPrice);
    }
    public void setTicketPrice(double ticketPrice) {
        if (ticketPrice >= 0) this.ticketPrice = ticketPrice;
        else System.out.println(“Ticket price cannot be negative.”);
    }
    public void displayDetails() {
        System.out.println(“Movie: ” + movieName + “, Show Time: ” + showTime + “, Ticket Price: $” + ticketPrice);
    }
}
public class Main {
    public static void main(String[] args) {
        MovieTicket ticket = new MovieTicket(“Inception”, “7:00 PM”, 12.50);
        ticket.displayDetails();
        ticket.setTicketPrice(-5);  // Invalid price
        ticket.setTicketPrice(15.00);  // Valid price
        ticket.displayDetails();
    }
}

Output :

Movie: Inception, Show Time: 7:00 PM, Ticket Price: $12.5
Ticket price cannot be negative.
Movie: Inception, Show Time: 7:00 PM, Ticket Price: $15.0

Explanation :

The program defines a MovieTicket class with private fields for movie name, show time, and ticket price. It includes a constructor to initialize these fields and uses the setTicketPrice method to ensure the ticket price is not negative. If a negative price is provided, an error message is printed instead of updating the price. The displayDetails method prints the ticket’s details in a formatted string. In the Main class, a MovieTicket object is created with valid values, and its details are displayed. The ticket price is then updated twice—first with an invalid value (which is rejected), and then with a valid one—before displaying the updated details.

14. Write a program to design a class ShoppingCart where private fields represent items and totalPrice implement encapsulation with methods to add items and update the total price, ensuring no negative price is added?

Algorithm :

  • Start Program – Execution begins in the main method of the Main class.
  • Create a ShoppingCart Object:
    • ShoppingCart cart = new ShoppingCart();
    • Initializes:
      • An empty items list.
      • totalPrice = 0.0
  • Add First Item:
    • cart.addItem(“Laptop”,800);
    • Price is valid → adds “Laptop” to list, updates totalPrice to 800.
    • Prints:
      “Laptop added. Price: $800.0”
  • Add Second Item:
    • cart.addItem(“Headphones”, 50);
    • Price is valid → adds “Headphones”, totalPrice = 850.
    • Prints:
      “Headphones added. Price: $50.0”
  • Attempt to Add Item with Invalid Price:
    • cart.addItem(“Keyboard”, -30);
    • Price is negative → rejected.
    • Prints:
      “Cannot add item with negative price: Keyboard”
  • Add Fourth Item:
    • cart.addItem(“Mouse”, 20);
    • Price is valid → adds “Mouse”, totalPrice = 870.
    • Prints:
      “Mouse added. Price: $20.0”
  • Display Cart Contents:
    1. cart.displayCart();
    1. Prints:
      Items: [Laptop, Headphones, Mouse]
      Total: $870.0
  • End Program

Program :

    import java.util.ArrayList;
    class ShoppingCart {
    private ArrayList<String> items = new ArrayList<>();
    private double totalPrice = 0.0;
    public void addItem(String item, double price) {
        if (price >= 0) {
            items.add(item);
            totalPrice += price;
            System.out.println(item + ” added. Price: $” + price);
        } else {
            System.out.println(“Cannot add item with negative price: ” + item);
        }
    }
    public void displayCart() {
        System.out.println(“Items: ” + items);
        System.out.println(“Total: $” + totalPrice);
    }
}
public class Main {
    public static void main(String[] args) {
        ShoppingCart cart = new ShoppingCart();
        cart.addItem(“Laptop”, 800);
        cart.addItem(“Headphones”, 50);
        cart.addItem(“Keyboard”, -30);  // Invalid price
        cart.addItem(“Mouse”, 20);
        cart.displayCart();
    }
}

Output :  

Laptop added. Price: $800.0
Headphones added. Price: $50.0
Cannot add item with negative price: Keyboard
Mouse added. Price: $20.0
Items: [Laptop, Headphones, Mouse]
Total: $870.0

Explanation :

This Java program defines a ShoppingCart class that allows items to be added with their prices and displays the total. Items with valid (non-negative) prices are added to the cart and contribute to the total price. In the main method, several items are added, including an invalid one with a negative price, which is rejected. Finally, the contents of the cart and the total price are displayed. This program demonstrates basic list operations, price validation, and accumulation of values.

15. Write a class Address with private fields street, city, and zipcode. Implement encapsulation, allowing the address fields to be updated only if the new values are valid?

Algorithm :

  •  Start Program – Execution begins in the main method of the Main class.
  • Create an Address Object:
    • Address address = new Address(“123 Main St”, “Springfield”, “12345”);
    • Sets:
      • street = “123 Main St”
      • city = “Springfield”
      • zipcode = “12345” (validated as 5-digit)
  • Display Initial Address:
    • address.display();
    • Prints:
      123 Main St, Springfield, 12345
  • Attempt to Set Invalid Street:
    • address.setStreet(“”);
    • Empty string → invalid → prints:
      “Street cannot be empty.”
  • Attempt to Set Invalid City:
    • address.setCity(“”);
    • Empty string → invalid → prints:
      “City cannot be empty.”
  • Attempt to Set Invalid Zipcode:
    • address.setZipcode(“1234A”);
    • Not all digits → invalid → prints:
      “Invalid zipcode. Must be 5 digits.”
  • Set Valid Street, City, and Zipcode:
    • address.setStreet(“456 Oak St”); → valid
    • address.setCity(“Greenville”); → valid
    • address.setZipcode(“67890”); → valid
  • Display Updated Address:
    • address.display();
    • Prints:
      456 Oak St, Greenville, 67890
  • End Program

Program :

   class Address {
    private String street, city, zipcode;
    public Address(String street, String city, String zipcode) {
        this.street = street;
        this.city = city;
        setZipcode(zipcode);
    }
    public void setStreet(String street) {
        if (!street.isEmpty()) this.street = street;
        else System.out.println(“Street cannot be empty.”);
    }
    public void setCity(String city) {
        if (!city.isEmpty()) this.city = city;
        else System.out.println(“City cannot be empty.”);
    }
    public void setZipcode(String zipcode) {
        if (zipcode.matches(“\\d{5}”)) this.zipcode = zipcode;
        else System.out.println(“Invalid zipcode. Must be 5 digits.”);
    }
 
    public void display() {
        System.out.println(street + “, ” + city + “, ” + zipcode);
    }
}
public class Main {
    public static void main(String[] args) {
        Address address = new Address(“123 Main St”, “Springfield”, “12345”);
        address.display();
        address.setStreet(“”);  // Invalid
        address.setCity(“”);    // Invalid
        address.setZipcode(“1234A”); // Invalid
        address.setStreet(“456 Oak St”);
        address.setCity(“Greenville”);
        address.setZipcode(“67890”);
        address.display();
    }
}

Output :   

123 Main St, Springfield, 12345
 Street cannot be empty.
 City cannot be empty.
 Invalid zipcode. Must be 5 digits.
 456 Oak St, Greenville, 67890

Explanation :

This Java program defines an Address class that validates inputs for street, city, and zipcode. A valid address is created and displayed initially. Attempts to set empty street and city names or an invalid zipcode format are rejected with error messages. Valid updates to all fields are then accepted, and the updated address is displayed. The program highlights input validation using string checks and regex, ensuring data integrity in object properties.

Leave a Reply

Your email address will not be published. Required fields are marked *