Java Methods (Functions) — Beginner Guide with Examples

Java Methods (Functions): Complete Beginner Guide (With Examples)

✨ Quick Summary

In this post, you’ll learn what Methods are in Java and why they are important. We will cover method creation, method calling, parameters, return types, and real examples in a beginner-friendly way.

Java Beginner Methods Functions

In our previous post, we learned about Java Strings and how to work with text.

Now, let’s learn one of the most important topics in Java: Methods.

A method is a block of code that performs a specific task. Instead of writing the same code again and again, we create methods and reuse them.


1) Why Do We Need Methods?

Methods make your code:

  • ✅ Clean and readable
  • ✅ Easy to reuse
  • ✅ Easy to maintain
  • ✅ Less repeated code

2) Java Method Syntax

A method has:

  • Return type
  • Method name
  • Parameters (optional)
  • Method body

Syntax


returnType methodName(parameters) {
    // code to execute
}

3) Example: Method Without Parameters

Let’s create a method that prints a welcome message.


public class MethodExample1 {

    static void welcomeMessage() {
        System.out.println("Welcome to The Logic Byte Tech!");
    }

    public static void main(String[] args) {
        welcomeMessage();
    }
}

4) Method With Parameters

Parameters allow you to pass values to a method.


public class MethodExample2 {

    static void printName(String name) {
        System.out.println("Hello " + name);
    }

    public static void main(String[] args) {
        printName("Aishwarya");
        printName("Logic Byte");
    }
}

5) Method With Return Type

A method can return a value using the return keyword.


public class MethodReturnExample {

    static int addNumbers(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        int result = addNumbers(10, 20);
        System.out.println("Sum: " + result);
    }
}

6) Method Overloading (Same Name, Different Parameters)

Java supports Method Overloading. That means you can create multiple methods with the same name but different parameters.


public class OverloadingExample {

    static int add(int a, int b) {
        return a + b;
    }

    static int add(int a, int b, int c) {
        return a + b + c;
    }

    public static void main(String[] args) {
        System.out.println(add(5, 10));
        System.out.println(add(5, 10, 20));
    }
}

Conclusion

Methods are very important in Java because they help you write clean and reusable code. Once you understand methods, you will easily learn Object-Oriented Programming (OOP).

In the next post, we will learn about Java OOP Concepts (Class and Object) and start real Java programming!

Comments

Post a Comment

Popular posts from this blog

Inheritance in Java (Single, Multilevel, Hierarchical)

The Java Blueprint: Your First Step into Software Development

Java Variables and Data Types: Storing Your Data