Question 5.2: Write a program in Java that follows the specifications as given below.
• Define a class Book as shown in the following figure.
• Create your Main class and the main() method. Define an array of Book type objects of size 5.
• Instantiate these Book objects by taking the inputs from the user.
• Print all Book objects’ data using a static method displayAll().
• Invoke compareTo() method to compare any two Book objects based on their pages. If caller object’s number of
pages is greater than callee object’s number of pages, compareTo() returns 1; if both pages are same, the method
returns 0 and -1 otherwise. Make sure to print the returned value.
• Define a static method isHeavier() within the Main class that takes a Book object as input parameter and returns
true if the Book’s number of pages is greater than 500; false, otherwise. Add appropriate code into your main()
method to demonstrate its functionalities.
Solution:
//Book class
public class Book {
private int ISBN;
private String bookTitle;
private int numberOfPages;
private int count;
Book(int ISBN, String bookTitle, int numberOfPages) {
this.ISBN = ISBN;
this.bookTitle = bookTitle;
this.numberOfPages = numberOfPages;
}
Book() {
}
@Override
public String toString() {
return "ISBN :" + ISBN + "\nBOOK Title :" + bookTitle + "\nNumber Of Pages:" + numberOfPages;
}
int compareTo(Book I) {
if (this.numberOfPages == I.numberOfPages) {
return 0;
} else if (this.numberOfPages > I.numberOfPages) {
return 1;
} else {
return -1;
}
}
public int getCount() {
return count;
}
public int getNumberOfPages() {
return numberOfPages;
}
void displayAll() {
System.out.println("ISBN:" + ISBN);
System.out.println("Book Title:" + bookTitle);
System.out.println("Number Of Pages:" + numberOfPages);
}
}
//Main Class
public class testBook {
public static void main(String[] args) {
Book b1 = new Book(125987136, "The Givers", 121);
Book b2 = new Book(987987136, "Hunger Games", 246);
Book b3 = new Book(654187136, "Shivering", 326);
b1.displayAll();
b2.displayAll();
b3.displayAll();
int data = b1.compareTo(b2);
System.out.println(data);
data = b2.compareTo(b3);
System.out.println(data);
Book[] bookArray = new Book[5];
bookArray[0] = new Book(1, "aa", 423);
bookArray[1] = new Book(2, "bb", 193);
bookArray[2] = new Book(3, "cc", 823);
bookArray[3] = new Book(8, "dd", 443);
bookArray[4] = new Book(6, "ee", 743);
for (int i = 0; i < 5; i++) {
System.out.println(bookArray[i]);
}
}
}