Return type in java | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Return type in java

It's unclear for me a bit. Can we call the methods that their return type is void?? If we can't so why we have void methods?? We say the methods with void return type Doesn't return any thing so calling them is useless. Is it true??

29th Mar 2018, 7:24 PM
Salim13i
Salim13i - avatar
4 Answers
+ 3
Void means that you're not returning data back to the what called the function, but whatever operations took place in the function is what took place. As an example that I just gave to someone: // Custom function for System.out.println() public static void println(String string){ System.out.println(string); } ^This function doesn't return anything to what called it. However, during the functions execution, it prints the data that was fed to the function. So it has its function, but it simply doesn't need to return me any data for me to use elsewhere. Here is an example of a class GETTER method, which returns data: METHOD IN CLASS: public int getNumber(){ return this.number; } FUNCTION CALL IN MAIN: myObject.getNumber(); ^With this, I want it to return data to me so that I can use it for whatever I'm doing elsewhere. As such, I set the return type to int and return the int value back to the where the function was called from.
29th Mar 2018, 7:44 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 2
It's not useless. void hello() { System.out.println ("Hello"); } Calling hello() will print Hello and it could do everything else functions with a return type can do - except for returning a value when it ends.
29th Mar 2018, 7:32 PM
Chris
Chris - avatar
+ 1
No, it just depends what you want the function to do. For example a sum method should usually return an integer so we can use it directly for our program: int x = sum(1,2); if (x > sum(y,z)) {...} etc. A method that doesn't need to return anything is print for example. It just prints what you told the method: print("Hello world"); => The print method would have a void return type
29th Mar 2018, 7:32 PM
Aaron Eberhardt
Aaron Eberhardt - avatar
+ 1
Hey,my name is Egbo Uchenna Matthew from Nigeria. Please I'm new to programming and I'm very enthusiastic about it and excited to know and learn more as I go ahead. I need assistance and guidance. Hopefully I can get help and great resources for improvement from great friends here. I want you to help me please. Thanks.
30th Mar 2018, 7:52 AM
Yuh_Cee
Yuh_Cee - avatar