简体   繁体   English

Java中返回类型为void的方法中返回的意义

[英]Significance of return in the method with return type as void in Java

Code Example:代码示例:

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);

    }

}

In the above code return has been used twice.在上面的代码中,return 已经被使用了两次。 While running the code you can see that according to the input the code runs only once.在运行代码时,您可以看到根据输入代码只运行一次。 Now if the return statement in the else block is commented out the loop runs for 5 times till it reaches the value 2 and then it stops printing.现在,如果 else 块中的 return 语句被注释掉,则循环运行 5 次,直到达到值 2,然后停止打印。

This can be achieved through break statement also.这也可以通过 break 语句来实现。 Are there any more advantages of this return statement?这个return语句还有更多的优点吗?

The only advantage of the return statement is that it exits the method. return 语句的唯一优点是它退出了方法。 So if you had any further code after the loop and used break , that would be executed.因此,如果您在循环之后有任何进一步的代码并使用了break ,那将被执行。

With return , it is not executed.使用return ,它不会被执行。

This is generally how I use return - if I know the method has finished executing for the purposes of what you need it for, I put a return statement in.这通常是我使用return的方式 - 如果我知道该方法已完成执行以达到您需要的目的,我会在其中添加一个 return 语句。

With return you end method's execution.使用return结束方法的执行。 With break you get out of the for loop.使用break你可以退出for循环。

return is slightly faster than break because it doesn't 'get out' of the for-loop, but quits the method completely. returnbreak稍快,因为它不会“退出” for 循环,而是完全退出该方法。 Also, if you had code after the loop, it would be run using break , but not using return .此外,如果您在循环之后有代码,它将使用break运行,但不使用return

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM