ApexSensei

Drills › Apex basics

Quick win: pick the larger number

Apex basics · 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. Returning from inside the if ends the method, so the line after it only runs when the test was false.

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

Apply the same pattern with two numbers: compare them, and return whichever one is larger.

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 ›