- Java Programming Basics
- Java Tutorial
- Java Environment Setup
- Java Separators
- Java Data Types
- Java Variables
- Java Variable Scope
- Java Type Casting
- Java Operators
- Java Increment Decrement
- Java Left Shift
- Java Right Shift
- Java Bitwise Operators
- Java Ternary Operator
- Java Control Statements
- Java if-else statement
- Java for Loop
- Java while Loop
- Java do-while Loop
- Java switch Statement
- Java break Statement
- Java continue Statement
- Java Popular Topics
- Java Arrays
- Java Multidimensional Array
- Java Strings
- Java Methods
- Java Date and Time
- Java Exception Handling
- Java File Handling
- Java OOP
- Java Classes and Objects
- Java Constructors
- Java Constructor Overloading
- Java Object as Parameter
- Java Returning Objects
- Java Encapsulation
- Java Abstraction
- Java Inheritance
- Java Polymorphism
- Java Packages
- Java Import Statement
- Java Multithreading
- Java Suspend Resume Stop Thread
- Java Programming Examples
- Java Programming Examples
Methods in Java with examples
A method in Java is a section of code that completes a particular task. Large, complex programs are divided into smaller, easier-to-manage pieces using this technique. Classes contain declarations of methods, which are accessible from anywhere in the program.
A method, in other words, is a block of code that performs a specific task and can be called (invoked) from other parts of the program. Methods are used to encapsulate functionality, encourage code reuse, and improve the code's maintainability and readability.
Method definition in Java
In Java, the basic syntax for defining a method is as follows:
[access modifier] [static] [return type] [method name]([parameter list]) {
// method body or block of code to define the method
return [return value];
}
In the above general form of the method definition in Java,
- access modifier: The visibility of the method is specified by the access modifier (public, private, protected, or default).
- static: Indicates whether the method belongs to the class itself (static method) or to the class's instances (instance method).
- return type: Specifies the data type of the method's returned value, or void if the method does not return a value.
- method name: Specifies the name of the method.
- parameter list: Specifies the method's input parameters, enclosed in parentheses and separated by commas.
- return value: Specifies the value that the method will return, if any.
Java method example
The following Java program is an example demonstrating the method.
public class MethodExample { public static void main(String[] args) { myMethod(); } public static void myMethod() { System.out.println("Hello there, I'm Edwin"); } }
Hello there, I'm Edwin
In this example, I define a class called MethodExample, which contains two methods: main() and myMethod(). The execution of a Java program always begins with the main() method. Inside the main() method, the method myMethod() was invoked or called, which in turn caused the program to output "Hello there, I'm Edwin" to the output console.
The myMethod() method is defined as a static method, which means that it belongs to the class rather than to an instance of the class.
Now let's create another example demonstrating the methods with parameters in Java.
public class MethodExample { public static void main(String[] args) { int a = 50; int b = 100; myMethod(a, b); } public static void myMethod(int x, int y) { int sum = x + y; System.out.println("The sum of " + x + " and " + y + " is " + sum); } }
The sum of 50 and 100 is 150
In the main method, two integer variables a and b are declared and initialized with the values 50 and 100 respectively. Then, the myMethod method is called with a and b as arguments. The myMethod method takes two integer parameters x and y, calculates their sum and assigns it to a local variable named sum. It then prints a message on the console which includes the values of x, y and sum using string concatenation.
When the myMethod method is called in the main method, it receives the values of a and b as arguments and performs the addition operation on them, and then prints the result on the output console.
The "x" and the "y" variables inside the "myMethod" are considered the formal parameters, which receive the copies of "a" and "b". So anything changed does not reflect the original value of "a" and "b" inside the main function. So this way of calling a method in Java with parameters can be called a call-by-value approach. However, to work with the actual value of the arguments passed to the method from the main method, you can approach it using the call-by-reference. As an example:
public class JavaMethodExample { public static void main(String[] args) { int a = 100; int b = 200; // Swap using call by value swapByValue(a, b); System.out.println("After swapping using the call-by-value approach:\n a = " + a + ", b = " + b); // Swap using call by reference int[] arr = new int[]{a, b}; swapByReference(arr); System.out.println("\nAfter swapping using the call-by-reference approach:\n a = " + arr[0] + ", b = " + arr[1]); } public static void swapByValue(int x, int y) { int temp = x; x = y; y = temp; } public static void swapByReference(int[] arr) { int temp = arr[0]; arr[0] = arr[1]; arr[1] = temp; } }
After swapping using the call-by-value approach: a = 100, b = 200 After swapping using the call-by-reference approach: a = 200, b = 100
In the call by reference approach, the actual parameters (a and b) are stored in an array and a reference to this array is passed to the swapByReference method. This means that the formal parameter (arr) of the method points to the same memory location as the actual parameter array.
Java method that returns a value
The following Java program uses a method named "FindSum()" to find the sum of two values and returns the addition or summation value.
public class MethodExample { public static void main(String[] args) { int a = 50; int b = 100; int sum = FindSum(a, b); System.out.println("The sum of " + a + " and " + b + " is " + sum); } public static int FindSum(int m, int n) { int result = m + n; return result; } }
The sum of 50 and 100 is 150
Now let's modify the above program to allow the user to enter the values of "a" and "b" at run time of the program.
import java.util.Scanner; public class MethodExample { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter the value of a: "); int a = input.nextInt(); System.out.print("Enter the value of b: "); int b = input.nextInt(); int sum = FindSum(a, b); System.out.println("\nThe sum of " + a + " and " + b + " is " + sum); input.close(); } public static int FindSum(int m, int n) { int result = m + n; return result; } }
Enter the value of a: 10 Enter the value of b: 20 The sum of 10 and 20 is 30
In the following code fragment from this example:
public static int FindSum(int m, int n) { int result = m + n; return result; }
- public: All other classes in the same or different packages can see the method.
- static: The method belongs to the class as a whole, not to individual instances of the class.
- int: The method returns an integer value.
- FindSum: The name of the method is "FindSum".
- (int m, int n): The method accepts two integer parameters, "m" and "n."
- int result = m + n;: The method body computes and stores the sum of the two parameters in a local variable called "result."
- return result;: The method returns the value of the variable "result."
Methods such as instance methods, constructors, abstract methods, and so on will be covered later in this Java tutorial series. Because these methods fall under the category of object-oriented concepts, they will be discussed or covered after the fundamentals of object-oriented concepts such as classes and objects have been covered. Don't worry, just keep following or continuing this tutorial series; everything needed for beginners will be covered one by one.
« Previous Tutorial Next Tutorial »