Write a function to multiply 2 numbers
Java is a popular programming language that's widely used in developing a range of applications. In this article, we'll explore how to write a function to multiply two numbers in Java.
To begin with, a function is a self-contained code unit that performs a specific task. In Java, we use the "public" keyword to indicate that a function is available to other parts of the program. For instance, to write a function that multiplies two numbers, we would start by declaring the function as follows:
Java public static int multiply(int num1, int num2) {
int result = num1 * num2;
return result;
}
The above function takes two integer arguments, "num1" and "num2," and returns their product. The "static" keyword means that the function belongs to the class, not to an instance of the class.
To use this function in your program, you need to call it from another part of your code. Here's an example of how to call the "multiply" function:
Javaint a = 5;
int b = 10;
int result = multiply(a, b);
System.out.println(result);
In the above example, we declare two integer variables "a" and "b" and assign them values of 5 and 10, respectively. We then call the "multiply" function, passing in the two variables, and assign the result to a new variable called "result." Finally, we print the value of "result" to the console.
Writing a function to multiply two numbers in Java is a simple task that can make your code more efficient and reusable. By encapsulating the multiplication operation in a function, you can easily call it from different parts of your program, saving you time and reducing the chances of introducing errors.
In conclusion, the "multiply" function we've shown is just one example of how you can write functions to perform specific tasks in Java. Functions can simplify your code and make it more readable and maintainable. So, go ahead and try writing your own functions to perform different operations in your Java programs.
Here the long and simple java program to function to multiply 2 numbers.
import java.util.*;
public class Functions {
//Multiply 2 numbers
public static int multiply(int a, int b) {
return a*b;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int result = multiply(a, b);
System.out.println(result);
}
}
Comments
Post a Comment