Java

Methods

Java / Methods

Methods

Java Methods

Java methods are blocks of code inside a program that perform a specific task and run only when they are called. They are also known as functions. Methods help you reuse code, so you can write it once and use it many times.

Β 

Create a Method

A method in Java is created by writing a block of code inside a class with a name and parentheses (). It is used to perform a specific task and can be called whenever needed. Methods help us reuse code and organize programs better.

Call Method

Calling a method in Java means using the method by its name so that the code written inside it gets executed (runs). A method only works when it is called from the main() method or another method.

Example

public class Main {

Β // Creating a method
Β static void showMessage() {
Β  Β System.out.println("Hello! This is a method call example.");
Β }

Β public static void main(String[] args) {

Β  Β // Calling the method
Β  Β showMessage();
Β }
}

Method Overloading

Method overloading in Java means a class can have more than one method with the same name but different parameters (different number, type, or order of parameters). It is used to make code more readable and reusable. With method overloading, multiple methods can share the same name but work with different inputs. Β 

Example

public class Main {

Β // Method with one parameter
Β static void show(int a) {
Β  Β System.out.println("Value: " + a);
Β }

Β // Method with two parameters
Β static void show(int a, int b) {
Β  Β System.out.println("Sum: " + (a + b));
Β }

Β // Method with different type
Β static void show(String name) {
Β  Β System.out.println("Name: " + name);
Β }

Β public static void main(String[] args) {

Β  Β // Calling different overloaded methods
Β  Β show(10);
Β  Β show(10, 20);
Β  Β show("Java");
Β }
}

Technology
Java
want to connect with us ?
Contact Us