Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Return
AP® Computer Science A (Java) Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source AP® (Advanced Placement®) Java Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency. It is a substantial amount of coursework that represents a typical year of high school-level study or a semester of a University computer science course. This course may also be used to prepare for the AP® Computer Science A exam.
-->
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
Another important branching statement in Java is the return statement, which we have already seen before when we covered methods. At any time in a method, the return statement is used to cause the whole method to return a certain value and ignore all the statements underneath it. The program belows shows an example of the count() method and a return statement inside a while loop.
ReturnStatementExample.java
package exlcode;
public class ReturnStatementExample {
public static int exampleVariableOne = 100;
public static void main(String[] args) {
System.out.println(count());
}
public static String count() {
while (exampleVariableOne > 0) {
if (exampleVariableOne == 25) {
return "exampleVariableOne is 25";
}
exampleVariableOne--;
}
// returns the statement below if exampleVariableOne
// is never equal to 25
return "exampleVariableOne is never equal to 25";
}
}
As you can see after running the code above, return breaks the loop and exits the method immediately after it is called. The statement return "exampleVariableOne is never equal to 25"; is never called because exampleVariableOne will eventually reach 25 as it decreases from 100 to 0.
The return statement is useful because it saves time and makes the program run faster by returning the output of method without executing unnecessary code and loops. It is good practice to always have a return statement after the for/while loop in case the return statement inside the for/while loop is never executed. Otherwise, a compile-time error will occur because the method cannot return nothing (unless it has the Java reserved word "void" in the method header).