[英]What is the significance of the return statement inside a method whose return type is void
[英]Significance of return in the method with return type as void in Java
代碼示例:
public class TestReturn {
public void printNum(int[] ab){
int i = 0;
for( i=0; i<ab.length; i++){
if(ab[i] < 10){
System.out.println("less than 10");
return;
}
else{
System.out.println("more than or equal to 10");
return;
}
}
}
public static void main(String args[])
{
TestReturn a = new TestReturn();
int[] ab = {67, 56, 34, 89, 2, 23, 92, 33, 9, 74};
a.printNum(ab);
}
}
在上面的代碼中,return 已經被使用了兩次。 在運行代碼時,您可以看到根據輸入代碼只運行一次。 現在,如果 else 塊中的 return 語句被注釋掉,則循環運行 5 次,直到達到值 2,然后停止打印。
這也可以通過 break 語句來實現。 這個return語句還有更多的優點嗎?
return 語句的唯一優點是它退出了方法。 因此,如果您在循環之后有任何進一步的代碼並使用了break
,那將被執行。
使用return
,它不會被執行。
這通常是我使用return
的方式 - 如果我知道該方法已完成執行以達到您需要的目的,我會在其中添加一個 return 語句。
使用return
結束方法的執行。 使用break
你可以退出for
循環。
return
比break
稍快,因為它不會“退出” for 循環,而是完全退出該方法。 此外,如果您在循環之后有代碼,它將使用break
運行,但不使用return
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.