在使用Java时,”return”与”break”的区别是什么?

huangapple go评论59阅读模式
英文:

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 &gt; 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&gt;0){
    }else{return;}
  }
  System.out.println(&quot;Hello&quot;);
}

vs

void run(){ 
  while(true){
    if(a&gt;0){
    }else{break;}
  }
  System.out.println(&quot;Hello&quot;);
}

The first version would not print, the second would

huangapple
  • 本文由 发表于 2023年7月6日 16:47:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76627050.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定