简体   繁体   English

为什么需要return语句

[英]Why there is need of return statement

I have very silly doubt that why we use return statement in method .我很愚蠢地怀疑为什么我们在 method 中使用 return 语句。 Without using return statement in method we can also get required value as example在方法中不使用 return 语句,我们也可以获取所需的值作为示例

package testing;

public class ReturnMethod {
    static int a = 10;
    static int b = 5;
    static int c;
    static int d;

    public static void add() {
        c = a + b;

    }

    public static int returnAddValue() {
        d = a + b;
        return d;
    }

    public static void main(String[] args) {
        add();
        System.out.println("c: " + c);
        int value = returnAddValue();
        System.out.println("value: " + value);

    }

}

In above example in both the cases i am getting output在上面的例子中,在这两种情况下我都得到输出

c: 15
value: 15

So i am having doubt when to use return statement and why is neccessary所以我怀疑何时使用 return 语句以及为什么需要

With return statement , the return value is not necessary to be saved in any global, external or member variable.使用return statementreturn value不需要保存在任何全局、外部或成员变量中。

However, without return statement you have to prepare kind of outer variable value to track that.但是,如果没有return statement您必须准备一种outer变量值来跟踪它。

If you assign the result of a method to a static variable (and, indeed, pass in the "parameters" of the method by setting static variables), you have problems when that method is called by two threads concurrently, since the variables are shared for all invocations of the method:如果将方法的结果分配给静态变量(并且实际上通过设置静态变量传入方法的“参数”),则当两个线程同时调用该方法时会出现问题,因为变量是共享的对于方法的所有调用:

Thread t1 = new Thread(() -> {a = 1; b = 2; add(); }); t1.start();
Thread t2 = new Thread(() -> {a = 3; b = 4; add(); }); t2.start();
t1.join(); t2.join();

You don't know which of these threads run first, or even if they run at the same time;您不知道这些线程中的哪一个先运行,或者它们是否同时运行; so you don't know what the value of a or b is when you call add() , and nor do you know whether the value in c afterwards is the result of the invocation in the first or second thread (or a mixture of the two).所以你不知道当你调用add()ab的值是什么,也不知道之后c的值是第一个或第二个线程中调用的结果(或二)。

The value stored in c afterwards could be any of 3 , 5 or 7 (or any other value, if there is another thread which is also invoking add() concurrently outside this code.之后存储在c的值可以是357任何一个(或任何其他值,如果还有另一个线程也在此代码之外同时调用add()

This problem of thread interference just completely goes away if you keep values localized to the stack, by passing a and b as method parameters, and receiving the result as a return value.如果您将值保持在堆栈中,通过将ab作为方法参数传递,并将结果作为返回值接收,那么线程干扰的问题就完全消失了。


Even if your code is single-threaded, it's simply ugly to have to write:即使您的代码是单线程的,也很难编写:

a = 1;
b = 2;
add();
int result = c;

rather than而不是

int result = add(1, 2);

You should use a return statement, when you need the method to return a value.当您需要该方法返回值时,您应该使用 return 语句。

In your case, both methods work.在您的情况下,这两种方法都有效。
But you can, and should use returning methods, when you don't want a field of your class to be changed by another class.但是,当您不希望您的类的字段被另一个类更改时,您可以并且应该使用返回方法。

For example, you want money to be only seen , and not changed , when you are making a bank-account related software.例如,在制作银行账户相关软件时,您希望money被看到,而不能被更改 So, you make money private, and make a method which returns the money.因此,您将money私有,并创建了一个返回钱的方法。 In this way, other classes can only see money, but not change it.这样一来,其他类只能看到钱,但不能改变它。

First, your functions are different, as you see首先,您的功能不同,如您所见

public static **void** add()

public static **int** returnAddValue()

First one does not return anything, because it has void as return type and the second one has int as return type.第一个不返回任何内容,因为它的返回类型为 void,而第二个的返回类型为 int。 First one works, because c is a global variable.第一个有效,因为 c 是一个全局变量。

You typically would use return when you don't store the result in a (static) variable of your class.当您不将结果存储在类的(静态)变量中时,您通常会使用 return 。

public class ReturnMethod {
    static int a = 10;
    static int b = 5;

    public static void add() {
        int c = a + b;
    }

    public static int returnAddValue() {
        int d = a + b;
        return d;
    }

    public static void main(String[] args) {
        add();
        //not possible to access c here
        //System.out.println("c: " + c);
        int value = returnAddValue();
        System.out.println("value: " + value);
    }
}

In that modified example, there would be no way for you to access the result of the add() method.在修改后的示例中,您将无法访问 add() 方法的结果。

You should probably read about Scopes in Java .您可能应该阅读Java 中的作用域

You have a class variable c & d.你有一个类变量 c & d。 These variables are associated with the class and stored in heap.这些变量与类相关联并存储在堆中。 If you assign a value back to it and you can access it without a explicit return statement.如果您为其分配一个值,并且无需显式 return 语句即可访问它。 But if you have declared d inside the method then return statement is required to give the value back to the caller.但是,如果您在方法中声明了 d,则需要 return 语句将值返回给调用者。

The reason that you are able to access the value of class variable c is that it has been initialized as static.您能够访问类变量 c 的值的原因是它已被初始化为静态。 Had this not been the case the information in the c variable would be lost as soon as the add method ends.如果不是这种情况,一旦 add 方法结束,c 变量中的信息就会丢失。 The reason methods have return value is that they user can get the updated value , if there are any manipulation in the object data.方法有返回值的原因是它们用户可以获得更新的值,如果对象数据中有任何操作。 In this case there is a very small, what if there is series of manipulation with the data.在这种情况下有一个非常小的,如果有一系列的数据操作怎么办。 In that case the final value has to be returned to the calling object which without return statement is not possible.在这种情况下,最终值必须返回给调用对象,没有 return 语句是不可能的。

The variable C in your code snippet is accessed in the class throughout, and will stay until the object of the class exists.代码片段中的变量 C 始终在类中访问,并将一直保留到类的对象存在。 So you can print the value of Variable C outside the method.所以你可以在方法之外打印变量 C 的值。

However, if you had declared a local variable in the method add() , then print statement System.out.println("c: " + c);但是,如果您在add()方法中声明了一个局部变量,则打印语句System.out.println("c: " + c); will print the default value for variable c .将打印变量c的默认值。 That is zero in this case.在这种情况下为零。

Its totally depends upon our requirement whether to return a value from our method or update instance variable.它完全取决于我们的要求是从我们的方法返回一个值还是更新实例变量。 Some time we just want to process a value and get back the result in and result will be used in different manner, in this case we need to return value from method.有时我们只想处理一个值并返回结果,结果将以不同的方式使用,在这种情况下,我们需要从方法返回值。

For example例如

java.lang.Math.sqrt(double a) method return a value and we use returned value as per our need OR requirement. java.lang.Math.sqrt(double a) 方法返回一个值,我们根据需要或要求使用返回值。 Can you think if this method does not returned any value then what it should update, I think this method useless if it does not returned any value.你能想到如果这个方法没有返回任何值那么它应该更新什么吗?如果它没有返回任何值,我认为这个方法没用。

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

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