See, that was easy. Don't doubt yourself!
Back to our sandwich software, we want to calculate the total cost for a customer when they purchase multiple quantities of the same product.
Let's say a group of 4 friends go out and purchase the same sandwich for lunch. Instead of doing this:
Integer sandwichPrice = 7; Integer totalPrice = sandwichPrice + sandwichPrice + sandwichPrice + sandwichPrice;
We can use multiplication to make this more succinct. Apex uses the *
operator for multiplication. Let’s try it out:
Integer sandwichPrice = 7; Integer quantity = 4; Integer totalCost = sandwichPrice * quantity; // totalCost is now set to 28
Let’s say another group of 3 friends wants to split their bill evenly. Apex provides the /
operator for division. We can use this to divide the total price by the number of friends. The code would look something like this:
Integer totalPrice = 120; Integer numberOfFriends = 3; Integer pricePerFriend = totalPrice / numberOfFriends; // pricePerFriend is now 40
Here are a few more examples of multiplication and division in action.
Integer yearlyRentCost = 12 * 1000; Integer monthlyRentCost = yearlyRentCost / 12; //get 1000 again Integer hourlyRate = 20; Integer hoursPerWeek = 40; Integer weeklyPay = hourlyRate * hoursPerWeek;