Java

Methods and functions

Methods and Functions in Java: Reusing Code with Ease

When programming, you often need to reuse code or organize your program into smaller, manageable pieces. That’s exactly what methods (also called functions) are for!

In Java, a method is a block of code that performs a specific task, which you can call whenever needed.


What Is a Method?

A method:

  • Groups related statements together

  • Has a name, parameters (optional), and a return type (or void if no value is returned)

  • Can be called (invoked) from other parts of the program


⚙️ Defining a Method

Here’s the basic syntax:

java
returnType methodName(parameterList) {
// method body
return value; // if returnType is not void
}

Example: A simple method that adds two numbers

java
public int add(int a, int b) {
int sum = a + b;
return sum;
}
  • public is an access modifier (means method can be accessed from other classes)

  • int is the return type (the method returns an integer)

  • add is the method name

  • (int a, int b) are parameters (inputs)

  • return sum; returns the result


Calling a Method

To use the method, call it with appropriate arguments:

java
int result = add(5, 3);
System.out.println("Sum is: " + result);

️ Methods with No Return Value (void)

Sometimes you just want a method to perform an action without returning data.

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

Call it like this:

java
greet("Alice"); // Output: Hello, Alice!

Method Overloading

Java allows methods with the same name but different parameter lists — called method overloading.

java
public int multiply(int a, int b) {
return a * b;
}

public double multiply(double a, double b) {
return a * b;
}

The compiler decides which method to call based on the argument types.


Access Modifiers (Quick Intro)

  • public: accessible from anywhere

  • private: accessible only within the class

  • protected: accessible within the package or subclasses


Example: Putting It All Together

java
public class Calculator {

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

public void printResult(int result) {
System.out.println("Result: " + result);
}

public static void main(String[] args) {
Calculator calc = new Calculator();
int sum = calc.add(10, 20);
calc.printResult(sum);
}
}


Summary

  • Methods organize reusable code blocks

  • Define with return type, name, and parameters

  • Call methods to execute their code

  • Use void if no return value

  • Method overloading allows multiple versions of a method

Leave a Reply

Your email address will not be published. Required fields are marked *