| Math Operators |
|
Examples |
Description |
| + |
int x = 1+3 string mystring = "Hello " + "my friend" |
Adds together two values. In this case it sets the variable x equal to 4. Can also be used to concatenate strings as in the second example. |
| - |
int x = 3-1 |
Subtracts two values. In this case it sets the variable x to 2. |
| / |
int x = 4/2 |
Divides two values. In this case it sets the variable x to 2. |
| * |
int x= 4*2 |
Multiplies two values. In this case it set the variable x to 8. |
| ^ |
int x = 5^2 |
This turns the number to the right of the caret into a power. This is the same as writing 52 which is of course equal to 25. |
| ++ |
int i=0; i++ |
Adds one to the number. In this case i would be equal to 0. This is identical to writing i=i+1. |
| -- |
int i=0; i-- |
Subtracts one from a number. In this case i would be equal to -1. This is identical to writing i=i-1. |
| += |
int i=0; i+=5 |
Adds the value on the right to the value on the left. In this case i is equal to 5. This is identical to writing i = i + 5. May also be used to concatenate strings. |
| -= |
int i=0; i-=5 |
Subtracts the value on the right from the value on the left. In this case i is equal to -5. This is identical to writing i = i - 5. |
| % |
int i=5; int k = 5 % 2 |
This is the modulo operator. It takes the number on the left, divides by the number on the right and returns the remainder. In this case k=1. Why 1 and not .5? Because ints are rounded to the nearest whole number. |
| Relational Operators |
|
Examples |
Description |
| = |
int x = 5 |
Set the value on the left to the value on the right. With this expression we set x equal to 5. |
| == |
if(x == 5) |
Compares the value on the left to the value on the right. Here we have the start of an if statement checking to see if x is equal to 5. |
| != |
if(x != 5) |
Compares the value on the left to the value on the right. This returns true only if the two are NOT the same. This would read if x is not equal to 5 then... |
| < |
if(x < 5) |
Compares the value on the left to see if it is smaller tham the value on the right. |
| > |
if(x > 5) |
Compares the value on the left to see if it is greater than the value on the right. |
| >= |
if(x >= 5) |
Compares the value on the left to see if it is greater than or equal to the value on the right. |
| <= |
if(x >= 5) |
Compares the value on the left to see if it is less than or equal to the value on the right. |
| Boolean Operators |
|
Examples |
Description |
| && |
(if x == 5 && y == 2) |
The AND operator. To return true, both portions of this statement must return true. |
| || |
(if x == 5 || y == 2) |
The OR operator. To return true, either or both of the portions in this statement must return true. |