English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, you will learn about Java methods through examples, how to define methods, and how to use methods in Java programs.
In mathematics, we may have already studied functions. For example, f(x) = x2x is a function that returns a square value.
If x = 2, then f(2) = 4 If x = 3, f(3) = 9 and so on.
Similarly, in computer programming, a function is a block of code that performs a specific task.
In object-oriented programming, this is a term used for functions. Methods are bound to classes and define the behavior of the class.
Before learning methods, make sure you understandJava Classes and Objects.
Java has two types of methods: those defined by the user and those available in the standard library.
Standard library methods
User-defined methods
Standard library methods are built-in methods in Java that can be used at any time. These standard libraries appear together with the Java class library (JCL) in the Java archive files (JAR) of the JVM and JRE.*.jar)
For example,
print() - It is a method of java.io.PrintStream. The print("…") method prints a string enclosed in quotes.
sqrt() - It is a method in mathematics class. It returns the square root of a number.
Here is a working example:
public class Main {}} public static void main(String[] args) { //Using the sqrt() method System.out.print("4The square root is: " + Math.sqrt(4)); } }
Output:
4The square root is: 2.0
We can also create our own chosen methods to perform certain tasks. This method is called a user-defined method.
This is how we create methods in Java:
public static void myMethod() { System.out.println("My function"); }
Here, we have created a method named myMethod(). We can see that we have used public, static, and void before the method name.
public - Access modifier. This means that the method can be accessed from anywhere. For more information, please visitJava Access Modifiers
static - This means that the method can be accessed without any object. For more information, please visitJava Static Keyword.
void - This means that the method does not return any value. We will learn more about this in the later part of this tutorial.
This is a simple example of how we create a method. However, the complete syntax for method definition in Java is:
modifier static returnType nameOfMethod (parameters) { // method body }
Here,
modifier - It defines the access method as public, private, etc.
static - If the static keyword is used, it can be accessed without creating an object.
For example, the sqrt() method of the standard Math class is static. Therefore, we can call Math.sqrt() directly without creating an instance of the Math class.
returnType - It specifies the type of the value returned by the method. For example, if the method has an int return type, it returns an integer value.
A method that can return a primitive data type (int, float, double, etc.), an original object (String, Map, List, etc.), or any other built-in and user-defined objects.
If the method does not return a value, its return type is void.
nameOfMethod - It is aidentifier, used to refer to a specific method in the program.
We can name the method anything. However, it is more conventional to name it after the task it performs. For example, calculateArea(), display(), etc.
parameters (arguments) - These are the values passed to the method. We can pass any number of parameters to a method.
method body - It includes programming statements used to perform certain tasks. The method body is enclosed in curly braces { }.
Now that we know how to define a method, we need to learn how to use it. To do this, we must call the method. Here's how
myMethod();
This statement calls the method myMethod() previously declared.
When executing the program code, it encounters myFunction() in the code.
Then, branch to the myFunction() method and execute code inside the method body.
After the method body is executed, the program returns to its original state and executes the next statement after the method call.
Let's see how to use methods in a Java program.
class Main { public static void main(String[] args) { System.out.println("A kind of method is about to be encountered."); //call the method myMethod(); System.out.println("The method has executed successfully!"); } // method definition private static void myMethod(){ System.out.println("Printed from inside myMethod()!"); } }
Output:
A kind of method is about to be encountered. Printed from inside myMethod()! The method has executed successfully!
In the above program, we have a method named myMethod(). This method does not accept any parameters. Similarly, the return type of the method is void (meaning it does not return any value).
In this case, the method is static. Therefore, we called the method without creating an object of the class.
Let's look at another example
class Main { public static void main(String[] args) { //Create an object of the Output class Output obj = new Output(); System.out.println("A method is about to be encountered."); //Call the myMethod() of the Output class obj.myMethod(); System.out.println("The method has executed successfully!"); } } class Output { //public: This method can be called from outside the class public void myMethod() { System.out.println("Printed from inside myMethod()."); } }
Output:
A method is about to be encountered. Printed from inside myMethod(). The method has executed successfully!
In the above example, we created a method named myMethod(). This method is located in a class named Output.
Since the method is not static, it is called using an object of the obj class.
obj.myMethod();
As mentioned before, Java methods can have zero or more parameters. And, they may also return some values.
Let's take a method with a return value as an example.
class SquareMain { public static void main(String[] args) { int result; //call the method and store the returned value result = square(); System.out.println("10the square value is: " + result); } public static int square() { //return statement return 10 * 10; } }
Output:
10The square value is: 100
In the above program, we created a method named square(). This method does not accept any parameters and returns a value of10 *10.
Here, we mention that the return type of the method is int. Therefore, the method should always return an integer value.
As we have seen, the scope of this method is limited because it always returns the same value. Now, let's modify the above code snippet to make it always return the square value of any integer passed to the method, not always10The square value is.
public class Main {}} public static void main(String[] args) { int result, n; n = 3; result = square(n); System.out.println("3The square is: " + result); n = 4; result = square(n); System.out.println("4The square is: " + result); } // Methods static int square(int i) { return i * i; } }
Output:
3The square is: 9 4The square is: 16
Here, the square() method accepts a parameter i and returns the square of i. The returned value is stored in the variable result.
If we pass any other data type instead of an int value, the compiler will throw an error. This is because Java is a strongly typed language.
The parameters passed to the getSquare() method during the method call are called actual parameters.
result = getSquare(n);
The parameters accepted by the method definition are called formal parameters. The type of formal parameters must be explicitly typed.
public static int square(int i) {...}
We can also use commas to pass multiple parameters to Java methods. For example,
public class Main {}} //Method Definition public static int getIntegerSum (int i, int j) { return i + j; } // Method Definition public static int multiplyInteger (int x, int y) { return x * y; } public static void main(String[] args) { //call the method System.out.println("10 + 20 = " + getIntegerSum(10, 20)); System.out.println("20 x 40 = " + multiplyInteger(20, 40)); } }
Output:
10 + 20 = 30 20 x 40 = 800
Note: The data types of actual parameters and formal parameters should match, that is, the data type of the first actual parameter should match the data type of the first formal parameter. Similarly, the type of the second actual parameter must match the type of the second formal parameter, and so on.
1. The main advantage isCode Reusability. We can write a method once and use it multiple times. We do not have to rewrite the entire code each time. We can consider it as a "write once, reuse multiple timesFor example,
public class Main {}} //Method Definition private static int getSquare(int x){ return x * x; } public static void main(String[] args) { for (int i = 1; i <= 5; i++) { //Method Call int result = getSquare(i); System.out.println("" + i + "The square is: " + result); } } }
Output:
1 The square is: 1 2 The square is: 4 3 The square is: 9 4 The square is: 16 5 The square is: 25
In the above program, we created a method named getSquare() to calculate the square of a number. Here, the same method is used to calculate the square of numbers less than6of the square of the number.
Therefore, we repeatedly use the same method
Methods2Making codeMore readable,Easier to debugFor example, the getSquare() method is very readable, so we can know that this method calculates the square of a number.