- Java: Library class with add and remove books methods
- Java: Tips of the Day
- Using Java Libraries
- Builder vs. User
- What’s in the Java SDK?
- Using a Java class
- The import statement
- API descriptions
- How to use static fields and methods
- Example: the java.lang.Math library
- How to use instance fields and methods
- Example: the java.util.Random library
Java: Library class with add and remove books methods
Write a Java program to create a class called «Library» with a collection of books and methods to add and remove books.
Sample Solution:
//Book.java public class Book < private String title; private String author; public Book(String title, String author) < this.title = title; this.author = author; >public String getTitle() < return title; >public void setTitle(String title) < this.title = title; >public String getAuthor() < return author; >public void setAuthor(String author) < this.author = author; >>
The above class has two private attributes, «title» and «author». It has a constructor that takes two arguments, the title and author of the book, and initializes the corresponding attributes. It also has getter and setter methods to access and modify the title and author attributes.
//Library.java import java.util.ArrayList; public class Library < private ArrayList < Book >books; public Library() < books = new ArrayList < Book >(); > public void addBook(Book book) < books.add(book); >public void removeBook(Book book) < books.remove(book); >public ArrayList < Book >getBooks() < return books; >>
The above “Library” class has a private books attribute, which is an ArrayList of Book objects. The Library constructor initializes this attribute as an empty list. The “addBook()” method adds a Book object to the books list, while the “removeBook()” method removes a Book object from the list. The “getBooks()” method returns the books list.
//Main.java public class Main < public static void main(String[] args) < Library library = new Library(); Book book1 = new Book("Adventures of Tom Sawyer", "Mark Twain"); Book book2 = new Book("Ben Hur", "Lewis Wallace"); Book book3 = new Book("Time Machine", "H.G. Wells"); Book book4 = new Book("Anna Karenina", "Leo Tolstoy"); library.addBook(book1); library.addBook(book2); library.addBook(book3); library.addBook(book4); System.out.println("Books in the library:"); for (Book book: library.getBooks()) < System.out.println(book.getTitle() + " by " + book.getAuthor()); >library.removeBook(book2); System.out.println("\nBooks in the library after removing " + book2.getTitle() + ":"); for (Book book: library.getBooks()) < System.out.println(book.getTitle() + " by " + book.getAuthor()); >> >
In the above class, we create an instance of the Library class and add two Book objects to the collection using the “addBook()” method. We then display the books in the library using the “displayBooks()” method. We remove one of the books using the “removeBook()” method and display the updated collection of books in the library.
Books in the library: Adventures of Tom Sawyer by Mark Twain Ben Hur by Lewis Wallace Time Machine by H.G. Wells Anna Karenina by Leo Tolstoy Books in the library after removing Ben Hur: Adventures of Tom Sawyer by Mark Twain Time Machine by H.G. Wells Anna Karenina by Leo Tolstoy
Java Code Editor:
Improve this sample solution and post your code through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource’s quiz.
Follow us on Facebook and Twitter for latest update.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook
Using Java Libraries
While there are still a number of fundamental basic programming concepts still to be covered, we would also like to be able to start using existing libraries in the Java SDK as quickly as possible. To that aim, this outline will provide «just enough» to illustrate basic core usage of existing Java class libraries.
Builder vs. User
- the builder is responsible for declaring and defining how some module works
- the user (or caller) is somebody (i.e. some portion of code, often some other module) that makes use of an existing module to perform a task.
We will look at how to build things like functions, classes, interfaces, etc. later on.
What’s in the Java SDK?
- There are mulitple kinds of library constructs to consider, including:
- classes
- interfaces
- packages
- classes and interfaces with generic type parameters
- java.lang
- java.util
- java.util.concurrent
- java.lang.String
- java.util.Scanner
- fields (i.e. data variables)
- methods (i.e. member functions)
Using a Java class
The import statement
- If you are using any item from the package java.lang, you don’t need to do anything special. Everything from java.lang is automatically imported for use into every Java program you write
- For a class out of any other package, you need to put an import statement at the top of your file, to let the Java tools (compiler and loader) know what libraries to pull in
- Basic form:
import java.util.Scanner; import javax.swing.JFrame; import java.awt.geom.GeneralPath;
import javax.swing.*; // imports all classes in javax.swing package import java.util.*; // imports all classes in java.util package
API descriptions
- The API description for a Java class gives all of the information you need to be able to syntactically use it correctly
- Starts with description of the class, in a general documentation format
- Field Summary
- This section lists data fields that you might want to use
- Often, these are constants, but not always
- This chart lists the variable names, descriptions, and their types
- This section lists the constructor methods that are available for this class
- Constructors are related to the creation of objects
- This chart provides the parameter list for each constructor option
- This section lists the methods that are available for this class
- For general class usage, this will typically be the most relevant set of features that you will want to call upon
- This chart provides the full prototype, or declaration, of each method
- first column shows the return type, and whether the method is static or not (more on this later)
- Second column provides method name, as well as list of expected parameters, and a short description
- class java.lang.String
How to use static fields and methods
- Some fields and methods are declared as static
- In the Field Summary and/or Method Summary, this information would show up in the left column
- If a variable or method is not declared with the word static, then we call it an instance variable or method
- To call upon variables or methods from a class, we use the dot-operator syntax. There is a difference between static and instance items, though
- For a static variable or method, we use this format:
className.fieldName // fields className.methodName(arguments) // methods
Example: the java.lang.Math library
- API: java.lang.Math
- Note that all fields and methods in this class are static
- class Math has two fields, which are common mathematical constants. Sample usage:
double area = Math.PI * radius * radius; // compute area of a circle
area = Math.PI * Math.pow(radius, 2); // area of circle, using power method y = Math.abs(x); // computes absolute value of x System.out.print(Math.random()); // prints random value in range [0,1) int die = (int)(Math.random() * 6) + 1; // roll a standard 6-sided die
How to use instance fields and methods
- Recall that an instance field or method is one that is not declared to be static. Instance is the default
- To call upon instance fields or methods in a class library, you have to create one or more objects from that class
- A class is a blueprint for building objects.
className variableName = new className( parameter(s) );
className variableName
Scanner input = new Scanner(System.in); JButton myButton = new JButton("Click Me"); String s1 = new String();
objectName.fieldName // fields objectName.methodName(arguments) // methods
int x = input.nextInt(); myButton.setText("Stop clicking me!"); System.out.print(s1.toUpperCase());
Example: the java.util.Random library
- API: java.util.Random
- This library is for generating pseudo-random numbers
- How computers do «random» number generation
- It’s really a «pseudo-random» generator
- Start with a «seed» value
- The seed is used as the input to an algorithm, which generates a seemingly randomized number
- Each «random» value generated becomes the seed for the next one
- Start with the same seed, and you’ll get the same random numbers!
Random r1 = new Random(); // uses the system time to create seed Random r2 = new Random(1234); // uses 1234 as the seed
int x = r1.nextInt(); // gets a random integer int y = r1.nextInt(10); // gets a random integer from 0-9 double z = r1.nextDouble(); // gets a random double in range [0,1)