ApexSensei

Drills › Write Apex

Quick win: pick the larger number

Write Apex · Beginner · 5 min · Runs in your Salesforce Developer org · Free

Scenario. A report shows the higher of two quarterly totals.

Return the bigger of two numbers. Your first if.

What you will learn

if runs a block only when its test is true. Put the other case after it.

String signLabel(Integer n) {
    if (n >= 0) {
        return 'non-negative';
    }
    return 'negative';
}

When n is 0 or more the first return runs and the method ends. Otherwise it falls through.

The task

Write a method larger(Integer a, Integer b) that returns the bigger of the two.

Examples:

  • larger(3, 9) → 9
  • larger(9, 3) → 9
  • larger(4, 4) → 4

Requirements:

  1. Use if to compare a and b.
  2. When they are equal, return either one. They are the same number.
  3. Keep the method's name and its two Integer inputs.

Starter code

Integer larger(Integer a, Integer b) {
    return null;
}

System.debug('3 or 9: ' + larger(3, 9));
System.debug('9 or 3: ' + larger(9, 3));

When it passes

`larger` returns the bigger number for every pair the grader tries, including equal and negative numbers.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Quick win: make initials · Quick win: shout it ›