I’m fairly new to programming, and I’m confused about what it means exactly to return a value. At first, I thought it meant to output what value is being returned, but when I tried that in my own code, nothing happened.
class Class1 {
public static int x = 3;
public static int getX(){
return x;
}
public static void main(String[] args){
Class1.getX();
}
}
This is an example of what I mean. When I run the program, nothing shows up. Considering this, I’m led to believe returning a value means something else. But what?
0
In simple terms, it means to return the value to caller of the method…
So, in your example, the method getX
would return the value of x
to the caller, allowing them access to it.
class Class1{
static int x = 3;
public static int getX(){
return x;
}
public static void main(String args[]){
int myX = Class1.getX(); // return the value to the caller...
System.out.println(myX); // print the result to the console...
}
}
1
Returning a value is a way for methods to talk to each other
public void method1() {
int value = 5 + method2(5);
System.out.println(value);
}
public int method2(int param) {
return param + 5;
}
This will print 15 (5 gets sent to method2
, which adds 5 to it and returns the result to method1
, which adds 5 to it and prints the result).
Java returns copies of values – in this case, it’s copying the value 10
and returning it to method1
. If method2
were returning an Object
then it would return a copy of the object’s reference. Different languages have different semantics for method returns, so be cautious when switching between languages. Java also copies the values of parameters passed to methods – in this case method1
copies the value 5 and passes it to method2
.
public void method1() {
int value = 5;
method2(value);
}
public void method2(int param) {
param = param + 5;
}
The value
in method1
is unaffected by method2
(value
still equals 5 after method2
executes), because only a copy of value
was sent as a parameter.
2
You are just calling a method which returns an integer but you are never using/printing it. Try to use it in your code to see whether you have got the desired value as you have set in your class.
What it means is that you invoke a function (any function) and the result of the function is passed back to the code that called it.
For example if you have a method called add and you invoke that method the value returned will be assigned to the calling code, please see the example below.
public class Main {
public static void main(String[] args) {
int a = 10;
int b = 20;
// Function add is called with two values and the result is assigned to
// the variable z
int z = add(a, b);
System.out.println("The sum of a and b is: " + z);
}
static int add(int a, int b){
int z = a+b;
return z;
}
}