ApexSensei

Drills › Apex basics

Quick win: double a number

Apex basics · 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.

What you will learn

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

Integer n = 7;
Integer result = n + 10;

result is 17. Do the same style of calculation inside your twice method, but return the value instead of assigning it to a variable.

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 ›