Learn from industry experts! Admin batch starts from 19 Feb.
Hurry up!
Book your slot now!

3

Shorthand Operator

What Is Shorthand Operator?

Shorthand operators, also known as compound assignment operators, are used to simplify the syntax of performing an operation and assignment in one step. Instead of writing the full expression, you can use shorthand operators to make your code more concise and readable.

How to use the shorthand operator?

To use a shorthand operator, you place the operator symbol directly before the assignment operator (=). This combination performs the operation on the left-hand operand with the right-hand operand and then assigns the result to the left-hand operand.

Syntax and Examples

Here are some common shorthand operators and their usage in Apex:

+= (Addition Assignment)

x += y; // Equivalent to x = x + y;

What Is OR Assignment and AND Assignment Operator?

|= (OR assignment operator)

The OR assignment operator (|=) is used to perform a bitwise OR operation on the left-hand operand with the right-hand operand and then assigns the result to the left-hand operand. In the context of boolean values, it assigns true to the variable if either operand is true.

SYNTAX

boolean x = false;

boolean y = true;

x |= y; // x becomes true because y is true

&= (AND assignment operator)

The AND assignment operator (&=) performs a bitwise AND operation on the left-hand operand with the right-hand operand and assigns the result to the left-hand operand. For boolean values, it assigns true only if both operands are true.

SYNTAX

boolean x = true;

boolean y = true;

x &= y; // x remains true because both x and y are true

EXAMPLE

boolean a = false;boolean b = true;
a |= b; // a becomes true because b is true
boolean c = true;boolean d = false;
c &= d; // c becomes false because d is false
Salesforce Developer
Next Topic

Need more support?

Get a head start with our FREE study notes!

Learn more and get all the answers you need at zero cost. Improve your skills using our detailed notes prepared by industry experts to help you excel.

Book A 15-Minutes Free Career Counselling Today!