# Operators

Course: [Java](https://www.devtutorials.ai/learn/java) · Section: Getting Started
Source: https://www.devtutorials.ai/learn/java/getting-started/operators

> Use Java's arithmetic, increment, comparison, logical, assignment, ternary, bitwise and shift operators, and learn the order Java follows to evaluate an expression.

Operators are the moving parts of Java. They take values, compare them, change them, and decide what happens next.

Think of them as buttons on a calculator, switches on a control panel, and rules in a decision tree all at once.

Without operators, values just sit there. With operators, they start doing work.

## What You Will Learn

In this lesson, you will learn:

1. What operators, operands, and expressions are.
2. How Java decides which part of an expression runs first.
3. How arithmetic operators work, including `/` and `%`.
4. How `++` and `--` change a value by one.
5. How to compare values and combine conditions.
6. How to update a variable quickly with compound assignment.
7. How to choose between two values with the ternary operator `? :`.
8. How bitwise and shift operators work on the bits of a number.

## Start With a Working Example

Press **Run**.

```java runnable title="Operators build a simple shopping bill"
public class Main {
    public static void main(String[] args) {
        int pens = 4;
        int penPrice = 15;
        int discount = 10;

        int total = pens * penPrice - discount;
        boolean isCheap = total < 100;

        System.out.println("Total: " + total);
        System.out.println("Is it cheap? " + isCheap);
    }
}
```

Expected output:

```text
Total: 50
Is it cheap? true
```

`*` multiplies, `-` subtracts, `<` compares, `=` stores, and `+` joins text with a value.

### Try This

Change `pens` to `8`. Predict both lines before you press Run.

## What Is an Operator?

An **operator** is a symbol that tells Java to do a job on one or more values.

`+` adds. `>` compares. `=` stores. Each one is an operator.

Java groups operators by the job they do:

| Group | Job | Examples |
|---|---|---|
| Arithmetic | Do maths | `+` `-` `*` `/` `%` |
| Increment / decrement | Add or take away 1 | `++` `--` |
| Comparison | Compare two values | `==` `!=` `>` `<` `>=` `<=` |
| Logical | Combine true/false values | `&&` `\|\|` `!` |
| Assignment | Store a value | `=` `+=` `-=` `*=` `/=` `%=` |
| Ternary | Pick one of two values | `? :` |
| Bitwise | Work on single bits | `&` `\|` `^` `~` |
| Shift | Move bits left or right | `<<` `>>` `>>>` |

## Operands and Operators

An **operand** is a value that an operator works on.

In `7 + 3`:

- `+` is the operator;
- `7` and `3` are the operands.

Operators are also grouped by how many operands they need:

- A **unary** operator needs one operand. Example: `-5` or `!isOpen`.
- A **binary** operator needs two operands. Example: `a + b`.
- A **ternary** operator needs three operands. Java has only one: `? :`.

## Expressions

An **expression** is any piece of code that produces a value.

All of these are expressions:

```text
42                      // a literal is an expression
price                   // a variable is an expression
price * 2               // an operator joins values into an expression
(price * 2) + shipping  // expressions can hold smaller expressions
age >= 18               // this one produces true or false
```

A **statement** is a full instruction that ends with `;`. A statement often contains an expression.

```text
int total = price * 2 + shipping;
```

Here the expression is `price * 2 + shipping`. The statement stores its value in `total`.

## Expression Evaluation

**Evaluating** an expression means working out its value.

When an expression has several operators, Java needs to know which one runs first. It follows two rules: **precedence** and **associativity**.

### Precedence

**Precedence** decides which operator goes first.

It works like school maths. Multiplication and division happen before addition and subtraction.

```java runnable title="Multiplication happens before addition"
public class Main {
    public static void main(String[] args) {
        int a = 2 + 3 * 4;
        int b = (2 + 3) * 4;

        System.out.println(a);
        System.out.println(b);
    }
}
```

Expected output:

```text
14
20
```

In the first line, `3 * 4` happens first, giving `12`. Then `2 + 12` gives `14`.

In the second line, the brackets go first. `2 + 3` gives `5`. Then `5 * 4` gives `20`.

Brackets always win. Use them whenever the order is not obvious.

### Associativity

**Associativity** decides the order when two operators have the **same** precedence.

Most operators go from **left to right**.

```java runnable title="Equal precedence runs left to right"
public class Main {
    public static void main(String[] args) {
        System.out.println(20 - 5 - 3);
        System.out.println(40 / 4 * 2);
    }
}
```

Expected output:

```text
12
20
```

`20 - 5 - 3` works as `(20 - 5) - 3`, which is `12`.

`40 / 4 * 2` works as `(40 / 4) * 2`, which is `20`.

Assignment is the main exception. It goes from **right to left**. So `a = b = 5` first stores `5` in `b`, then stores that in `a`.

### Precedence Table

This table lists operators from first to last:

| Order | Operators | Direction |
|---|---|---|
| 1 | `()` brackets | — |
| 2 | `++` `--` after a variable (`x++`) | left to right |
| 3 | `++` `--` before a variable, unary `-`, `!`, `~` | right to left |
| 4 | `*` `/` `%` | left to right |
| 5 | `+` `-` | left to right |
| 6 | `<<` `>>` `>>>` | left to right |
| 7 | `<` `>` `<=` `>=` | left to right |
| 8 | `==` `!=` | left to right |
| 9 | `&` | left to right |
| 10 | `^` | left to right |
| 11 | `\|` | left to right |
| 12 | `&&` | left to right |
| 13 | `\|\|` | left to right |
| 14 | `? :` | right to left |
| 15 | `=` `+=` `-=` and the other assignments | right to left |

**Easy Way to Remember:** brackets first, then maths, then comparisons, then logic, then storing. When in doubt, add brackets.

## Arithmetic Operators

Arithmetic operators do maths.

| Operator | Name | Example | Result |
|---|---|---|---|
| `+` | Addition | `10 + 3` | `13` |
| `-` | Subtraction | `10 - 3` | `7` |
| `*` | Multiplication | `10 * 3` | `30` |
| `/` | Division | `10 / 3` | `3` |
| `%` | Remainder (modulus) | `10 % 3` | `1` |

```java runnable title="Five arithmetic operators on the same two numbers"
public class Main {
    public static void main(String[] args) {
        int a = 10;
        int b = 3;

        System.out.println("a + b = " + (a + b));
        System.out.println("a - b = " + (a - b));
        System.out.println("a * b = " + (a * b));
        System.out.println("a / b = " + (a / b));
        System.out.println("a % b = " + (a % b));
    }
}
```

Expected output:

```text
a + b = 13
a - b = 7
a * b = 30
a / b = 3
a % b = 1
```

Notice the brackets around `(a + b)`. Without them, Java would join `"a + b = "` and `a` as text first. You would get `a + b = 103`.

### Integer Division

When **both** operands are whole numbers, `/` gives a whole number. The decimal part is thrown away.

So `10 / 3` gives `3`, not `3.333`.

If at least one operand is a decimal, the answer is a decimal.

```java runnable title="Whole-number division drops the decimal part"
public class Main {
    public static void main(String[] args) {
        System.out.println(7 / 2);
        System.out.println(7.0 / 2);
        System.out.println((double) 7 / 2);
    }
}
```

Expected output:

```text
3
3.5
3.5
```

`7 / 2` uses two `int` values, so the answer is `3`.

`7.0 / 2` has a `double`, so the answer is `3.5`. The cast `(double) 7` does the same thing.

### The Remainder Operator %

`%` gives what is **left over** after division.

Think of sharing 10 sweets between 3 friends. Each friend gets 3. One sweet is left over. So `10 % 3` is `1`.

`%` is useful for checking if a number is even. An even number has no remainder when divided by 2.

```java runnable title="Remainder finds even numbers and leftovers"
public class Main {
    public static void main(String[] args) {
        int number = 17;
        int minutes = 135;

        System.out.println("17 is even? " + (number % 2 == 0));
        System.out.println(minutes / 60 + " hours and " + minutes % 60 + " minutes");
    }
}
```

Expected output:

```text
17 is even? false
2 hours and 15 minutes
```

`17 % 2` is `1`, so 17 is not even.

`135 / 60` gives the whole hours, `2`. `135 % 60` gives the minutes left over, `15`.

### Dividing by Zero

Dividing a whole number by zero stops the program with an `ArithmeticException`:

```text
int result = 10 / 0;   // ArithmeticException: / by zero
```

Dividing a **decimal** by zero does not stop the program. It gives a special value called `Infinity`.

The `+` operator has two jobs. With two numbers, it adds them. If either side is a `String`, it joins them as text. So `"Total: " + 5 + 5` gives `Total: 55`, while `"Total: " + (5 + 5)` gives `Total: 10`.

## Increment / Decrement

`++` adds 1 to a variable. `--` takes 1 away.

`count++` is a short way of writing `count = count + 1`.

These are used a lot in loops, where you count up or down one step at a time.

### Prefix and Postfix

You can put `++` before or after the variable. On its own line, both do the same thing.

The difference shows when you use them inside a bigger expression:

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

Think of a ticket machine. With postfix, you get the current ticket number, then the machine moves on. With prefix, the machine moves on first, and you get the new number.

```java runnable title="Prefix changes first, postfix changes after"
public class Main {
    public static void main(String[] args) {
        int a = 5;
        int b = a++;
        System.out.println("After b = a++  ->  a = " + a + ", b = " + b);

        int c = 5;
        int d = ++c;
        System.out.println("After d = ++c  ->  c = " + c + ", d = " + d);

        int lives = 3;
        lives--;
        System.out.println("Lives left: " + lives);
    }
}
```

Expected output:

```text
After b = a++  ->  a = 6, b = 5
After d = ++c  ->  c = 6, d = 6
Lives left: 2
```

Both `a` and `c` end up as `6`.

But `b` got the **old** value, `5`, because `a++` hands over its value before adding 1. `d` got the **new** value, `6`.

In simple words: when you use `++` on its own line, the position does not matter. Inside a bigger expression, it does.

## Comparison Operators

A comparison operator compares two values. The answer is always a `boolean`: `true` or `false`.

They are also called **relational** operators.

| Operator | Meaning | Example | Result |
|---|---|---|---|
| `==` | Equal to | `5 == 5` | `true` |
| `!=` | Not equal to | `5 != 3` | `true` |
| `>` | Greater than | `5 > 3` | `true` |
| `<` | Less than | `5 < 3` | `false` |
| `>=` | Greater than or equal to | `5 >= 5` | `true` |
| `<=` | Less than or equal to | `3 <= 2` | `false` |

```java runnable title="Every comparison answers true or false"
public class Main {
    public static void main(String[] args) {
        int marks = 72;
        int passMark = 40;

        System.out.println("Passed? " + (marks >= passMark));
        System.out.println("Full marks? " + (marks == 100));
        System.out.println("Not zero? " + (marks != 0));
        System.out.println("Below 50? " + (marks < 50));
    }
}
```

Expected output:

```text
Passed? true
Full marks? false
Not zero? true
Below 50? false
```

You will use these answers in `if` statements and loops, to decide what the program does next.

Do not use `==` to compare two `String` values. `==` checks if they are the same object in memory, not if they hold the same text. Use `.equals()` instead: `name.equals("Asha")`.

## Logical Operators

A logical operator combines `true`/`false` values into one answer.

| Operator | Name | True when |
|---|---|---|
| `&&` | AND | **both** sides are true |
| `\|\|` | OR | **at least one** side is true |
| `!` | NOT | the value is false (it flips it) |

Think of entering a cinema. You need a ticket **AND** you must be old enough. If either one is missing, you cannot enter.

Now think of paying. You can pay by cash **OR** by card. Either one works.

```java runnable title="AND, OR and NOT combine conditions"
public class Main {
    public static void main(String[] args) {
        boolean hasTicket = true;
        int age = 15;
        boolean hasCash = false;
        boolean hasCard = true;

        System.out.println("Can watch the film? " + (hasTicket && age >= 18));
        System.out.println("Can pay? " + (hasCash || hasCard));
        System.out.println("Needs a ticket? " + !hasTicket);
    }
}
```

Expected output:

```text
Can watch the film? false
Can pay? true
Needs a ticket? false
```

`hasTicket && age >= 18` is false. The ticket is fine, but `15 >= 18` is false. AND needs both.

`hasCash || hasCard` is true. Cash is false, but the card is true. OR needs only one.

`!hasTicket` flips `true` to `false`.

### Truth Table

| `a` | `b` | `a && b` | `a \|\| b` | `!a` |
|---|---|---|---|---|
| true | true | true | true | false |
| true | false | false | true | false |
| false | true | false | true | true |
| false | false | false | false | true |

### Short-Circuit Evaluation

`&&` and `||` stop as soon as they know the answer. This is called **short-circuit** evaluation.

- With `&&`, if the left side is false, the answer must be false. Java skips the right side.
- With `||`, if the left side is true, the answer must be true. Java skips the right side.

This lets you guard a risky check:

```java runnable title="The left side protects the right side from dividing by zero"
public class Main {
    public static void main(String[] args) {
        int students = 0;
        int totalMarks = 0;

        boolean goodAverage = students > 0 && totalMarks / students > 50;

        System.out.println("Good average? " + goodAverage);
    }
}
```

Expected output:

```text
Good average? false
```

`students > 0` is false. So Java never runs `totalMarks / students`, and the program does not divide by zero.

Swap the two sides and run it again. The program now stops with an `ArithmeticException`, because the division runs first.

## Assignment Operators

The assignment operator `=` stores a value in a variable.

Java also has **compound** assignment operators. They do a calculation and store the result in one step.

| Operator | Example | Same as |
|---|---|---|
| `=` | `x = 10` | — |
| `+=` | `x += 5` | `x = x + 5` |
| `-=` | `x -= 5` | `x = x - 5` |
| `*=` | `x *= 5` | `x = x * 5` |
| `/=` | `x /= 5` | `x = x / 5` |
| `%=` | `x %= 5` | `x = x % 5` |

```java runnable title="Compound assignment updates a wallet step by step"
public class Main {
    public static void main(String[] args) {
        int wallet = 500;

        wallet += 200;
        System.out.println("After salary: " + wallet);

        wallet -= 150;
        System.out.println("After shopping: " + wallet);

        wallet *= 2;
        System.out.println("After doubling: " + wallet);

        wallet /= 4;
        System.out.println("After sharing: " + wallet);

        wallet %= 100;
        System.out.println("Coins left over: " + wallet);
    }
}
```

Expected output:

```text
After salary: 700
After shopping: 550
After doubling: 1100
After sharing: 275
Coins left over: 75
```

Each line changes `wallet` and keeps the result in the same variable.

### A Hidden Cast Inside Compound Assignment

There is one real difference between `x += 5` and `x = x + 5`.

For small types like `byte`, Java turns `x + 5` into an `int`. An `int` does not fit back into a `byte` without a cast. So the long form fails to compile:

```java runnable expect-error title="The long form needs a cast for a byte"
public class Main {
    public static void main(String[] args) {
        byte level = 10;
        level = level + 5;
        System.out.println(level);
    }
}
```

The compiler reports `possible lossy conversion from int to byte`.

The short form `level += 5;` compiles fine. Compound assignment adds the cast for you.

## Ternary Operator

The **ternary operator** picks one of two values based on a condition.

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

Read it as a question: "Is the condition true? If yes, use the first value. If no, use the second."

```java runnable title="One line picks between two values"
public class Main {
    public static void main(String[] args) {
        int marks = 72;
        String result = marks >= 40 ? "Pass" : "Fail";

        int a = 18;
        int b = 25;
        int bigger = a > b ? a : b;

        System.out.println("Result: " + result);
        System.out.println("Bigger number: " + bigger);
    }
}
```

Expected output:

```text
Result: Pass
Bigger number: 25
```

`marks >= 40` is true, so `result` gets `"Pass"`.

`a > b` is false, so `bigger` gets `b`, which is `25`.

The ternary operator is a short form of a simple `if-else`. Use it for small choices. For anything longer, an `if` statement is easier to read.

## Bitwise Operators

Inside the computer, every whole number is stored as **bits**. A bit is a single `0` or `1`.

For example, `12` is stored as `1100`, and `10` is stored as `1010`.

**Bitwise operators** work on these bits one position at a time.

| Operator | Name | A bit in the result is 1 when |
|---|---|---|
| `&` | AND | both bits are 1 |
| `\|` | OR | at least one bit is 1 |
| `^` | XOR | the two bits are different |
| `~` | NOT | it flips every bit |

Here is `12 & 10`, one column at a time:

```text
  1100   (12)
& 1010   (10)
------
  1000   (8)
```

Only the leftmost column has a `1` in both numbers. So the answer is `1000`, which is `8`.

```java runnable title="Bitwise operators compare numbers bit by bit"
public class Main {
    public static void main(String[] args) {
        int a = 12;
        int b = 10;

        System.out.println("a & b = " + (a & b));
        System.out.println("a | b = " + (a | b));
        System.out.println("a ^ b = " + (a ^ b));
        System.out.println("~a    = " + (~a));
        System.out.println("a in bits: " + Integer.toBinaryString(a));
    }
}
```

Expected output:

```text
a & b = 8
a | b = 14
a ^ b = 6
~a    = -13
a in bits: 1100
```

`a | b` is `1110`, which is `14`. `a ^ b` is `0110`, which is `6`.

`~a` flips every bit, including the sign bit. For any whole number, `~x` equals `-x - 1`. So `~12` is `-13`.

`Integer.toBinaryString()` shows a number's bits as text. It is handy for checking your work.

### Where Bitwise Operators Are Used

You will not use these every day. They appear in:

- settings stored as on/off flags in a single number;
- graphics and colour values;
- networking and file formats;
- fast tricks, such as `x & 1`, which is `1` for odd numbers and `0` for even numbers.

`&` and `|` also work on `boolean` values. But unlike `&&` and `||`, they **always** check both sides. They never short-circuit. For conditions, use `&&` and `||`.

## Shift Operators

**Shift operators** move all the bits of a number to the left or to the right.

| Operator | Name | What it does |
|---|---|---|
| `<<` | Left shift | Moves bits left and fills the gap with `0` |
| `>>` | Right shift | Moves bits right and keeps the sign |
| `>>>` | Unsigned right shift | Moves bits right and always fills with `0` |

Think of a row of digits on a counter. Sliding them one place to the left adds a `0` at the end. In base 10, that multiplies by 10. In bits (base 2), it multiplies by 2.

```java runnable title="Shifting bits multiplies or divides by 2"
public class Main {
    public static void main(String[] args) {
        int n = 5;

        System.out.println("5 << 1 = " + (n << 1));
        System.out.println("5 << 3 = " + (n << 3));
        System.out.println("40 >> 2 = " + (40 >> 2));
        System.out.println("-16 >> 2 = " + (-16 >> 2));
        System.out.println("-16 >>> 28 = " + (-16 >>> 28));
    }
}
```

Expected output:

```text
5 << 1 = 10
5 << 3 = 40
40 >> 2 = 10
-16 >> 2 = -4
-16 >>> 28 = 15
```

`5` is `101`. Shifting left by 1 gives `1010`, which is `10`. Each left shift doubles the number. So `5 << 3` is `5 × 2 × 2 × 2`, which is `40`.

`40 >> 2` halves twice, giving `10`.

`>>` keeps negative numbers negative. So `-16 >> 2` is `-4`.

`>>>` fills with zeros, even for a negative number. The sign bit becomes an ordinary bit, so the result is a large positive number. Here, `-16 >>> 28` gives `15`.

In simple words: `x << n` multiplies by 2, `n` times, and `x >> n` divides by 2, `n` times.

## Common mistakes

The following mistakes are common when using operators. Each row shows what you see, why it happens and how to fix it.

| Symptom | Cause | Fix |
|---|---|---|
| `int cannot be converted to boolean` | `=` was used to compare | Use `==` |
| An average comes out as a whole number | Both operands are `int` | Make one of them a `double` |
| `Sum: 23` instead of `Sum: 5` | Text joining ran before the maths | Put brackets around the maths |
| A value is one less than expected | `x++` gave the old value | Use `++x`, or move `x++` to its own line |
| `ArithmeticException: / by zero` | The division ran before the zero check | Put the zero check first with `&&` |
| `possible lossy conversion from int to byte` | `b = b + 1` on a `byte` | Use `b += 1`, or cast with `(byte)` |

## What to Remember

- An operator does a job on operands. Together they form an expression, which produces a value.
- Java follows precedence first, then left-to-right order. Brackets always win.
- `/` with two whole numbers drops the decimal part. `%` gives the remainder.
- `x++` uses the old value, then adds 1. `++x` adds 1, then uses the new value.
- Comparisons give `true` or `false`. `&&` needs both sides true, `||` needs one, and `!` flips the value.
- `+=`, `-=` and the other compound operators update a variable in one step.
- `condition ? a : b` picks one of two values. Bitwise and shift operators work on the bits of a number.

Next: Conditional Statements
