英文:
when using java return vs break
问题
当源代码如下所示时:
```java
void run() {
while (true) {
if (a > 0) {
} else {
return;
}
}
}
“else”块中有“return”,但当写下“break;”时,它也能正常工作。所以我想更深入地了解为什么在这里使用“return;”是更好的代码。
<details>
<summary>英文:</summary>
When have the source code like this:
```java
void run() {
while (true) {
if (a > 0) {
} else {
return;
}
}
}
The "else" block has return, but when write down "break;", it also works the same.
So I wonder a little more deep reason why using "return;" is more good code here.
答案1
得分: 4
In this case it works because break
exits the loop and goes to the end of the method which immediately returns. Which is functionally equivalent to returning immediately.
但在这种情况下,例如
void run(){
while(true){
if(a > 0){
}else{return;}
}
System.out.println("Hello");
}
与
void run(){
while(true){
if(a > 0){
}else{break;}
}
System.out.println("Hello");
}
第一个版本不会打印,而第二个会。
英文:
In this case it works because break
exits the loop and goes to the end of the method which immediately returns. Which is functionally equivalent to returning immediately.
But in this case, for example
void run(){
while(true){
if(a>0){
}else{return;}
}
System.out.println("Hello");
}
vs
void run(){
while(true){
if(a>0){
}else{break;}
}
System.out.println("Hello");
}
The first version would not print, the second would
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论