+ 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?
9 ответов
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.
+ 1
JavaBobbo so what you are saying is if i dont put void in any part then a value could change?
+ 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
+ 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?)
+ 1
Dan Walker JavaBobbo thatnks guys that both really helped
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
0
Everytime you wanna use ''return'' you need to replace the void with the data type you wanna change.
0
Take a extra look at the examples i gave you and you will understand
0
Yes exactly