Quick win: is it positive?
Write Apex · Beginner · 5 min · Runs in your Salesforce Developer org · Free
Scenario. A form shows a green tick when a quantity is above zero. You write the check.
Return true or false from a comparison. Meet the Boolean type and see what happens with null.
What you will learn
A comparison like age >= 18 is already a Boolean: it is true or false. You can return it straight away, no if needed.
Boolean isAdult(Integer age) {
return age >= 18;
}
Gotcha. When the input is null, a comparison such as null > 0 is false. Apex does not throw here.
The task
Write a method isPositive(Integer n) that returns true for numbers above zero and false for everything else.
Examples:
isPositive(5)→trueisPositive(0)→falseisPositive(null)→false
Requirements:
- Return the result of comparing
nwith 0. - Zero is not positive.
- Keep the method's name and its Integer input.
Starter code
Boolean isPositive(Integer n) {
return null;
}
System.debug('5: ' + isPositive(5));
System.debug('0: ' + isPositive(0));
When it passes
`isPositive` returns true above zero, and false for zero, negative numbers and null.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.