The method in Java or Methods of Java is a collection of statements that perform some specific task and return the result to the caller. Every method has a return type that can be differentiated between void and non-void. In this article, we will learn about void and non-void methods.
Void Methods in Java
The void method is a method that does not return any value. It is used to perform some action or operation but does not return any data.
Syntax:
public void methodName(parameter1, parameter2, …)
{
// body of the method
// do some operations here
// …
}
Example of Java void Method
// Java Program to demonstrate // Void Method in Java import java.io.*;
public class Example {
// void method that takes a string as input and prints
// it to the console
public static void printString(String input)
{
System.out.println(input);
}
// main method that calls the printString method
public static void main(String[] args)
{
// call the printString method with "Hello, World!"
// as the input
printString( "Hello, World!" );
}
} |
Output:
Hello, World!
Non-Void Methods in Java
The non-void method is a method that returns a value of a specific data type.It is used to the perform some calculation or operation and return.
Syntax of Java Non-Void
access_modifier return_type method_name(parameter_list)
{
// method body
return value;
}
Example of Non Void Methods
// Java Program to Demonstrate // Non Void Methods in Java import java.io.*;
public class Example {
// non-void method that takes two integers as input and
// returns their sum
public static int addNumbers( int num1, int num2)
{
int sum = num1 + num2;
return sum;
}
// main method that calls the addNumbers method and
// prints the result
public static void main(String[] args)
{
// call the addNumbers method with 5 and 7 as the
// inputs
int result = addNumbers( 5 , 9 );
System.out.println( "The sum of 5 and 9 is: "
+ result);
}
} |
Output:
The sum of 5 and 9 is: 14