Void keyword and void method

void keyword:

 Void keyword is used with the method declaration to specify that this particular method is not going to return any value after completing its execution. We can’t assign the return type of a void method to any variable because void is not a data type.

void method:

Look at the following program that demonstrate how a method is defined and called. In this program, we have defined a method displayLine that displays a line. Execution of program start from main and when it encounters statment displayLine() control passes to method and after execution of the code of method control comes back to next statement of main method.

/**
 *   This program defines and calls a method.
 */
public class MethodDemo
{
   public static void main(String[] args)
   {
      System.out.println("Advantage of methods.");
      displayLine();
      System.out.println("Write once use many times");
      displayLine();
   }

   /**
    *      The displayLine method displays a line.
    */
   public static void displayLine()
   {
      for (int i = 1; i <= 40; i++)
      {
         System.out.print("_");
      }

      System.out.println(" ");
   }
}

Output :

Advantage of methods.
________________________________________
Write once use many times
________________________________________


Method definition

Method definition has two parts, header and body. Following figure explain each of these parts.

method-parts

Calling a Method

To call a method, simply type the name of the method followed by a set of parentheses. As we used in above example.

displayLine();

Here, in the following example we’re considering a void method is method rank points. This method is a void method, which does not return any value. Call to a void method must be a statement i.e. method rank points. It is a Java statement which ends with a semicolon as shown in the following example.

Example

 

public class ExampleVoid {

   public static void main(String[] args) {
      methodRankPoints(255.7);
   }

   public static void methodRankPoints(double points) {
      if (points >= 202.5) {
         System.out.println("Rank:A1");
      }else if (points >= 122.4) {
         System.out.println("Rank:A2");
      }else {
         System.out.println("Rank:A3");
      }
   }
}

This will produce the following result −

Output

Rank:A1

Reference:

https://www.tutorialspoint.com/java/java_methods.htm#:~:text=The%20void%20keyword%20allows%20us,statement%20i.e.%20methodRankPoints(255.7)%3B.

https://www.w3schools.com/java/ref_keyword_void.asp#:~:text=The%20void%20keyword%20specifies%20that,not%20have%20a%20return%20value.

http://www.beginwithjava.com/java/methods/void-methods.html

https://examples.javacodegeeks.com/what-does-void-mean-in-java/

Leave a comment

Design a site like this with WordPress.com
Get started