Experience Salesforce

Shorthand Operator

What You’ll Learn

  • What Is Shorthand Operator?
  • How to use the shorthand operator ?
  • What Is OR Assignment and AND Assignment 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 Extra Support? Our FREE study materials have got you covered.

Our expert-prepared study materials provide the answers you need. Clear your doubts and improve your skills with detailed notes from industry professionals.

cts-img
Rakshabandhan Sale