Operators In Apex
Operators In Apex
In Apex, operators are symbols used to perform operations on variables and values.
Operators in Apex can be categorized into various types, such as arithmetic,
assignment, comparison, logical, and bitwise operators. Below is a comprehensive
guide on these operators with examples.
1. Arithmetic Operators
Operat
Description Example
or
+ Addition 5 + 3 => 8
- Subtraction 5 - 3 => 2
* Multiplication 5 * 3 => 15
/ Division 5 / 3 => 1.666...
Modulus
% 5 % 3 => 2
(remainder)
Example:
Integer a = 10;
Integer b = 3;
Integer sum = a + b; // 13
Integer difference = a - b; // 7
Integer product = a * b; // 30
Double division = a / (Double)b; // 3.3333
Integer remainder = a % b; // 1
2. Assignment Operators
Operat Exam
Description
or ple
= Assigns a value x=5
+= Adds and assigns x += 5
Subtracts and
-= x -= 5
assigns
Multiplies and
*= x *= 5
assigns
/= Divides and assigns x /= 5
%= Modulus and assigns x %= 5
Example:
Integer x = 10;
x += 5; // x = x + 5, result is 15
x -= 3; // x = x - 3, result is 12
x *= 2; // x = x * 2, result is 24
x /= 4; // x = x / 4, result is 6
x %= 5; // x = x % 5, result is 1
3. Comparison Operators
These operators compare two values and return a Boolean result (true or false).
Operat
Description Example
or
5 == 5 =>
== Equal to
true
!= Not equal to 5 != 3 => true
> Greater than 5 > 3 => true
< Less than 5 < 3 => false
Greater than or equal 5 >= 5 =>
>=
to true
5 <= 3 =>
<= Less than or equal to
false
Example:
Integer a = 10;
Integer b = 5;
Boolean result1 = a > b; // true
Boolean result2 = a <= b; // false
Boolean result3 = a == b; // false
Boolean result4 = a != b; // true
4. Logical Operators
Operat Descripti
Example
or on
Logical true && false =>
&&
AND false
|| Logical OR true || false → true
Logical
! !true => false
NOT
Example:
Boolean a = true;
Boolean b = false;
Boolean result1 = a && b; // false
Boolean result2 = a || b; // true
Boolean result3 = !a; // false
5. Bitwise Operators
Operat Descripti
Example
or on
Bitwise
& 5 & 3 => 1
AND
` ` Bitwise OR
Bitwise
^ 5 ^ 3 => 6
XOR
Bitwise
~ ~5 => -6
NOT
5 << 1 =>
<< Left shift
10
5 >> 1 =>
>> Right shift
2
Example:
6. Ternary Operator
Example:
7. Instanceof Operator
(Answer: A) +
Integer x = 10;
Integer y = 3;
Integer result = x % y;
System.debug(result);
A) 0
B) 1
C) 2
D) 3
(Answer: B) 1
(Answer: A) ==
4. What is the purpose of the || operator in Apex?
A) It performs an AND operation between two Boolean expressions.
B) It performs an OR operation between two Boolean expressions.
C) It assigns a value to a variable.
D) It checks if two values are equal.
(Answer: C) It adds a value to the variable and assigns the result to that variable.