'Is it necessary to store a value from a method which is returning a value in java?
Let suppose I have a method
public int dummy(){
return 1;
}
and if I call this method by
dummy();
not
int a = dummy();
will it make any difference? why?
Solution 1:[1]
It will still compile, but (assuming that the method is just called in isolation) it'll be pointless, since you can never use the value returned. (At a deeper level, and depending on implementation, it's possible the JVM may optimise away the method call entirely.)
If however you do int a = dummy();, then you can later reference that variable, eg. System.out.println(a); will print out its value.
If your method had another side effect other than returning a value, such as:
public int dummy(){
System.out.println("hello");
return 1;
}
...then calling it without assigning its result to a variable wouldn't be pointless, since the side effect would still occur (printing "hello" in this case). While some argue this is poor design, this sometimes occurs in practice in the Java libraries - you could call createnewFile() on a File object for instance and ignore its returned boolean value (which will tell you whether the file was created or not.)
Solution 2:[2]
These two are both true statements, but the difference is, when you use
dummy()
this will call the function in the program, but since you are returning a value, it is pointless ( considering you will keep the value )
When you use
int a = dummy()
You will create an integer named a in order to store the output ( return value ) of the function, which you can reuse any time.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Batuhan Tosyalı |
