Operators

37 0 0
                                        

Operators works the same way as mathematics. It also has a precedence.  Precedence is kind of a way on who goes to perform first. Like for example the operators +, -, *, /. If we didn't use a parenthesis, * or / will go first before + or -. If you want to know the sequence  of precedence of all operators, check the link on the first page. Though,  to avoid conflicts, why not just use a parenthesis.  A parenthesis has the highest priority of them all anyway.

Note:
In the precedence, the assignment operator is neglected.

Assignment operator ( = )
    - Assignment operator is the equal sign in mathematics.  It is called assignment since we, normally used this symbol to assign a value in a variable and also this is a better way to avoid confusion with equality operator ( == ).

Arithmetic operators
    1. Addition ( + )
    2. Subtraction ( - )
    3. Multiplication ( * )
    4. Division ( / )
    5. Remainder ( % )

Note:
There is a remainder operator since division works great in numbers with decimals which is either a float or a double but problem occurs with whole numbers which is an integer.

===============================

int x = 5;
int y = 2;
int z = x / y;
System.out.println(z);

===============================
Result:
2

The result is a whole number 2 and not 2.5 since the data type of 2.5 is either a float or a double.
You can either use a float or double in variable z or you can use the remainder of modulus operator.

================================

int x = 5;
int y = 2;
int za = 5 / 2;
int zb = 5 % 2;
System.out.println(za + " r  " + zb);

===============================
Result:
2 r 1

Other functions of addition operator is to concatenate strings just like in Result above.

Compound assignment
+=, -=, *=, /=, %=

==============================

int x += 5;

==============================
Equivalent:
x = x + 5

Unary Operator
+, -, ++, --, !

These operators are usually use together with a variable.
-( x ) means negative of x
! ( false ) means not false or true
x++ or ++x means x = x + 1
y-- or --y means y = y - 1

Note:
Incrementing (++) or decrementing (--) depends on the placement. If it is before the variable like ++x, the increment will take place right away but if after the variable, the increment will take effect on the invocation of x.

Java ProgrammingWhere stories live. Discover now