0
The Return Type in Java
I'm working on my java tutorial and having trouble understanding the difference between using "return" to return a value, and using a void method with the System.out.println() to return a value. Any explanations would be appreciated! And sorry if the question doesn't make sense I'm really new at coding.
3 Answers
+ 12
Think of it like this, a method with a return type that is not void performs a bunch of statements and lastly returns a value:
Example:
public int square(int number) {
int square = number * number;
return square;
}
Here the method(square) squares its parameter(number) and returns the square.
As a result we can have something like this
int x = 3;
int squareOfX = square(x);
This last statement is valid the method square() will return 9.
EDIT: System.out.println() does not return anything, it is a method used to print text.
+ 3
A function returns a value and a procedure just executes commands.
The name function comes from math. It is used to calculate a value based on input.
A procedure is a set of command which can be executed in order.
In most programming languages, even functions can have a set of commands. Hence the difference is only in the returning a value part.
But if you like to keep a function clean, (just look at functional languages), you need to make sure a function does not have a side effect.
public class Program{
public static void main(String[] args) {
int result;
result=sum(1,6)+sub(1,2); //getting result of function
change_a();
System.out.println(result);
}
public static int sum(int a,int b){
return a+b;
}
public static int sub(int a,int b){
return a-b;
}
public void change_a(int a){
a=5; //just changing the value
}
}
+ 3
@ elie java uses methods not functions đ