How to compare integers in apex
In apex, comparison is a common operation that lets developers compare two variables and run different execution paths based on the outcome. The result of all comparison operations operation in apex is a boolean value (true or false).
Using the outcome of comparison, conditional statements are used to route the execution path. Apex provides the following comparison operators to handle various scenarios.
| Operator | Description | Example |
|---|---|---|
| == | Equal to | Comparison outcome true
Integer x = 5; Integer y = 5; if( x == y) { //Do something } |
| != | Not equal to | Comparison outcome false
Integer x = 5; Integer y = 5; if( x != y) { //Do something } |
| > | Greater than | Comparison outcome false
Integer x = 5; Integer y = 5; if( x > y) { //Do something } |
| < | Less than | Comparison outcome false
Integer x = 5; Integer y = 5; if( x < y) { //Do something } |
| >= | Greater than or equal to | Comparison outcome true
Integer x = 5; Integer y = 5; if( x >= y) { //Do something } |
| <= | Less than or equal to | Comparison outcome true
Integer x = 5; Integer y = 5; if( x <= y) { //Do something } |
The following example shows how to compare two numbers in apex using various operators:
Loading...
In the above example:
- The variables numb1, numb2 are
Integervariables. - The
==operator checks if the two numbers numb1 and numb2, have the same value. - The
>operator checks if numb1 is greater than numb2. - The
!operator checks if numb1 is not equal to numb2. - The
&&operator is used to join two comparison statements, and all of them must be true for the overall expression to evaluate as true. - The
||operator is used to combine two comparison statements, and at least one of them must be true for the overall expression to evaluate as true.
Try It Yourself
Loading...