You are on page 1of 2
QB Penseum Void Methods vs Value-Returning Methods Void Methods * Avoid method performs a task and terminates. * It does not return any value back to the code where it was called. * Example: System.out.print1n("Hello, world!"); * This method prints out "Hello, world!" and then terminates. Value-Returning Methods * Avalue-returning method performs a task and returns a value back to the code where it was called. * Example: Math.pow(2, 3)5 * This method calculates 2 to the power of 3 and returns the result * The returned value can be assigned to a variable for further use. Example: Void Method public static void add(int x, int y) { system.out.print1n(x + y)5 } * This method takes two numbers as parameters (x and y) and prints out their sum. * Calling add(2, 5); will print out 7 on the screen Example: Value-Returning Method public static int add(int x, int y) { return x + y; + * This method takes two numbers as parameters (x and y) and returns their sum. “Calling int answer = add(2, 5); will assign the value 7 to the variable answer. "The returned value can be used in further calculations or printed out. Note: When calling a value-retuming method, you need to do something with the returned value, such as assigning it to a variable or using it in an expression. # Value-Returning Methods In Java, methods can either be value-returning or void methods. Value-returning methods are those that perform a task and then return a value back to the caller. This value can be of any data type, such as an integer, double, or even a custom object. ‘Syntax The syntax for defining a value-returning method is as follows: public () { /{ method body return ; Example Let's consider the following example: public class Example { public static void main(string[] args) { int result = add(4, 8); system.out.printIn("The sum of four plus 8 is + result); public static int add(int num1, int num2) { int sum = numa + num2; return sum; t In this example, we have a value-returning method called add that takes two integers as parameters and returns their sum. The main method calls the add method and assigns the returned value to the variable result. Finally, the System.out.println statement prints the result. Key Points * Value-returning methods have a return statement at the end, which specifies the value to be returned. * The return type of a value-returning method determines the type of value that can be returned. * Value-returning methods can be assigned to variables of the same data type as the return type. * Value-returning methods can have any number of parameters, as long as the parameter types match the method signature

You might also like