Please Am stuck again........... Java says when void is used in a method it doesnt return any value....... | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

Please Am stuck again........... Java says when void is used in a method it doesnt return any value.......

Yet it is possible to call a method that is void......... why all these??..........its so confusing that I dont know how to explain my question....... /* now this code returns the value of sum since it isnt void */ class MyClass { static int sum(int val1, int val2) { return val1 + val2; } public static void main(String[ ] args) { int x = sum(2, 5); System.out.println(x); } } /* and this code also does sayHello() even though its void.........Now the question is; "I thought void doesnt return any value, how come the public class still does the instructions in sayHello()?" */ class MyClass { static void sayHello() { System.out.println("Hello World!"); } public static void main(String[ ] args) { sayHello(); }

3rd Jul 2018, 11:06 AM
Roff Bilex
Roff Bilex - avatar
2 Answers
+ 2
returning a value isn't the same as executing the instructions within a method, you'll notice the first one has a return statement but the void one does not. so, void methods do not return a value
3rd Jul 2018, 11:13 AM
hinanawi
hinanawi - avatar
+ 2
Returning VALUE means that method returns number, string or any other data. Void is when method does not return anything. It might be printing text on screen, but does not return any value. For exanple: System.out.println will only print text to screen. Nothing will be returned, no number or thing like that. Sum method will calculate sum and will return int. That's why sum method can be asigned to variable. I hope this helps😝
3rd Jul 2018, 11:17 AM
Sad
Sad - avatar