Java Operators

Java Control Statements

Object Oriented Programming

Java Built-in Classes

Java File Handling

Java Error & Exceptions

Java Multithreading

Java Synchronization

Java Networking

Java Collections

Java Interfaces

Java Data Structures

Java Collections Algorithms

Advanced Java

Java Miscellaneous

Java APIs & Frameworks

Java Class References

Java Useful Resources

Java - void keyword



The void keyword allows us to create methods which do not return a value. Here, in the following example we're considering a void method methodRankPoints. This method is a void method, which does not return any value. Call to a void method must be a statement i.e. methodRankPoints(255.7);. It is a Java statement which ends with a semicolon as shown in the following example.

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

Example

In this example, we've created a static method methodRankPoints() which is not returning any value. As method is not returning any value, it's return type is marked as void. Once defined, this method is called without assigning this method response to any variable. As method is printing a statement based on parameter passed, executing program results in a printed statement.

package com.tutorialspoint;

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");
      }
   }
}

Output

Rank:A1

Example

In this example, we've created a static method methodRankPoints() which is not returning any value. As method is not returning any value, it's return type is marked as void. Once defined, this method is called but assigning this method response to a variable. As method return type is void, this will result in compilation error.

package com.tutorialspoint;

public class ExampleVoid {

   public static void main(String[] args) {
      int result = 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");
      }
   }
}

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Type mismatch: cannot convert from void to int

	at com.tutorialspoint.ExampleVoid.main(ExampleVoid.java:6)
java_basic_syntax.htm
Advertisements