Return statement in the Java language

zhaozj2021-02-12  150

Author: qlampskyface

Contact your author: xiaozuidaizhi@sina.com

It is well known that return can only be used in a function of return type, but is Return if there is a function of return values? What places can RETURN can be used in functions? This is a question that needs to be discussed herein.

Example 1:

Class test {public string test () {if (true) {return "";} else {return ";}}}

This 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 ()) {// The judgment of two IF includes all the possibilities, but still Compilation Error Return "";}} boolean istrue () {return true;}}}

Conclusion 1: For (a), this is because the Java compiler determines that a separate IF statement is only performed when a certain condition is met, it believes that if if IF does not have the ability to perform without any circumstances. For (b), this is because the Java compiler can completely cover the IF ELSE statement, only if the IF ... Else (or if ... else if ... else) is limited, ... Else IF.

Re-see example 2:

Class test {public string test () {while (true) {return "";}}} can be compiled, but the following is not:

Class test {public string test () {while (istrue ()) {return "";}} boolean istrue ()}}

Conclusion 2: This is because the compiler believes that the WHILE statement is capable of executing in any case, but it has the ability to be in the case where imported as TRUE.

Look again in the case:

Public class test {string test () throws exception {

Throw new exception (); // After the abnormality, jump out the program, the program abort}} Conclusion 3: If an exception is created in the function and throws, the function may not return a value.

I know the above situation, you can skillfully use Return.

转载请注明原文地址:https://www.9cbs.com/read-6173.html

New Post(0)