# Operators

Course: [Dart](https://www.devtutorials.ai/learn/dart) · Section: Operators
Source: https://www.devtutorials.ai/learn/dart/operators-and-null-safety/operators

> Arithmetic, increment, comparison, logical, assignment, type and bitwise operators, the ternary operator, and the order Dart works them out.

## What Is an Operator?

**Operator** = a symbol that does something with values.

For example:

- `+` adds two numbers
- `>` compares two numbers
- `&&` joins two conditions
- `=` puts a value into a variable

**Operand** = a value an operator works on. In `5 + 3`, the operands are `5` and `3`.

**Simple lesson:** operators are the action symbols of Dart, like the buttons on a calculator.

### A Real-World Example

The class teacher shares 47 chocolates among 6 students.

- **How many does each student get?** 47 divided by 6, whole chocolates only: `7`.
- **How many are left over?** The remainder: `5`.
- **Does everyone get at least 5?** A comparison: `7 >= 5` is `true`.

Each question uses a different operator. This lesson covers all of them.

Every **Run** box on this page runs on the course's Dart runner in your browser.

Try changing the numbers and running again.

## What You Will Learn

In this lesson, you will learn:

1. Arithmetic operators, including `~/` and `%`.
2. Increment and decrement: `++` and `--`.
3. Comparison and logical operators.
4. Assignment, type and bitwise operators, and the ternary operator `?:`.
5. The order in which Dart works out operators.

## Arithmetic Operators

| Operator | Meaning | Example | Result |
|---|---|---|---|
| `+` | add | `17 + 5` | `22` |
| `-` | subtract | `17 - 5` | `12` |
| `*` | multiply | `17 * 5` | `85` |
| `/` | divide | `17 / 5` | `3.4` |
| `~/` | divide, keep the whole part | `17 ~/ 5` | `3` |
| `%` | remainder (modulus) | `17 % 5` | `2` |

```dart runnable title="The six arithmetic operators"
void main() {
  int a = 17;
  int b = 5;
  print(a + b);
  print(a - b);
  print(a * b);
  print(a / b);
  print(a ~/ b);
  print(a % b);
}
```

### Division Always Gives a double

- `/` always gives a `double`, even for two `int`s.
- `10 / 2` gives `5.0` in real Dart, not `5`.
- Use `~/` when you want a whole number.

### Integer Division and Modulus

**Integer division (`~/`)** = divide, and throw away the decimal part.

**Modulus (`%`)** = the remainder left after dividing.

```dart runnable title="Sharing chocolates fairly"
void main() {
  int chocolates = 47;
  int students = 6;
  int each = chocolates ~/ students;
  int left = chocolates % students;
  print('Each student gets $each chocolates.');
  print('$left chocolates are left over.');
}
```

`%` is very useful:

- `n % 2 == 0` tells you `n` is **even**.
- `minutes % 60` gives the minutes left after full hours.

**Simple lesson:** `/` gives a decimal answer, `~/` gives the whole part, and `%` gives the remainder.

## Unary Operators

**Unary operator** = an operator that works on just **one** value.

- **`++`** = add 1. `count++` is the same as `count = count + 1`.
- **`--`** = take away 1. `count--` is the same as `count = count - 1`.
- **`-`** in front of a value makes it negative: `-temperature`.

### Prefix and Postfix

The position of `++` matters when you **use** the value in the same line.

- **Postfix `i++`** = use the old value first, then add 1.
- **Prefix `++i`** = add 1 first, then use the new value.

On a line by itself, `i++` and `++i` do the same thing.

The difference matters only when the same line also uses the value.

**Simple lesson:** `++` adds 1 and `--` subtracts 1, and putting them first means "change, then use".

## Relational Operators

**Relational operator** = compares two values and gives `true` or `false`.

| Operator | Question | Example | Result |
|---|---|---|---|
| `==` | equal? | `80 == 80` | `true` |
| `!=` | not equal? | `80 != 75` | `true` |
| `>` | greater? | `80 > 90` | `false` |
| `<` | less? | `80 < 90` | `true` |
| `>=` | greater or equal? | `35 >= 35` | `true` |
| `<=` | less or equal? | `36 <= 35` | `false` |

```dart runnable title="Comparing marks"
void main() {
  var marks = 72;
  var passMark = 35;
  print(marks > passMark);
  print(marks == 100);
  print(marks != 100);
  print(marks >= 72);
  print('Asha' == 'Asha');
}
```

`=` and `==` are different.

- `=` **puts** a value into a variable.
- `==` **asks** whether two values are equal.

**Simple lesson:** relational operators ask a yes-or-no question about two values.

## Logical Operators

**Logical operator** = joins or flips `true` and `false` values.

- **`&&` (AND)** = `true` only when **both** sides are `true`.
- **`||` (OR)** = `true` when **at least one** side is `true`.
- **`!` (NOT)** = flips `true` to `false`, and `false` to `true`.

Click both switches and compare:

- **`&&`** turns green only when both switches are `true`.
- **`||`** turns red only when both switches are `false`.

```dart runnable title="Can the student enter the exam hall?"
void main() {
  bool hasHallTicket = true;
  bool hasIdCard = false;
  bool isLate = false;

  print(hasHallTicket && hasIdCard);
  print(hasHallTicket || hasIdCard);
  print(!isLate);
  print(hasHallTicket && !isLate);
}
```

### Short-Circuit Evaluation

**Short-circuit** = Dart stops as soon as it knows the answer.

- In `a && b`, if `a` is `false`, Dart never checks `b`.
- In `a || b`, if `a` is `true`, Dart never checks `b`.

**Simple lesson:** `&&` needs both, `||` needs one, and `!` flips the answer.

## Assignment Operators

**Compound assignment** = do a calculation and store the answer in the same variable.

| Operator | Same as | Example |
|---|---|---|
| `=` | put a value in | `points = 10` |
| `+=` | `points = points + n` | `points += 5` |
| `-=` | `points = points - n` | `points -= 2` |
| `*=` | `points = points * n` | `points *= 3` |
| `/=` | `amount = amount / n` | `amount /= 2` (only for `double`) |
| `~/=` | `points = points ~/ n` | `points ~/= 4` |
| `%=` | `points = points % n` | `points %= 5` |

```dart runnable title="House points during sports day"
void main() {
  int points = 10;
  points += 5;
  print('After the race: $points');
  points -= 2;
  print('After a foul: $points');
  points *= 3;
  print('Triple bonus: $points');
  points ~/= 4;
  print('Shared by 4: $points');
  points %= 5;
  print('Remainder: $points');

  double prize = 125.5;
  prize /= 2;
  print('Half the prize: $prize');
}
```

`/=` needs a `double` variable, because `/` always gives a `double`.

**Simple lesson:** `x += 5` is a short way to write `x = x + 5`.

## Type Operators

You met these in **Data Types**:

- **`is`** = "is it this type?" gives `true` or `false`.
- **`is!`** = "is it NOT this type?"
- **`as`** = "treat it as this type" (check with `is` first).

```dart runnable title="Type operators"
void main() {
  dynamic value = 'Pune';
  print(value is String);
  print(value is! int);
  String city = value as String;
  print(city.length);
}
```

**Simple lesson:** `is` and `is!` ask about a type, and `as` treats a value as a type.

## Bitwise Operators

**Bit** = a single 0 or 1. Computers store every number as bits.

`5` is `101` in bits, and `3` is `011`.

| Operator | Name | Example | Result |
|---|---|---|---|
| `&` | AND each bit | `5 & 3` | `1` |
| `\|` | OR each bit | `5 \| 3` | `7` |
| `^` | XOR each bit | `5 ^ 3` | `6` |
| `~` | flip every bit | `~5` | `-6` |
| `<<` | shift left | `1 << 3` | `8` |
| `>>` | shift right | `16 >> 2` | `4` |
| `>>>` | shift right, fill with 0 | `16 >>> 2` | `4` |

```dart runnable title="Bitwise operators"
void main() {
  print(5 & 3);
  print(5 | 3);
  print(5 ^ 3);
  print(1 << 3);
  print(16 >> 2);
}
```

- `1 << 3` is `1` doubled three times: `8`.
- `16 >> 2` is `16` halved two times: `4`.

You will rarely need these as a beginner. They are used for flags, colours and fast maths.

**Simple lesson:** bitwise operators work on the 0s and 1s inside a number.

## The Conditional Operator

**Ternary operator (`?:`)** = a one-line if-else that gives a value.

```text
condition ? valueIfTrue : valueIfFalse
```

```dart runnable title="Pass or fail in one line"
void main() {
  var marks = 28;
  var result = marks >= 35 ? 'Pass' : 'Fail';
  print('Result: $result');

  var age = 15;
  print(age >= 18 ? 'Can vote' : 'Too young to vote');
}
```

Read it as a question: "Is `marks >= 35`? If yes, `'Pass'`, otherwise `'Fail'`."

You will use it again in **Conditional Statements**.

Dart also has the **cascade operator** `..`, which calls many methods on one object.

It needs objects, so you will learn it in **Classes**.

**Simple lesson:** `?:` picks one of two values, based on a condition.

## Operator Precedence

**Precedence** = the order in which Dart works out operators in one expression.

It is like BODMAS in maths: multiplication before addition.

From first to last, the most common ones:

1. `()` brackets
2. `!`, `-x`, `++`, `--`
3. `*`, `/`, `~/`, `%`
4. `+`, `-`
5. `<`, `>`, `<=`, `>=`, then `==`, `!=`
6. `&&`, then `||`
7. `?:`, then `=`, `+=` and the other assignments

```dart runnable title="Brackets change the answer"
void main() {
  print(2 + 3 * 4);
  print((2 + 3) * 4);
  print(100 - 20 - 5);
  print(10 > 5 && 3 > 4 || true);
}
```

- `2 + 3 * 4` is `14`, because `*` goes first.
- `(2 + 3) * 4` is `20`, because brackets go first.

**Easy way to remember**

When in doubt, add brackets.

They make the order clear to Dart, and to everyone who reads your code.

**Simple lesson:** Dart follows BODMAS-like rules, and brackets always go first.

## TL;DR

1. **Arithmetic** = `+ - * /`, plus `~/` (whole part) and `%` (remainder).
   - `/` always gives a `double`.
2. **`++` and `--`** = add or subtract 1. Prefix changes first, postfix uses first.
3. **Comparison** = `== != > < >= <=`, giving `true` or `false`.
   - **Logical** = `&&` (both), `||` (at least one), `!` (flip).
4. **Assignment** = `=`, and short forms like `+=`.
   - **Type** = `is`, `is!`, `as`. **Bitwise** = `& | ^ ~ << >> >>>`.
5. **Ternary** = `condition ? a : b`. **Precedence** = brackets first, then `*` before `+`.

## Common mistakes

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| `=` instead of `==` | Both compare | `==` compares, `=` assigns | A wrong result, or an error. |
| `/` for whole numbers | `7 / 2` is `3` | `7 / 2` is `3.5`. Use `~/` for `3` | A `double` where an `int` was needed. |
| `int x` with `/=` | All ints can use `/=` | `/=` makes a `double` | A type error. |
| Forgetting precedence | `2 + 3 * 4` is `20` | `*` comes first, so it is `14` | A wrong answer. |
| `print(i++)` expecting the new value | `++` always changes first | Postfix uses the old value first | An off-by-one output. |
| `&` instead of `&&` | They are the same | `&&` joins conditions, `&` works on bits | Confusing results. |
| A long chain of `?:` | Ternaries replace if-else | Use if-else for more than two choices | Code nobody can read. |

## Check Yourself

## Exercises

## What to Remember

- `/` always gives a `double`. `~/` gives the whole part, and `%` gives the remainder.
- `++` and `--` change a value by 1. Prefix changes first, postfix uses first.
- `==` compares, and `=` assigns. `&&` needs both sides, `||` needs one.
- `x += 5` is short for `x = x + 5`.
- `condition ? a : b` picks a value, and brackets control the order of work.

Next: **Null Safety**. You will learn how Dart protects you from the "empty box" crash.
