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?
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) { // Create an Employee object Employee emp = new Employee(); // Set values using setter methods emp.setName(“John Doe”); emp.setAge(30); emp.setSalary(50000); emp.setAge(-5); emp.setSalary(-2000); emp.displayEmployeeDetails(); } } |
Output :
Employee Name: John Doe Employee Age: 30 Employee Salary: 50000.0 Age must be a positive integer. Salary cannot be negative. |
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?
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 |
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)?
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); } 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 |
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?
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) { Rectangle rect = new Rectangle(5, 10); rect.displayDetails(); Rectangle invalidRect = new Rectangle(-5, -10); } } |
Output :
Width: 5.0 Height: 10.0 Area: 50.0 Perimeter: 30.0 Width must be positive. Height must be positive. |
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?
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); } 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(); } } |
Output :
Product ID: 101 Product Name: Laptop Price: $899.99 Price cannot be negative. Product ID: 102 Product Name: Smartphone Price: $0.0 |
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?
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. |
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?
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 |
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 ?
class Car { private String model; private int year; private double price; 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) { Car car = new Car(“Toyota Corolla”, 2020, 20000); car.displayDetails(); car.updatePrice(22000, “guest”); car.updatePrice(22000, “admin”); 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 |
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?
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”); customer.updateAddress(101, “456 Elm St”); 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 |
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?
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 |
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?
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); emp.updateSalary(55000); 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 |
12. Write a program to create a class Library with private fields bookName, author, and availabilityStatus. Implement encapsulation and a method to mark a book as checked out or returned?
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(); book.returnBook(); book.returnBook(); 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 |
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?
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); ticket.setTicketPrice(15.00); 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 |
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?
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); 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 |
15. Write a program to create 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?
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(“”); address.setCity(“”); address.setZipcode(“1234A”); 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 |