The method "addOneToX()" does something, but doesn't return a value. That means I can write Demo d = new Demo(); d.addOneToX(); But I can't legally write Demo d = new Demo(); Q q = d.addOneToX(); no matter what "Q" is (i.e., int, String, or anything else.) You can't assign the return value of addOneToX() to a variable, because there is no return value.
Here�s a contrived example that uses two methods with a void. The first method go() is just a �Start Here� method used after instantiating an object of my class. This is done since main is a static method, I cannot call non-static methods without an object. The second method is simply a utility method I use to display an error message. It saves me from having to write the same code over and over to display an error. And is I decided I want to change how I display error messages (or maybe add code to log all error messages) I only have to do it in the one place (the displayError() method). There are many other time when you need a method to just do some work, but necessarily return any value.
Here's a couple of examples of methods that return void:
In the method baz() above, the method checkTwice() is a static method on a class called Santa. It could do something useful (like add and remove children from that list), therefore having an impact on the data when control is returned to baz()'s caller. It is still a void method, though, because it doesn't return anything. One thing to keep in mind is that when working with an immutable object (such as a String) or primitives, the caller will not see any changes you make as in the following examples:
In the case of badOne() above, because the argument a is a primitive, whatever int is passed in is a *copy* of the int the caller used. So if I caller did this:
Similarly, a caller passing in a String to badTwo() would not see a change:
The proper way to write those methods would be:
And these are of course no longer void methods, and the caller would have to assign the returned value to a variable in order to get the result. sev [ March 01, 2004: Message edited by: sever oon ]
'void' is the declaration equivalent of 'page intentionally left blank' so to speak. You explicitly declare that no, there is no return value, and no, it is not because you forgot about it. [ March 01, 2004: Message edited by: Maarten Vergouwen ]
Originally posted by Maarten Vergouwen: 'void' is the declaration equivalent of 'page intentionally left blank' so to speak. You explicitly declare that no, there is no return value, and no, it is not because you forgot about it.