11. Write a Java program to create a class called "Library" with a collection of books and methods to add and remove books.
import java.util.ArrayList;
import java.util.List;
class Library {
private List books;
public Library() {
books = new ArrayList<>();
}
// Method to add a book to the library
public void addBook(String book) {
books.add(book);
System.out.println("Book added: " + book);
}
// Method to remove a book from the library
public void removeBook(String book) {
if (books.contains(book)) {
books.remove(book);
System.out.println("Book removed: " + book);
} else {
System.out.println("Book not found: " + book);
}
}
// Method to display all books in the library
public void displayBooks() {
if (books.isEmpty()) {
System.out.println("No books in the library.");
} else {
System.out.println("Books in the library:");
for (String book : books) {
System.out.println("- " + book);
}
}
}
}
public class LibraryManagement {
public static void main(String[] args) {
Library library = new Library();
// Adding books to the library
library.addBook("The Great Gatsby");
library.addBook("To Kill a Mockingbird");
library.addBook("1984");
// Displaying all books
library.displayBooks();
// Removing a book from the library
library.removeBook("1984");
// Displaying all books after removal
library.displayBooks();
// Trying to remove a book that doesn't exist
library.removeBook("Moby Dick");
}
}
OUTPUT
Book added: The Great Gatsby
Book added: To Kill a Mockingbird
Book added: 1984
Books in the library:
- The Great Gatsby
- To Kill a Mockingbird
- 1984
Book removed: 1984
Books in the library:
- The Great Gatsby
- To Kill a Mockingbird
Book not found: Moby Dick