A Return inside and outside an If Statement(If 语句内部和外部的 Return)
问题描述
这可能是一个相当容易回答的问题,但它一直困扰着我一段时间.
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.
这篇关于If 语句内部和外部的 Return的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:If 语句内部和外部的 Return
基础教程推荐
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 降序排序:Java Map 2022-01-01