What does void do? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What does void do?

I have zero idea what void does. I don’t understand what “Return no value” means. Every time I look up what void does very answer says returns no value and that doesn’t mean anything. What doesn’t return a value? Where?

14th Sep 2018, 8:33 PM
JakHmakc
JakHmakc - avatar
9 Answers
0
Suppose I create a method that will take a product ID and a quantity as parameters. At the end of it, I want a result, which is the price of the transaction. How do I get hold of this result? My method must return a value, in this case maybe an int or double. int amount = calculateAmount(39583, 3); Another method may take a product ID and give me the name of the product. This must return a value too, which would be a String. String name = getProductName(48493); Yet another might update my stock list. In this case, I don't want anything returned, just an operation to take place (e.g. reduce the available stock by 1). In this case there is no information I need to 'get hold of' so nothing is returned. This will have a void return type for this reason. updateStock(48596, 2); in the first two examples the method "returns" a value which I can assign to a variable, but in the last case I can't, since there is nothing to assign, because nothing is returned.
15th Sep 2018, 2:02 AM
Dan Walker
Dan Walker - avatar
+ 1
JavaBobbo so what you are saying is if i dont put void in any part then a value could change?
14th Sep 2018, 8:42 PM
JakHmakc
JakHmakc - avatar
+ 1
JavaBobbo I dont understand the examples your explanation of void and how it doesnt return a value doesnt make sense. im new so nothing makes sense
14th Sep 2018, 9:02 PM
JakHmakc
JakHmakc - avatar
+ 1
JavaBobbo when it “returns” something does it mean change a value ( like changing the value when you make x = x + y or when you add subtract multiply or divide two values?)
14th Sep 2018, 9:03 PM
JakHmakc
JakHmakc - avatar
+ 1
Dan Walker JavaBobbo thatnks guys that both really helped
15th Sep 2018, 4:17 AM
JakHmakc
JakHmakc - avatar
0
You use void when you dont want the method to return anything, for example This method does not return anything so i use void: public void aMethod(){ System.out.println("Hello"); } But this method return a value of type int so i replace the void with data type: public int aMethod(int x, int y){ return x * y; } If you wanna return a value of typ double: public double aMethod(int x, int y){ return x * y; } Hope it helps
14th Sep 2018, 8:40 PM
JavaBobbo
JavaBobbo - avatar
0
Everytime you wanna use ''return'' you need to replace the void with the data type you wanna change.
14th Sep 2018, 8:49 PM
JavaBobbo
JavaBobbo - avatar
0
Take a extra look at the examples i gave you and you will understand
14th Sep 2018, 8:55 PM
JavaBobbo
JavaBobbo - avatar
0
Yes exactly
14th Sep 2018, 9:08 PM
JavaBobbo
JavaBobbo - avatar