Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

what is void in programming?

can any one explain me why use void and when please explain in brief

2 Answers

Void is used when there is no return, for example, You could make a constructor like

public String onColorSwitch(String color) { return color; }

but if you aren't going to return anything, then you could use,

public void onColor() {

}

Void basically means "no type", "no value" or "empty". Void is most commonly used in functions and methods. If you have worked with functions before, this might help you understand better:

java\main.java
functions f = new functions();
String message = "Hello world!";
f.print_func(message);
java\functions.java
public void print_func(String var) {
   System.out.println(var);
}

In our main class we make a string with the value "Hello world!" and then call the function print_func with that message as the argument. The function takes the argument and prints it out and returns nothing back to the main class because there is nothing that functions calculated or created -- it just printed a message to the user. This is why we declared our function as a void -- it passes nothing back to it's caller once it's finished running.

An example where void shouldn't be used:

java\main.java
functions f = new functions();
int number = 5;
int new_number = 0;
new_number = f.calc_func(number);
System.out.println(new_number);
java\functions.java
public int calc_func(int var) {
   int new_number = var * 2;
   return new_number;
}

In this example, our function takes a number (in this case the number "5") and calculates it's double (5 x 2 = 10 in this example). Once the function has completed this calculation, our main class needs to know what was calculated, so the function needs to return this value back to it's caller. The main class get's the value and stores it in new_number which is then printed out to the user.

So whenever you create a function or method in java, you need to tell java the type that is being returned (int, String, etc). If nothing is returned, then you need to tell this by using void where applicable.

Void can also be used as a pointer for unknown types, but that's a bit advanced.

Hope this helps! :)