Chapter 4 - Java for Beginners Course

Delivering Items

As our second requirement, we will implement the delivery of items to a customer. Here, we’ll assume the client/user has added some money and presses a button in the vending machine to get an item delivered.

In our previous section, we defined an addMoney(int amountToAdd) method that takes care of updating the current balance that the user has with the vending machine. We’ll use that balance field to check if the user can be delivered an item or not.

We’ll add a deliverItem() method for this purpose. Note though that this method has no parameters as we don’t need any additional input at this stage. All the data or state information that we need is already stored in our UnlimitedSupplyVendingMachine object in our balance field.

public boolean deliverItem() {
    // initially, define that no item has been delivered
    boolean itemDelivered = false;

    if (balance >= costPerItem) {
        // if we have enough balance then deduct the cost of the item
        // from the balance and indicate that the item was delivered
        balance -= costPerItem;
        itemDelivered = true;
    }
    return itemDelivered;
}

The method returns a boolean value, indicating whether the user should get an item (true) or if they didn’t have enough money in their balance and shouldn’t get an item (false).

An alternative way of writing the above method is using an if-else statement:

public boolean deliverItem() {
    if (balance >= costPerItem) {
        // if we have enough balance then deduct the cost of the item
        // from the balance and indicate that the item was delivered
        balance -= costPerItem;
        return true;
    } else {
        return false;
    }
}
The else statement in this particular case could be removed, as in, having the return false; straight after the if block. This is because the if block ends with a return statement so we know that anything after the if block won’t get executed if the condition is true.
In the example class in GitHub you’ll find the second version of the method. This is just to illustrate again that there are different ways of achieving the same result.

Let’s give this a try by creating an UnlimitedSupplyVendingMachine object:

In the example project, run the JavaIfElseStatementApp application.
// create a new vending machine
UnlimitedSupplyVendingMachine vendingMachine = new UnlimitedSupplyVendingMachine();

// our initial balance should be 0
System.out.println("Initial balance: " + vendingMachine.getBalance());

// we haven't added any money yet, so the first delivery attempt should be false
boolean firstDelivery = vendingMachine.deliverItem();
System.out.println("First item delivery attempt: " + firstDelivery);

// Now, let's add 10 to the vending machine
vendingMachine.addMoney(10);
// we expect a balance of 10.
System.out.println("Balance after adding money: " + vendingMachine.getBalance());

// and let's try again to get an item, this time we have enough money:
boolean secondDelivery = vendingMachine.deliverItem();
System.out.println("Second item delivery attempt: " + secondDelivery);

// and let's also check that the balance is updated
System.out.println("Balance after getting the item: " + vendingMachine.getBalance());

Output:

Initial balance: 0
First item delivery attempt: false
Balance after adding money: 10
Second item delivery attempt: true
Balance after getting the item: 0

Analysing the first deliverItem call

The first time we try to get an item, the current balance is 0. In this case, the condition in the method will be false as we’re checking if balance >= costPerItem. Remember that our cost per item is fixed to 10, hence, the condition checks if 0 >= 10, which is false.

This means that our else statement gets executed and the method returns false as the value, and as a result, we get the message First item delivery attempt: false in our output.

Analysing the second deliverItem call

By the time we invoke deliverItem() the second time, we’ve added 10 to the vending machine, meaning that the internal balance field of our vendingMachine object has a value of 10.

In this case, our condition balance >= costPerItem will check if 10 >= 10, which is true, and as a result we deduct 10 from our balance and return true indicating that an item has been delivered.

Code in GitHub

Get the code for this tutorial using the links below.

Project Repo
Download code for this step
Main class for this step
Dependencies

This is a list of recommended tutorials or courses that might be useful before starting this one.

Contents
Welcome to the Course!
Course Introduction
Chapter 1 - Building Blocks
Quick introduction to Java Variables Classes And Objects Class Example - Defining a class Object Examples - Creating instances Java Application Example - Running our first app Accessing class members - The dot operator Packages - Organizing the code
Chapter 2 - Primitives and Operators
Primitives Arithmetic Operators Assignment Operator Unary Operators Equality and Relational Operators Conditional Operators
Chapter 3 - Statements and Control Flow
Expressions Statements If-Then Statement If-Then-Else Statement More If Statements Switch Statement While and Do-While Statements For Statement Branching Statements Exception Handling
Chapter 4 - Code Example
Example Project - A Simple Vending Machine Adding money Delivering Items Giving Change
Chapter 5 - Classes and Interfaces
Introduction Access Level Modifiers Class Declaration - Class, Methods and Fields Class Declaration - Constructors Inheritance Basics Inheritance - Constructors Inheritance - Methods and Fields Polymorphism Abstract Classes and Methods Interfaces Static Class Members Class Composition Final Classes and Class Members Generic Classes
Chapter 6 - Base Object Behaviors
Introduction Type Comparison Type Casting Object Equality - The Contract Object Equality - Common Pitfalls Object String Representation Garbage Collection Object Comparison Primitive Wrappers and Autoboxing
Chapter 7 - Data Structures
Introduction Arrays - Declaration and Creation Arrays - Basic Operations Core Collection Interfaces List and ArrayList - Basic Operations ArrayList Internals Introduction to Hash Tables Map and HashMap - Basic Operations Set and HashSet - Basic Operations
Chapter 8 - Anonymous classes and lambdas
Introduction Filtering a List Anonymous Classes Lambdas Built-in Functional Interfaces
Chapter 9 - Streams
Introduction Creating Streams Intermediate Operations Terminal Operations