If you’re new to programming, the term “operators” might sound a bit technical. But don’t worry—once you understand what operators do, you’ll see that they are quite intuitive. In programming, operators are symbols that perform operations on data, which are called operands. This article will introduce you to the different types of operators in Apex, Salesforce’s programming language, and how they work.
Types of Operators Based on the Number of Operands
An operand is a value or variable that the operator acts upon. Operators are classified based on how many operands they take. Let’s break this down:
1. Unary operators in Apex operate on a single operand. These are primarily used to increment or decrement a variable’s value by 1, either before or after the current statement is executed. Let’s look at the two main types of unary operators in detail:
- Increment (
++
): Adds 1 to the variable. There are two types:- Pre-increment (
++x
): The value of the variable is incremented before the expression is evaluated. - Post-increment (
x++
): The value of the variable is incremented after the expression is evaluated.
- Pre-increment (
- Decrement (–): Subtracts 1 from the variable. There are two types:
- Pre-decrement (
--x
): The value of the variable is decremented before the expression is evaluated. - Post-decrement (
x
–): The value of the variable is decremented after the expression is evaluated.
- Pre-decrement (
Integer y = 10;
// Pre-decrement: y is decremented before being used
System.debug(--y); // Outputs 9
// Post-decrement: y is decremented after being used
System.debug(y--); // Outputs 9, then y becomes 8
Pre-increment/decrement affects the variable before the current line of code is executed, while post-increment/decrement allows the original value to be used before the variable is modified. This distinction can be important depending on the order in which you want the operations to occur in your code.
By understanding both assignment operators and unary operators, you’ll be able to write cleaner, more efficient code in Apex, making your programming experience more intuitive. Keep practicing to get comfortable with these fundamental operators!
2. Binary Operators: These operators take two operands. This is the most common type, used in arithmetic, comparison, and logical operations. For example:
- Addition (
+
): Adds two numbers. - Equality (
==
): Compares two values to check if they are the same
Example in Apex:
Integer a = 10;
Integer b = 20;
System.debug(a + b); // Outputs 30
3. Ternary Operators: These operators take three operands. Apex has a ternary operator that acts like a shorthand for an if-else
statement.
- Ternary (
? :
): Checks a condition and returns one value if the condition is true and another if false.
Example in Apex: (condition) ? valueIfTrue : valueIfFalse
Integer i= 5;
Boolean isLarger = i > 5 ? true : false;
Different Types of Operators in Apex
Apex provides a variety of operators that you can use to perform different kinds of tasks. Let’s look at some common types of operators:
1. Mathematical Operators: These are used to perform arithmetic operations like addition, subtraction, multiplication, and division.
+
(Addition)-
(Subtraction)*
(Multiplication)/
(Division)
Integer num1 = 10;
Integer num2 = 5;
System.debug(num1 * num2); // Outputs 50
2. Logical Operators: Logical operators in Apex are used to combine or compare Boolean expressions, which result in either true
or false
. These operators are commonly used in if
statements, loops, and other control structures to control the flow of your program based on certain conditions.
Let’s explore each logical operator and how it works in Apex.
Logical AND Operator (&&)
The AND (&&
) operator returns true
only if both conditions are true. If either of the conditions is false, the result will be false
.
Working:
true && true
results intrue
true && false
results infalse
false && true
results infalse
false && false
results infalse
This operator is used when you want both conditions to be true for the entire expression to be evaluated as true.
Example:
Boolean hasPermission = true;
Boolean isAdmin = true;
if (hasPermission && isAdmin) {
System.debug('Access granted'); // This will be printed since both conditions are true
} else {
System.debug('Access denied');
}
In the example above, the condition evaluates to true
only if both hasPermission
and isAdmin
are true
. If either is false
, the program will deny access.
Logical OR Operator (||)
The OR (||
) operator returns true
if at least one of the conditions is true. The only case where it returns false
is when both conditions are false.
Working:
true || true
results intrue
true || false
results intrue
false || true
results intrue
false || false
results infalse
This operator is useful when you want the expression to be true if either of the conditions is true.
Example:
Boolean isEmployee = true;
Boolean isGuest = false;
if (isEmployee || isGuest) {
System.debug('Access granted'); // This will be printed because isEmployee is true
} else {
System.debug('Access denied');
}
In this case, the program grants access if either isEmployee
or isGuest
is true
. Even though isGuest
is false, the result is true
because isEmployee
is true.
Logical NOT Operator (!)
The NOT (!
) operator reverses the value of a Boolean expression. If a condition is true
, using !
makes it false
, and vice versa.
Working:
!true
results infalse
!false
results intrue
This operator is useful when you want to check the opposite of a condition.
Example:
Boolean isLoggedIn = false;
if (!isLoggedIn) {
System.debug('User is not logged in'); // This will be printed because isLoggedIn is false
} else {
System.debug('User is logged in');
}
Here, !isLoggedIn
inverts the false
value of isLoggedIn
to true
, so the program prints that the user is not logged in.
Combining Logical Operators
You can combine multiple logical operators in a single expression to create more complex conditions. The order of evaluation follows logical precedence, but you can always use parentheses ()
to control how conditions are grouped and evaluated.
Example:
Boolean isMember = true;
Boolean hasPaid = false;
Boolean hasDiscount = true;
if ((isMember && hasPaid) || hasDiscount) {
System.debug('Offer available'); // This will be printed because hasDiscount is true
} else {
System.debug('Offer not available');
}
In this example, the condition evaluates to true
because even though isMember && hasPaid
results in false
, the || hasDiscount
makes the whole expression true, so the offer is available.
Short-Circuiting in Logical Operators
In Apex, logical operators like &&
and ||
follow a behavior known as short-circuiting:
- For
&&
: If the first condition is false, Apex doesn’t evaluate the second condition, because the result will always be false. - For
||
: If the first condition is true, Apex doesn’t evaluate the second condition, because the result will always be true.
Example:
Boolean hasPermission = false;
Boolean isAdmin = true;
if (hasPermission && isAdmin) {
System.debug('Admin with permission');
} else {
System.debug('Condition failed'); // This will be printed without checking isAdmin because hasPermission is false
}
In this case, since hasPermission
is false, Apex will not bother checking isAdmin
due to short-circuiting, and the program moves to the else
block.
3. Assignment Operators
Assignment operators in Apex allow you to assign values to variables. In addition to the basic assignment operator (=
), there are complex assignment operators that perform an operation and assign the result back to the variable in one step. These are useful for simplifying your code when performing operations like addition, subtraction, multiplication, and division.
Here are the most common complex assignment operators:
=
(Assignment): Simply assigns the value on the right to the variable on the left.
Integer x = 10; // Assigns the value 10 to x
+=
(Add and assign): Adds the value on the right to the variable and then assigns the result back to the variable.
Integer x = 5;
x += 3; // Same as x = x + 3, now x is 8
-=
(Subtract and assign): Subtracts the value on the right from the variable and assigns the result back to the variable.
Integer x = 10;
x -= 4; // Same as x = x - 4, now x is 6
*=
(Multiply and assign): Multiplies the variable by the value on the right and assigns the result back to the variable.
Integer x = 7;
x *= 2; // Same as x = x * 2, now x is 14
/=
(Divide and assign): Divides the variable by the value on the right and assigns the result back to the variable.
Integer x = 20;
x /= 4; // Same as x = x / 4, now x is 5
These operators help keep your code concise and easy to read by combining assignment and the operation in one step.
4. Comparison Operators: These are used to compare two values.
==
(Equality): Checks if two values are equal.!=
(Not equal): Checks if two values are not equal.>
(Greater than),<
(Less than): Compares the size of two values.
Example:
Integer score1 = 85;
Integer score2 = 90;
System.debug(score1 > score2); // Outputs false
Equation or Statement: Operands + Operators
In programming, an equation or statement is made up of operands (data) and operators (symbols that act on the data). For example, consider the following statement:
Integer sum = 5 + 3;
Here’s what’s happening:
- The operands are
5
and3
, which are numbers. - The operator is
+
, which adds the two numbers together. - The result of the operation (
8
) is assigned to the variablesum
.
In this case, the operator takes two operands and returns a result based on the operation it performs.
Operators are Specific to Data Types
One important thing to remember is that operators are specific to data types. This means that not all operators can be used with every data type. For example:
- You can add numbers together, but you can’t add two
Boolean
values. - You can concatenate (join) strings, but you can’t multiply strings.
Example:
String firstName = 'John';
String lastName = 'Doe';
System.debug(firstName + ' ' + lastName); // Outputs 'John Doe'
Integer x = 10;
Integer y = 5;
System.debug(x / y); // Outputs 2
In the example above, the +
operator is used to concatenate two strings, while the /
operator is used to divide two numbers. The key is to use the right operator with the correct data type to avoid errors in your code.
Operator Associativity vs. Precedence
When multiple operators are used in an expression, the order in which they are evaluated is determined by operator precedence. Operators with higher precedence are evaluated first. If two operators have the same precedence, associativity determines the order in which they are evaluated.
Operator Precedence: This determines the order of operations. For example, multiplication and division have higher precedence than addition and subtraction.
- Example:
Integer result = 10 + 5 * 2; // The multiplication is done first, result is 20
Apex uses the following operator precedence rules:
Precedence | Operators | Description |
---|---|---|
1 | {} () ++ — | Grouping and prefix increments and decrements |
2 | ~ ! -x +x (type) new | Unary operators, additive operators, type cast and object creation |
3 | * / | Multiplication and division |
4 | + – | Addition and subtraction |
5 | << >> >>> | Shift Operators |
6 | < <= > >= instanceof | Greater-than and less-than comparisons, reference tests |
7 | == != | Comparisons: equal and not-equal |
8 | & | Bitwise AND |
9 | ^ | Bitwise XOR |
10 | | | Bitwise OR |
11 | && | Logical AND |
12 | || | Logical OR |
13 | ?? | Null Coalescing |
14 | ?: | Ternary |
15 | = += -= *= /= &= <<= >>= >>>= | Assignment operators |
Operator Associativity: This determines the direction in which an expression is evaluated when multiple operators of the same precedence are present. Most operators in Apex are left-to-right associative, meaning expressions are evaluated from left to right.
- Example:
Integer result = 20 - 10 + 5; // The subtraction is done first, result is 15
Let’s look at a more complex example:
Integer a = 10;
Integer b = 5;
Integer c = 2;
Integer result = a + b * c - 1;
System.debug(result); // Outputs 19 (Multiplication first, then addition, then subtraction)
In this example, the multiplication (b * c
) is performed first because it has higher precedence than addition and subtraction. Then the addition (a + result of b*c
), and finally, the subtraction.
Conclusion
Understanding how operators work in Apex is fundamental to writing efficient and effective code. Operators allow you to perform calculations, compare values, and control the flow of your program. Remember that different types of operators (unary, binary, ternary) and operator categories (mathematical, logical, assignment, comparison) serve different purposes, and they are specific to certain data types.
As you continue your journey in Salesforce development, mastering operators will give you the power to manipulate data and create dynamic applications with ease. Keep experimenting with different types of operators, and soon you’ll be writing code like a pro!