As we all know, return can only be used in functions with return types, but do functions with return values have to have return? Where can return be used in functions? This is a question to be discussed in this article.
--------------------------------------------------------------------------------
Example 1:
Class test {
Public String test (){
If (true ){
Return "";
}
Else {
Return "";
}
}
}
The above code can be compiled, but the following two examples cannot be compiled:
(1)
Class test {
Public String test (){
If (true ){
Return "";
}
}
}
(2)
Class test {
Public String test (){
If (istrue ()){
Return "";
}
Else if (! Istrue () {// all possibilities are included in the judgments of the two if statements, but they are still errors during compilation.
Return "";
}
}
Boolean istrue (){
Return true;
}
}
Conclusion 1:
For (1), this is because the Java compiler determines that a separate if statement is executed only when certain conditions are met. It assumes that if statements cannot be executed under any circumstances.
For (2), this is because the ability of the Java compiler to fully cover all situations for the IF else statement is limited to if... else (or if... else if... else), excluding if... else if.
--------------------------------------------------------------------------------
Let's look at Example 2:
Class test {
Public String test (){
While (true ){
Return "";
}
}
}
The above code can be compiled, but the following code does not work:
Class test {
Public String test (){
While (istrue ()){
Return "";
}
}
Boolean istrue (){
Return true;
}
}
Conclusion 2:
This is because the compiler considers that the while statement can be executed under any circumstances, but only when the input parameter is true.
--------------------------------------------------------------------------------
Let's look at Example 3:
Public class test {
String test () throws exception {
Throw new exception (); // after an exception is thrown, the program is aborted.
}
}
Conclusion 3:
If an exception is created in the function and thrown, the function does not return a value.
--------------------------------------------------------------------------------
With the above information, you will be able to use return freely.