Reputation: 289
I am beginner in Java i am learning about Java methods in my tutorial there is this code:
public class JavaLessonSix {
static double myPI = 3.14159;
public static void main(String[] args){
addThem(1, 2);
}
public static int addThem(int a,int b){
int c = a + b;
System.out.println(c);
return c;
}
}
I did not really understood what return statement means. Could you please describe to me what the return statement means in Java..?
Upvotes: 0
Views: 3416
Reputation: 1
First you need to know what a method is: a method is a modular structure consisting of integrated units arranged in a logical order to form a complete unit.
Meaning when a method is called it does 'something'. So, you want to know whether that 'something' is right, or not!
When you add a return type in your method prototype, and in your method body you specify the actual variable to return, this allows you to pass back such value generated internally.
Upvotes: 0
Reputation: 30300
The return
statement does the following:
return
value is the analogue to f(x)
.Consider this method:
public boolean isEven(int number) {
return number % 2 == 0;
}
The caller might say
if (isEven(givenNumber)) {
//Do stuff
}
So if x is givenNumber
and f is isEven
, f(x) is isEven(givenNumber)
. The return
statement specifies just what that answer is.
You can also think of it this way. Since isEven(4)
returns true
I can replace this
if (isEven(givenNumber))
with this
if (true)
when givenNumber
= 4 because true
is what got returned.
Upvotes: 0
Reputation: 4923
A Java method is a collection of statements that are grouped together to perform an operation.So when you call any method to complete some task,so it will give you the result of the method.In below code :
public static int addThem(int a,int b){
int c = a + b;
System.out.println(c);
return c; ----->>> Returning result (int)
}
You are having method addThem
whose task is to add the two number but in what data type it will return the result..
Upvotes: 1
Reputation: 63945
A statement
is a single instruction, roughly every line of code that does something is a statement.
A return statement
is one like return c
.
Return statements stop the execution of a method and return the final value (or nothing in case of void
methods).
Execution continues at the place that called the method. The value you returned is used in place of the method call and calulation can continue.
Upvotes: 5
Reputation: 121
return
does what it names suggests. It returns the value of c. so if you have this
int result = addThem(1, 2);
result
will equal 3, so you can then print it in main.
Upvotes: 7