Forum

Learn Java Function…
 
Notifications
Clear all

Learn Java Functions

1 Posts
1 Users
0 Reactions
13 Views
 josh
(@josh)
Member Admin
Joined: 2 months ago
Posts: 510
Topic starter  

Java functions—technically known as methods—are how you organize actions or behaviors in a class. Imagine them as tiny workers inside your program that perform specific tasks when called 🛠️🚀


🧪 What Is a Function (Method) in Java?

A method is a block of code that performs a specific operation. You define it once and can reuse it whenever needed.


🧱 Basic Syntax

returnType methodName(parameters) {
    // method body
}
  • returnType: The type of value the method returns (int, void, String, etc.)
  • methodName: The name you choose
  • parameters: Optional inputs the method uses

⚙️ Example: A Simple Method

public class Calculator {
    
    // Method that adds two numbers
    int add(int a, int b) {
        return a + b;
    }
}

To use the method:

Calculator calc = new Calculator();
int sum = calc.add(5, 3); // sum is 8

🫧 Void Methods (No Return Value)

void sayHello(String name) {
    System.out.println("Hello, " + name + "!");
}

This method just prints a greeting—it doesn’t return anything.


🍭 Static Methods

Static methods belong to the class itself, not a specific object.

public class MathUtil {
    static int square(int num) {
        return num * num;
    }
}

Use it like:

int result = MathUtil.square(4); // result is 16

🌈 Why Use Methods?

  • Organize and reuse code
  • Reduce repetition
  • Make programs easier to read and debug
  • Build more complex behaviors step by step

 


   
Quote
Share: