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)→8twice(0)→0twice(-3)→-6
Requirements:
- Return
n * 2. - Keep the method's name and its Integer input.
- Leave the two
System.debuglines. 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.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.