Salesforce Operators in Apex

Operators in Apex

Operators are the sign that operates on one or more operands.

Types of Operators:

OperatorsDescriptionSyntax
== operator (Assignment Operator) assigns the value of “y” to the value of “x”.  x = y
+=+= operator (Addition assignment operator) adds the value of “y” to the value of “x” and then it reassigns the new value to “x”.x += y
*=*= operator (Multiplication assignment operator)multiplies the value of “y” with the value of “x” and then it reassigns the new value to “x”.x *= y
-=-= operator (Subtraction assignment operator) substract the value of “y” with the value of “x”, and then it reassigns the new value of “x”.  x -= y
/=/= operator (Division assignment operator) divides the value of “x” with the value of “y” and then reassigns the new value of “x”.x /= y
|=|= operator(OR Assignment operator), If “x” (Boolean), and “y” (Boolean) both are false, then “x” remains false.  x |= y
&=&= operator, if “x” (Boolean), and “y” (Boolean) both are true, then “x” remains true.x &= y
&&&& operator (AND logical operator) it shows “short-circuiting” behavior that means “y” is evaluated only if “x” is true.x && y
|||| OR logical operator.x || y
==== Operator, if the value of “x” equals to the value of “y”, then the expression evaluates true.  x == y
====== operator, if “x” and “y” reference the same location in the memory, then the expression evaluates true.x === y
++++ Increment operator.X ++
     ---- Decrement operator.x --

Example: 

integer result=250;   
result=result+50;
System.debug('result =result+50 =>'+result);
result=result-10;
System.debug('result =result-10 =>'+result);
result=result*20;
System.debug('result =result*20 =>'+result);
result=result/15;
System.debug('result =result/15 =>'+result);

Output:

Salesforce Operators in Apex

Example: Addition assignment operator.

integer output=100;   //storing output value as an integer
output+=10;  //adds output value with 10.
System.debug('output+=10 =>'+output);

Output:

Salesforce Operators in Apex

Example: Multiplication Assignment Operator

integer output=76;  //storing value as an integer
output*=12;       // multiplies value of output with 12
System.debug('output*=12 =>'+output);

Output:

Salesforce Operators in Apex

Example: Division Assignment Operator

integer output=25;   //storing value as an integer
output/=17;               // divides value of output with 17
System.debug('output/=17'+output);

Output:

Salesforce Operators in Apex

Example: Subtraction Assignment Operator

integer output=50;    //storing value as an integern 
output-=20;                // subtract value of output with 20
System.debug('output-=20 =>'+output);

Output:

Salesforce Operators in Apex