void keyword in java

The "void" keyword can be used as the return type of a method to indicate that the method does not return a value.

Example:

1
2
3
4
5
6
7
8
 public class Employee
 {
      public void greeting(String name);
      {
            System.out.println("Welcome to "+name);
             // no return
      }
 }
 public class Employee
 {
      public void greeting(String name);
      {
            System.out.println("Welcome to "+name);
             // no return
      }
 }


We can also specify empty return for void methods as below

1
2
3
4
5
6
7
8
 public class Employee
 {
      public void greeting(String name);
      {
          System.out.println("Welcome to "+name);
          return;
      }
 }
 public class Employee
 {
      public void greeting(String name);
      {
          System.out.println("Welcome to "+name);
          return;
      }
 }


Calling void method should not assign anything as return value

So calling above void method is as below

1
2
Employee e1 - new Employee();
e1.greeting("Ram");
Employee e1 - new Employee();
e1.greeting("Ram");

Note:
We should use void as the return type of a method when we dont want any return value from the method but only need to execute some code inside a method.

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on