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:
- 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
- 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
- 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.