Next page | Contents page |

Operators

Arithmetic, between numbers

+ add, - subtract, * multiply, / divide, % modulus (remainder)

Examples:

	a = b + c;
	d = e + f * 17;  // Normal associativity: * and / done before + and -
	h = (i + j) * k; // Normal bracketing to force + to be done first
	m = 13 % 3;      // = 1, the remainder after division

+ is also used to concatenate strings: s = "Hello " + name;

++ and -- increment and decrement, commonly for loops. Eg,

	x++;		// Increment x (by 1). Shorthand for x = x + 1;
	a = x++  + y;	// a = x + y, then increment x (post-increment)
	b = --x * y;	// Decrement x then b = x * y (pre-decrement)

Tip: do not try to be too clever like this. Instead of those last 2 statements use separate steps for clarity:

	a = x + y;
	x++;
	
	x--;
	b = x * y;

Comparisons

== is equal to (not to be confused with assignment, =)
!= is not equal to
> is greater than
>= is greater than or equal to
< is less than
<= is less than or equal to

Combining boolean values

& (AND), | (OR), ^ (XOR) !, (NOT)

boolean useable = !tooCold & !tooHot;

Conditional logic

Used in "if" statements and loops (coming soon).

&& (AND), || (OR), ! (NOT)

if (a < 1 && b > 3) c=10;

Bitwise operators for whole numbers

& (AND), | (OR), ^ (XOR), ~ (NOT, 1's complement)

Bit shifting for whole numbers

<< (shift left)
>> (shift right, signed)
>>> (shift right, unsigned)

a = b << 3; // Shift b left 3 bits (zero fill from the right)

The conditional operator

? :

String s = (x == y) ? firstName + " " : initial;

If the condition is true do the statement between ? and :, otherwise do the statement after the colon.

NB: Use this sparingly - it is hard to read.

Compound operators

There are also compound operations of the form op=

+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, >>>=

Example:

	a %= b;     // is shorthand for:
	a = a % b;

This might be more efficient because the address of a (may be a complicated expression) is only computed once. However compilers these days are clever enough to spot that kind of optimisation and do it anyway. Nevertheless you will often see compound operators so you need to know what they mean.

Next page | Contents page |