Java If 语句内外的 Return
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18282883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
A Return inside and outside an If Statement
提问by A13X
This is probably a fairly easy question to answer, but it has been bugging me some time.
这可能是一个相当容易回答的问题,但它一直困扰着我一段时间。
If there is a return statement inside an if statement, inside a method (in the Java language), but I add another at the end as a catch-all and to avoid the error, are both return values going to be fired one after the other if the if statement is true?
如果在 if 语句中,在方法中(Java 语言)中有一个 return 语句,但我在最后添加了另一个作为包罗万象并避免错误,两个返回值都将在其他 if if 语句是否为真?
An example:
一个例子:
public int getNumber() {
if( 5 > number) {
return 5;
}
return 0;
}
Result: Method returns 5, and then via stacks logic, returns 0 shortly thereafter.
结果:方法返回 5,然后通过堆栈逻辑,此后不久返回 0。
Or, do I need to use an outside variable like so:
或者,我是否需要像这样使用外部变量:
int num = 1;
public int getNumber() {
if( 5 > number) {
num = 5;
}
return num;
}
Result: Method changes variable num to 5, then num is returned for use. I suppose in this case, the return statement wouldn't necessarily be required depending on the variable's usage.
结果:方法将变量 num 更改为 5,然后返回 num 以供使用。我想在这种情况下,根据变量的使用情况,不一定需要 return 语句。
Thanks in advance.
提前致谢。
采纳答案by rgettman
No, both values aren't going to be returned. A return
statement stops the execution of the method right there, and returns its value. In fact, if there is code after a return
that the compiler knows it won't reach because of the return
, it will complain.
不,这两个值都不会返回。一条return
语句在那里停止方法的执行,并返回它的值。事实上,如果在 a 之后有return
编译器知道由于 无法到达的代码return
,它会抱怨。
You don't need to use a variable outside the if
to return it at the end. However, if your method is long and complex, this technique can help readability and clarity because only one return
statement is used.
您不需要在最后使用外部变量if
来返回它。但是,如果您的方法又长又复杂,则此技术有助于提高可读性和清晰度,因为只使用了一个return
语句。
回答by Xabster
Only the first return statement hit is used. The method then terminates.
仅使用第一个返回语句命中。然后该方法终止。
There are some code conventions that frown on multiple return statements because they might be hard to read, but I'm not one of them. :)
有一些代码约定不赞成多个 return 语句,因为它们可能难以阅读,但我不是其中之一。:)