+ 2

What is difference printing to screen and returning a value?

void horn() { System.out.println("Beep!"); } Here is example. As I know void does not return anything, and what does println means then? What will it do?

16th Dec 2017, 4:16 PM
Sad
Sad - avatar
3 Respuestas
+ 4
print, println and printf output stuff on the console, strings generally. The return in the other hand is just a value, can be any data type, and it is not displayed on console. The return is there to use. for example int num = 2 + Math.sqrt(4); The return of sqrt is the square root of 4 in this case, which is 2 + 2 = 4 so the var num equals 4
16th Dec 2017, 4:23 PM
voidneo
+ 9
Since void means that nothing can be returned by the method, you can't add a return statement to the horn() method. Thus, in a void method, the println() method (which prints a line of text to the screen.) is used in place of the return statement.
16th Dec 2017, 4:23 PM
Dev
Dev - avatar
+ 2
Thanks guys!
16th Dec 2017, 4:24 PM
Sad
Sad - avatar