简体   繁体   中英

Why there is need of return statement

I have very silly doubt that why we use return statement in method . Without using return statement in method we can also get required value as example

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

With return statement , the return value is not necessary to be saved in any global, external or member variable.

However, without return statement you have to prepare kind of outer variable value to track that.

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

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.

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.


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.

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. So, you make money private, and make a method which returns the 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. First one works, because c is a global variable.

You typically would use return when you don't store the result in a (static) variable of your class.

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.

You should probably read about Scopes in Java .

You have a class variable 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. But if you have declared d inside the method then return statement is required to give the value back to the caller.

The reason that you are able to access the value of class variable c is that it has been initialized as static. Had this not been the case the information in the c variable would be lost as soon as the add method ends. 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.

The variable C in your code snippet is accessed in the class throughout, and will stay until the object of the class exists. So you can print the value of Variable C outside the method.

However, if you had declared a local variable in the method add() , then print statement System.out.println("c: " + c); will print the default value for variable 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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