Difference Between Void and Non Void Methods in Java
Last Updated :
22 Sep, 2023
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
import java.io.*;
public class Example {
public static void printString(String input)
{
System.out.println(input);
}
public static void main(String[] args)
{
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
import java.io.*;
public class Example {
public static int addNumbers( int num1, int num2)
{
int sum = num1 + num2;
return sum;
}
public static void main(String[] args)
{
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
Share your thoughts in the comments
Please Login to comment...