Void and return in Java - when to use

后端 未结 7 1892
予麋鹿
予麋鹿 2020-12-18 17:10

I have some \"confusion\" about void and return. In general, I understand void is used in methods without returning anything, and return is used in methods when I want to re

相关标签:
7条回答
  • 2020-12-18 18:03

    In the void method:

    public void add(double n)
    {
        number += n;
    } 
    

    You aren't able to use the n variable across methods. This means that you won't be able to use it for the Calc method.

    However, when using a method which actually returns something, like:

    public double add1(double n)
    {
        return number = number +  n;
    }
    

    you get to use that variable as an object thus allowing you to use it within the Calc method and others as many times as you wish, each time might be the same object (not advised if using to calculate using different values) or a new object every time.

    As far as I know, there are no visible performances issues.

    0 讨论(0)
提交回复
热议问题