ApexSensei

Drills › Write Apex

Quick win: double a number

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

Scenario. Your first method. Nothing to look up, just one line to write.

Write a one-line method that returns a number times two. Your first method that returns a value.

What you will learn

A method takes input and gives back a result with return. The word before the name says what type comes back.

Integer plusTen(Integer n) {
    return n + 10;
}

Call it like plusTen(4) and you get 14. Once the method works for one number, it works for every number.

The task

Write a method twice(Integer n) that returns the number doubled.

Examples:

  • twice(4) → 8
  • twice(0) → 0
  • twice(-3) → -6

Requirements:

  1. Return n * 2.
  2. Keep the method's name and its Integer input.
  3. Leave the two System.debug lines. They show your method working.

Starter code

Integer twice(Integer n) {
    return null;
}

System.debug('Twice 4: ' + twice(4));
System.debug('Twice 21: ' + twice(21));

When it passes

`twice` returns double its input for every number the grader tries, including 0 and negatives.

Try this drill free

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

‹ Hello, ApexSensei · Quick win: greet by name ›