Understanding Functions/Methods in Java

Understanding Functions/Methods in Java

In programming, functions or methods play a crucial role in breaking down complex tasks into manageable units. They allow us to write reusable code that can be invoked multiple times without repetition. In Java, using methods ensures cleaner, more efficient, and maintainable code. Functions or methods help avoid redundancy, improve readability, and enable modular programming, where large code blocks are broken down into smaller, logical components.

What is a Function and a Method?

In Java, a function refers to a block of code that performs a specific task. However, in Java, the term method is more commonly used because every function must reside within a class. Hence, in Java, methods are essentially functions defined inside a class.

Key Difference:

  • Function: A generic term that refers to a reusable block of code in various programming languages.

  • Method: A function that is associated with an object or class in Object-Oriented Programming (OOP). In Java, functions are always methods since they are encapsulated within classes.

Syntax of Method
<access_modifier> <return_type> <method_name>(<parameters>) {
    // method body
}
  • access_modifier: Defines the visibility of the method (e.g., public, private).

  • return_type: The data type of the value the method will return (e.g., int, String, void).

  • method_name: The name of the method, which should be descriptive of the task it performs.

  • parameters: Input values that are passed to the method when it's called.


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

This method takes two integers as parameters, adds them, and returns the result.

Returning a Value from a Method

A method in Java can return a specific value. The return type of the method is defined by the return_type. If the method does not return anything, we use void.

Example of returning a integer value
public int multiply(int x, int y) {
    return x * y;
}
Example of Returning a String:
public String greet(String name) {
    return "Hello, " + name + "!";
}

Parameters in Methods

Parameters allow methods to accept input values when they are called. These inputs are processed within the method to perform a task.

Integer Parameter Example:
public void printSquare(int number) {
    System.out.println(number * number);
}
String Parameter Example:
public void printGreeting(String message) {
    System.out.println(message);
}

Swap Two Numbers Using a Method

Let’s use methods to swap two numbers:

public void swap(int a, int b) {
    int temp = a;
    a = b;
    b = temp;
    System.out.println("After Swap: a = " + a + ", b = " + b);
}

Pass by Value vs. Pass by Reference

In Java, pass by value means that when an argument is passed to a method, a copy of the argument's value is created. Java does not support pass-by-reference, but it does handle object references differently.

Example: Pass by Value (for primitives):
public void changeValue(int num) {
    num = 10;
    System.out.println("Inside method: " + num);
}

public static void main(String[] args) {
    int x = 5;
    changeValue(x);
    System.out.println("After method call: " + x);
}
Example: Pass by Reference (for objects):
public void changeObjectValue(Student student) {
    student.name = "John";
}

public static void main(String[] args) {
    Student s = new Student("Alice");
    changeObjectValue(s);
    System.out.println("Student name: " + s.name);
}

We will understand about pass by objects more when we will study about OOP concept.

Scope of Methods and Blocks

The scope of a method refers to the visibility and lifetime of variables and parameters. A variable declared inside a method is local to that method and cannot be accessed outside of it. Similarly, a block scope exists within any pair of curly braces {}.

Example of Method Scope:
public void exampleMethod() {
    int localVar = 5; // local variable to this method
    System.out.println(localVar);
}
Example of Block Scope:
public void blockScopeExample() {
    int x = 10;
    if (x > 5) {
        int y = 20; // block scope, only available within this if block
        System.out.println(y);
    }
    // System.out.println(y); // Error: y is not accessible here
}

Shadowing

Shadowing occurs when a local variable in a method or block hides (or "shadows") a variable with the same name in the outer scope.

Example 1:
int x = 10;

public void shadowingExample() {
    int x = 5; // shadows the outer x
    System.out.println("Local x: " + x);
}
Example 2:
class Shadow {
    static int x = 1;

    public static void main(String[] args) {
        System.out.println("Before shadowing: " + x); 
        int x = 2; // shadowing the class-level x
        System.out.println("After shadowing: " + x);
    }
}

Variable Arguments in Java

Variable arguments, or varargs, allow a method to accept zero or more arguments. It's a useful feature when the exact number of arguments is unknown.

Syntax:
public void printNumbers(int... numbers) {
    for (int number : numbers) {
        System.out.println(number);
    }
}
Example 1:
public void sumNumbers(int... numbers) {
    int sum = 0;
    for (int num : numbers) {
        sum += num;
    }
    System.out.println("Sum: " + sum);
}
Example 2:
public void displayNames(String... names) {
    for (String name : names) {
        System.out.println(name);
    }
}

Method Overloading

Method overloading allows multiple methods in the same class to have the same name but different parameter lists.

Example:
public void display(int a) {
    System.out.println("Integer: " + a);
}

public void display(String s) {
    System.out.println("String: " + s);
}
Another Example:
public int add(int a, int b) {
    return a + b;
}

public double add(double a, double b) {
    return a + b;

Java methods allow for modular, clean, and efficient coding practices. By understanding the scope, parameter handling, return types, and concepts like overloading and variable arguments, you can enhance your programming skills and write optimized Java applications.


Now that’s it for this blog, in next upcoming blog we will learn about Arrays in JAVA and with array our Leetcode journey will be started.

Until then, Keep Learning, Keep Sharing And Keep Supporting.