Thursday, July 10, 2008

The void Type


void can be the most confusing type. It's an odd word to start with. It's part of the long string of words that appear before the word main in the declaration of that method.

Void means 'empty' or 'nothing'. In the case of a Java method, it means that that method returns nothing:

public void drawTriangle(){ ...

This is as opposed to a method with another type, which returns an object of that type:

public int sum(int a, b){
return a + b;

This returns an int object to the caller:

int count1, count2, amt;
amt=sum(count1, count2);

Why would you want a method that returns nothing? Because often you have methods that do something that doesn't affect the state of the program itself. Drawing something is an example of this. A method that draws something makes its results obvious in what it draws. It doesn't need to pass any information back to the other parts of the program. Instead it is expressing the state of the program to the outside world.