Alice Alice - 4 years ago 190
Java Question

What does void do in java?

The return type—the data type of the value returned by the method, or void if the method does not return a value.

Okay, then.. Here is my question:

public class EnumTest {
Day day;

public EnumTest(Day day) { = day;

public void tellItLikeItIs() {
switch (day) {
case MONDAY: System.out.println("Mondays are bad.");

case FRIDAY: System.out.println("Fridays are better.");

case SUNDAY: System.out.println("Weekends are best.");

default: System.out.println("Midweek days are so-so.");

public static void main(String[] args) {
EnumTest firstDay = new EnumTest(Day.MONDAY);
EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
EnumTest fifthDay = new EnumTest(Day.FRIDAY);
EnumTest sixthDay = new EnumTest(Day.SATURDAY);
EnumTest seventhDay = new EnumTest(Day.SUNDAY);


The above code does not work without void.

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method tellItLikeItIs() is undefined for the type EnumTest

What did I miss out?
Why is there a void in there?
And it does return a string?

Answer Source

The reason the code will not work without void is because the System.out.println(String string) method returns nothing and just prints the supplied arguments to the standard out terminal, which is the computer monitor in most cases. When a method returns "nothing" you have to specify that by putting the void keyword in its signature.

You can see the documentation of the System.out.println here:

To press the issue further, println is a classic example of a method which is performing computation as a "side effect."

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download