Operators - StarShipTutor/StarshipTutorAPCS GitHub Wiki

Operators

Operator Precidence

Operations in an expression are performed highest first, from left to right, except for row 1), the unitary operators, and row 8), the assignment operators that or evaluated from right to left. Parentheses ( ) are used to clarify or alter the order of evaluation.

1) !, ++, --
2) *, /, %
3) +, -
4) <, >, <=, >=
5) ==, !=
6) &&
7) ||
8) =, +=, -=, *=, /=, %=

Arithmetic Operators

If x = 7 and y = 2 then

Addition       : x + y == 9 
Subtraction    : x - y == 5
Multiplication : x * y == 14
Division       : x / y == 3 (Integer division truncates to the lower integer)
Modulus        : x % y == 1 (gives the remainder when 7 is divided by 2)

Note : if x or y is a String + is concatenation

Logical Operators

Logical operators evaluate to a boolean ( true or false )

NOT : !
AND : &&
OR  : ||

Relational Operators

Relational operators evaluate to a boolean ( true or false )

Equal to                 : ==
Not equal to             : !=
Greater than             :  >
Less than                :  <
Greater than or equal to : >=
Less than or equal to    : <=

Assignment Operators

Equals         :  =   : x  = 2; Stores the value 2 in the variable x
Plus Equals    : +=   : x += 2; The same as x = x + 2;
Minus Equals   : -=   : x -= 2; The same as x = x - 2;
Times Equals   : *=   : x *= 2; The same as x = x * 2;
Divide Equals  : /=   : x /= 2; The same as x = x / 2;
Mod Equals     : %=   : x %= 2; The same as x = x % 2;

Special Operators

Increment Operator

++i : First set i = i + 1; then use the updated value of i
i++ : First use the value of i, then set i = i + 1;

Decrement Operator

--i : First set i = i - 1; then use the updated value of i
i-- : First use the value of i, then set i = i - 1;

Ternary Operator

The ternary operator is a short hand for an if statement.
It takes the form : A ? B : C

A is an expression that evaluates to a boolean
B and C are expressions that evaluate to the return type for the expression

For example : 

int aNumber = 5 > 10 ? 1 : 2;

sets aNumber to 2

So the ternary operator is an inline function equivalent to : 

if ( A )
{
   return ( B ); // If A == true return B
}
else
{
   return ( C ); // If A == false return C 
}



⚠️ **GitHub.com Fallback** ⚠️