## 1.5. Operators

There are 3 main classes of operators: arithmetic, comparison, logical

You should learn what they are and have a fairly good idea of precedence.
Precendence means which operators are done first. In math we just use BEDMAS to figure this out.

Look at the operator precedence page.

What is printed out by this statement?

System.out.print("The total is " + 5 + 3);

It will print "The total is 53"

#### Types of Brackets

Brackets are generally evaluated before other operators.

• { } This shows code blocks. Very important.
• [ ] This is used for arrays
• ( ) This is used for
• functions: main() or println()
• changing order of operations in math statements: 5 * (2 - x)
• control flow statements: if( ), for( ), while ( ), switch( )
• < > This is used for lists of objects. eg. arraylists. More later

### Arithmetic operators

• + - * / %
• * is the multiplication sign
• / is division, but with integers, it's integer division. Any decimals are discarded, not rounded. .: 8/10 = 0 not 1 and not 0.8
• % is modulus. This is the remainder. So 15%12 = 3 (since 15/12 = 1 remainder 3)
• Order of operation: * / % all have the same precedence. After them comes + -

### Comparison Operators

• These operators compare two numbers (or rarely, two objects) and always return True or False
• They are: ` > < >= <= != ==`
• NOTE: you have to write ` <= . =< `will not work
• == is used to ask if two things are equal. e.g. ` if (lives == 0) exitGame();`
• To see if two strings are equal use this: `if (name.equals("Lars")) ...`
not `if (name == "Lars") ...`

Use .equals() for comparing any two objects.
• != means not equals
• Precendence: > < <= and >= are evaluated first. Then come == and !=

### Logical Operators

• These are used to join comparison operators together in IF statements
• && means AND
• || means OR
• ! means NOT
• eg. `if (date == 29 && month == 2) System.out.println("Leap day!!");`

### Assignment Operator

This is the = sign. It takes everything on the right hand side and puts the results into a variable on the left side.
It is generally the last thing done.

### Other Operators

You need to know the increment and decrement operators: a++ and a-- , as well as ++a and --a.

You also need to know the shortcut operators:` += -= *= /=`

• a++ means a = a + 1 , likewise a-- means a = a - 1
• a++; and ++a; are identical ONLY if they are used alone.
If they are in an expression, ++a is evaluated before other things, a++ is evaluated after other things
• You can never say (x*y)++ . It only works for single variables.
• x += 5 means x = x + 5
• x += 1 means x++ or x = x + 1
• x *= speed means x = x * speed