Arithmetic Shortcuts
Part of the Fundamentals section of Coddy's Java journey — lesson 19 of 73.
Java created a cool shortcut for self-arithmetic operations.
For example instead of writing:
int a = 5;
a = a + 3; // a holds 8We can simplify it by writing +=:
int a = 5;
a += 3; // a holds 8The += is adding to a itself the value 3
This operation is valid for all arithmetic operations:
| Operator | Shortcut |
|---|---|
| + | += |
| - | -= |
| * | *= |
| / | /= |
| % | %= |
Challenge
BeginnerYou are given a code with initialization of count. (Don't delete this line!)
Your task is to add the following operations, in this order:
- Add
4tocount - Multiply
countby2 - Subtract
1fromcount
Use the arithmetic shortcuts to do so!
Cheat sheet
Java provides shortcut operators for self-arithmetic operations:
| Operator | Shortcut |
|---|---|
| + | += |
| - | -= |
| * | *= |
| / | /= |
| % | %= |
Instead of writing:
int a = 5;
a = a + 3; // a holds 8You can use the shortcut:
int a = 5;
a += 3; // a holds 8Try it yourself
public class Main {
public static void main(String[] args) {
int count = 0;
// Type your code below
// Don't change the line below
System.out.println("count = " + count);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else