What is void vs value-returning method in Java Please elaborate it in an easy to understand manner and provide a short examples to elaborate You have to explain it such that high schools students an c
In Java, a method is a set of instructions that performs a specific task. There are two types of methods: void methods and value-returning methods.
A void method is a method that does not return a value. It performs a task or an action and then completes its execution. For example, a void method might print something to the console or change the value of a variable. Here is an example of a void method that prints a message to the console:
public void sayHello() {
System.out.println("Hello!");
}
In this example, the method is called "sayHello" and it does not take any arguments (inputs). When the method is called, it will simply print "Hello!" to the console.
On the other hand, a value-returning method is a method that does return a value. It performs a task or an action and then returns a value to the caller. For example, a value-returning method might perform a calculation and then return the result. Here is an example of a value-returning method that calculates the area of a rectangle:
public int calculateArea(int length, int width) {
int area = length * width;
return area;
}
In this example, the method is called "calculateArea" and it takes two arguments: "length" and "width". The method calculates the area of the rectangle using the formula "length * width" and then returns the result. The result is an integer value, so the method has a return type of "int".
To summarize, void methods do not return a value and value-returning methods do return a value. Void methods are used when you want to perform a task or an action without returning a value, while value-returning methods are used when you want to perform a task or an action and then return a result.
原文地址: https://www.cveoy.top/t/topic/Yjf 著作权归作者所有。请勿转载和采集!