Chapter 4 - Java for Beginners Course

Adding money

Based on our vending machine description, we should only allow customers to add money up to a maximum balance of 100. Any attempt to add money above that balance should not be accepted (or in real life, assume the coin will just fall-through).

In that sense, we can add an addMoney(int amountToAdd) method into our UnlimitedSupplyVendingMachine class, where the amountToAdd parameter would be the money inserted by the customer into the vending machine:

public void addMoney(int amountToAdd) {
    // only add the money to the balance if it doesn't exceed the allowed maximum
    if (balance + amountToAdd <= maxAllowedBalance) {
        balance += amountToAdd;
    }
}

Our boolean expression in this case for our if statement is balance + amountToAdd <= maximumBalance. Basically, we are checking if by adding the new amount (amountToAdd) to our current balance, would exceed the maximum allowed balance.

If it doesn’t exceed the maximum allowed balance (i.e. if the condition is true), then we update our current balance by adding the amountToAdd. Otherwise, if the condition is false, the balance will remain unchanged.

Let’s create an UnlimitedSupplyVendingMachine object and give this a try:

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

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

// By adding 20, our new balance would not exceed the max allowed balance, so the condition is true
vendingMachine.addMoney(20);
// we expect a balance of 20 as it doesn't exceed the max allowed balance
System.out.println("Balance after first addition of money: " + vendingMachine.getBalance());

// By adding 90, our new balance would exceed the max allowed balance, so the addition shouldn't occur
vendingMachine.addMoney(90);
// we still expect a balance of 20.
System.out.println("Balance after second addition of money: " + vendingMachine.getBalance());

Output:

Initial balance: 0
Balance after first addition of money: 20
Balance after second addition of money: 20

Analysing the first addMoney call

When we invoke vendingMachine.addMoney(20), the condition in the if statement is:

  1. balance + amountToAdd <= maxAllowedBalance, where balance is 0, amountToAdd is 20 and maxAllowedBalance is 100.

  2. This means that we are checking if 0 + 20 <= 100 which is true, 20 is less or equal than 100.

As the condition is true, the balance += amountToAdd; line is executed and our balance field is set to 20.

Analysing the second addMoney call

When we invoke vendingMachine.addMoney(90), the condition in the if statement is:

  1. balance + amountToAdd <= maxAllowedBalance, where balance is 20, amountToAdd is 90 and maxAllowedBalance is 100.

  2. This means that we are checking if 20 + 90 <= 100 which is false, 110 is not less or equal than 100.

As the condition is false, the balance += amountToAdd; line is not executed and our balance remains unchanged.

We’ll continue adding functionality to our UnlimitedSupplyVendingMachine class in the next sections to illustrate more types of if statements.
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