+ 1
the difference between return method and a simple method
static void doSomething(int x) { System.out.println(x*x); } this method returns a value without adding that "return" to it . please to receive your answers :)
4 Respostas
+ 22
This method doesn't return any value (its return type is void). It just gets an integer value as an argument and then multiply and print it out to console.
+ 22
Many thanks Schindlabua. As always very thorough and informative.
+ 1
check this:
static void printSquare(int x){
System.out.println(x*x);
}
static int returnSquare(int x){
return x*x;
}
now:
System.out.println(returnSquare(2) + returnSquare(3));
will print 13 (4+9), while
Systrm.out.println(printSquare(2) + printSquare(3));
doesn't even work.
In programming you want to re-use code as often as possible so you don't have to write the same code twice, and that's why return is so useful.
+ 1
With methods that return some value / object you can assign that value / object to a local varijable... An extra simple example would be:
int valueFromMethod = methodThatReturnsIntValue();
int methodThatReturnsIntValue(){
return 2;
}
With void methods you can't do that as they don't return value / object.