What are Operators?
Operators are symbols that are used to perform logical, mathematical, and relational operations.
Types of Operators
- Assignment Operator: Used to assign values. For Example, x = y
- Logical Operator: Used to do calculations like addition, subtraction, etc. For Example, x + y or x – y or x * y
- Shorthand Operator: Used to assign values with operations by using short syntax. For Example, x += y or x *= y or x -= y or x /= y or x |= y
- Relational Operator: Used to compare values. For Example, x > y or x <= y
- Safe navigation operator: Used for error handling, as it gives null instead of throwing NullPointerException. For Example, x?.y
Add/Sub Considerations
- If X and Y are integers or doubles then add or subtract the value of Y from X and if any X or Y is double then the result is double.
- If X is a date and Y is an integer then it returns a new date that is incremented or decremented by the specified number of days.
- If X is a DateTime and Y is an integer or double then it returns a new DateTime which is incremented or decremented by a specified number of days with a fractional portion corresponding to a portion of the day.
Ex:
main() {
Double d = 5.2;
DateTime dt = new DateTime.now();
DateTime finalDate = dt - d ;
System.debug(dt);
System.debug(finalDate);
}
Note:
Only in the case of ‘+’ if X is a string and Y is a string or any other type of non-null argument then it concatenates Y to the end of X.