codegurukool.com · Free coding tutorials & online compiler

Home › Java Tutorial › Live project: Library books

Live project: Library books

Borrow books using classes and lists.

Use classes, objects, ArrayList and methods to model a small library.

What you will build

Steps

  1. Read the Book class.
  2. Read borrow: it loops through the shelf.
  3. Press Run and read the messages.
  4. Add more books and borrow them.

Run it

Press Run to see the project work. Then change the data in the editor and run it again.

Challenge

Example code

import java.util.ArrayList;

class Main {
  static void borrow(ArrayList<Book> shelf, String title) {
    for (Book b : shelf) {
      if (b.title.equals(title)) {
        if (b.available) {
          b.available = false;
          System.out.println("Borrowed: " + title);
        } else {
          System.out.println("Already borrowed: " + title);
        }
        return;
      }
    }
    System.out.println("Not found: " + title);
  }

  public static void main(String[] args) {
    ArrayList<Book> shelf = new ArrayList<>();
    shelf.add(new Book("Java Basics"));
    shelf.add(new Book("Data Structures"));
    borrow(shelf, "Java Basics");
    borrow(shelf, "Java Basics");
    borrow(shelf, "Algorithms");
    int free = 0;
    for (Book b : shelf) if (b.available) free++;
    System.out.println("Available books: " + free);
  }
}

class Book {
  String title;
  boolean available = true;
  Book(String title) { this.title = title; }
}

Run this code in the online editor

← Java project: grade report