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.  public class Employee
  2.  {
  3.       public void greeting(String name);
  4.       {
  5.             System.out.println("Welcome to "+name);
  6.              // no return
  7.       }
  8.  }
 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.  public class Employee
  2.  {
  3.       public void greeting(String name);
  4.       {
  5.           System.out.println("Welcome to "+name);
  6.           return;
  7.       }
  8.  }
 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. Employee e1 - new Employee();
  2. 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

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