☰ Contents The Main Thing

Into the Void

Student: Wait, you snuck something by me, didn’t you?
Prof: Hm?
Student: You never told me what void means in void main(). What type is that?
Prof: Good question as usual, you really are keeping me honest!
Student: I’m just trying to learn!
Prof: void is a a type that only makes sense in the return type position of a method definition. It means the method doesn’t return a value.
Student: It doesn’t return a value?
Prof: That’s right – the methods we’ve seen so far have always computed some value to return, like a new Pict or a int or String. main is different – its only job is to get the program started and have effects like printing. So it has no value to meaningfully return, and gets a void return type. Java expects and requires that it have that return type.
Student: Hmm. OK. Do we ever write other void methods?
Prof: You might if there are other methods you write that don’t return anything, but do some printing or other work that only has effects.

Practice

One of these prints a greeting; the other builds one and hands it back to whoever called it. Give each the return type it needs.
printGreeting(String name) {
System.out.println("Hello, " + name);
}

createGreeting(String name) {
return "Hello, " + name;
}