If 语句内部和外部的 Return

2022-01-19 00:00:00 return if-statement java

这可能是一个相当容易回答的问题,但它一直困扰着我一段时间.

This is probably a fairly easy question to answer, but it has been bugging me some time.

如果在 if 语句中,在方法中(在 Java 语言中)有一个 return 语句,但我在最后添加另一个作为包罗万象并避免错误,两个返回值都会被触发如果if语句为真,一个接一个?

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?

一个例子:

public int getNumber() {
 if( 5 > number) {
 return 5;
 }
 return 0;
 }

结果:方法返回 5,然后通过堆栈逻辑,此后不久返回 0.

Result: Method returns 5, and then via stacks logic, returns 0 shortly thereafter.

或者,我是否需要像这样使用外部变量:

Or, do I need to use an outside variable like so:

int num = 1;
public int getNumber() {
 if( 5 > number) {
 num = 5;
 }
 return num;
 }

结果:方法将变量 num 更改为 5,然后返回 num 以供使用.我想在这种情况下,根据变量的使用情况,不一定需要 return 语句.

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.

提前致谢.

推荐答案

不,这两个值都不会返回.return 语句会在此处停止方法的执行,并返回其值.事实上,如果在 return 之后有代码,编译器知道由于 return 而无法到达,它会报错.

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.

您不需要使用 if 之外的变量在最后返回它.但是,如果您的方法又长又复杂,则此技术有助于提高可读性和清晰度,因为只使用了一个 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.

相关文章