Defining Methods in Java with Syntax and Examples

0

1. Defining Methods in Java

A method is a block of code that performs a specific task.

Methods help organize code into smaller reusable units.

Instead of writing the same logic multiple times, developers can place the logic inside a method and call it whenever needed.


2. Why Methods are Used

Methods improve code quality and reduce repetition.

  • a. Reuse code easily
  • b. Reduce duplicate code
  • c. Improve readability
  • d. Simplify debugging
  • e. Organize large programs
  • f. Improve maintainability

3. Where Methods are Used

Methods are used in almost every Java application.

  • a. Banking systems
  • b. Web applications
  • c. Android applications
  • d. Game development
  • e. Automation systems
  • f. Enterprise software

4. Basic Structure of a Method

A method contains multiple parts that define its behavior.


4.1 General Syntax

returnType methodName() {

    // method body

}

The method body contains the logic that executes when the method is called.


4.2 Parts of a Method

Part Purpose
returnType Specifies returned value type
methodName Name of the method
() Parameter section
{ } Method body

5. Defining a Simple Method

A method can perform a task without returning any value.


5.1 Method Without Return Value

public class Main {

    static void greet() {

        System.out.println("Welcome to Java");
    }

    public static void main(String[] args) {

        greet();
    }
}

The greet() method prints a welcome message when called.


The void keyword means the method does not return any value.


6. Understanding Method Call

A method executes only when it is called.


6.1 Calling a Method Multiple Times

public class Main {

    static void display() {

        System.out.println("Java Method");
    }

    public static void main(String[] args) {

        display();
        display();
        display();
    }
}

The same method executes multiple times without rewriting the code.


7. Methods with Return Values

Some methods return data back to the caller.


7.1 Returning Integer Value

public class Main {

    static int getNumber() {

        return 100;
    }

    public static void main(String[] args) {

        int result = getNumber();

        System.out.println(result);
    }
}

The method returns the integer value 100.


7.2 Returning String Value

public class Main {

    static String getLanguage() {

        return "Java";
    }

    public static void main(String[] args) {

        System.out.println(getLanguage());
    }
}

The method returns a String value.


The returned value type must match the declared return type.


8. Understanding static Methods

The static keyword allows methods to be called without creating objects.


8.1 Example of static Method

public class Main {

    static void showMessage() {

        System.out.println("Static Method");
    }

    public static void main(String[] args) {

        showMessage();
    }
}

The static method is called directly using the class context.


9. Understanding Non-static Methods

Non-static methods belong to objects.


9.1 Example of Non-static Method

public class Main {

    void display() {

        System.out.println("Non-static Method");
    }

    public static void main(String[] args) {

        Main obj = new Main();

        obj.display();
    }
}

An object is required to call a non-static method.


10. Methods with Parameters

Parameters allow methods to receive input values.

These values can be used inside the method body.


10.1 Single Parameter Method

public class Main {

    static void greet(String name) {

        System.out.println("Welcome " + name);
    }

    public static void main(String[] args) {

        greet("Rahul");
    }
}

The value Rahul is passed into the method parameter.


10.2 Multiple Parameters

public class Main {

    static void add(int a, int b) {

        System.out.println(a + b);
    }

    public static void main(String[] args) {

        add(10, 20);
    }
}

The method receives two integer values and prints their sum.


Parameters act like local variables inside methods.


11. Understanding Arguments and Parameters

Parameters and arguments are closely related concepts.


Concept Description
Parameter Variable inside method definition
Argument Actual value passed during method call

11.1 Example of Parameters and Arguments

public class Main {

    static void square(int number) {

        System.out.println(number * number);
    }

    public static void main(String[] args) {

        square(5);
    }
}

number is the parameter and 5 is the argument.


12. Return Statement in Methods

The return statement sends data back to the caller.


12.1 Returning Calculation Result

public class Main {

    static int multiply(int a, int b) {

        return a * b;
    }

    public static void main(String[] args) {

        int result = multiply(4, 5);

        System.out.println(result);
    }
}

The multiplication result is returned back to main().


12.2 Returning Boolean Value

public class Main {

    static boolean isAdult(int age) {

        return age >= 18;
    }

    public static void main(String[] args) {

        System.out.println(isAdult(20));
    }
}

The method returns true because age 20 is greater than or equal to 18.


A method with a non-void return type must return a value.


13. Method Execution Flow

Java executes methods step-by-step during runtime.


13.1 Understanding Execution Sequence

  • a. main() method starts execution
  • b. A method call occurs
  • c. Control moves to the called method
  • d. Method logic executes
  • e. Control returns back to the caller

13.2 Example of Method Flow

public class Main {

    static void first() {

        System.out.println("First Method");
    }

    static void second() {

        System.out.println("Second Method");
    }

    public static void main(String[] args) {

        first();

        second();
    }
}

Methods execute in the same order in which they are called.


14. Internal Working of Methods

Internally, Java stores method information in memory during program execution.


14.1 Stack Memory and Methods

Each method call creates a separate memory block inside the stack memory.


public class Main {

    static void test() {

        int number = 10;

        System.out.println(number);
    }

    public static void main(String[] args) {

        test();
    }
}

Local variables and method data are stored temporarily inside stack memory.


14.2 Method Completion

When a method finishes execution, its stack memory is automatically removed.


public class Main {

    static void show() {

        System.out.println("Method Finished");
    }

    public static void main(String[] args) {

        show();
    }
}

After the show() method completes, Java removes its memory block from the stack.


Every method call gets its own separate stack frame.


15. Nested Method Calls

One method can call another method.


15.1 Example of Nested Calls

public class Main {

    static void second() {

        System.out.println("Second Method");
    }

    static void first() {

        System.out.println("First Method");

        second();
    }

    public static void main(String[] args) {

        first();
    }
}

The first() method internally calls the second() method.


16. Common Beginner Mistakes


16.1 Missing Return Statement

Methods with non-void return types must return a value.


public class Main {

    static int getValue() {

    }

    public static void main(String[] args) {

        System.out.println(getValue());
    }
}

This code causes a compilation error because no value is returned.


Every non-void method must contain a valid return statement.


16.2 Wrong Return Type

public class Main {

    static int getText() {

        return "Java";
    }

    public static void main(String[] args) {

        System.out.println(getText());
    }
}

This code causes a type mismatch error because the method expects an integer return value.


16.3 Calling Non-static Method Incorrectly

public class Main {

    void display() {

        System.out.println("Java");
    }

    public static void main(String[] args) {

        display();
    }
}

This code causes an error because non-static methods require objects.


16.4 Incorrect Parameter Count

public class Main {

    static void add(int a, int b) {

        System.out.println(a + b);
    }

    public static void main(String[] args) {

        add(10);
    }
}

This code causes an error because one required argument is missing.


17. Edge Cases in Methods


17.1 Empty Method Body

Methods can exist without any logic.


public class Main {

    static void test() {

    }

    public static void main(String[] args) {

        test();
    }
}

The method executes successfully even though it performs no operation.


17.2 Returning Immediately

public class Main {

    static void check() {

        return;
    }

    public static void main(String[] args) {

        check();
    }
}

The return statement immediately stops method execution.


17.3 Methods Without Parameters

public class Main {

    static void welcome() {

        System.out.println("Welcome");
    }

    public static void main(String[] args) {

        welcome();
    }
}

Methods do not always require parameters.


18. Best Practices for Defining Methods


18.1 Use Meaningful Method Names

Method names should clearly describe their purpose.


static void calculateTotal() {

}

Clear method names improve readability.


18.2 Keep Methods Small

Small methods are easier to test and maintain.


static void printMessage() {

    System.out.println("Java");
}

Methods should ideally perform one specific task.


18.3 Avoid Repeated Code

Methods should be reused instead of rewriting logic repeatedly.


public class Main {

    static void line() {

        System.out.println("------------");
    }

    public static void main(String[] args) {

        line();
        line();
    }
}

Reusing methods reduces duplicate code.


Well-designed methods make programs cleaner and easier to manage.


19. Important Points to Remember

  • a. Methods organize reusable logic
  • b. Methods execute only when called
  • c. Parameters receive input values
  • d. Arguments are actual passed values
  • e. return sends data back to the caller
  • f. Non-static methods require objects
  • g. Each method call creates a stack frame
  • h. Small methods improve readability

Methods are one of the most important building blocks in Java programming because they help organize logic into reusable, manageable, and readable sections. Understanding how methods are defined, called, executed, and returned makes it easier to build scalable and professional Java applications.

Post a Comment

0Comments
Post a Comment (0)