xSKILLby Infirals
Register

Java for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Methods

Control flow and methods12 min readLesson 4 of 4

4.1 Methods give a name to a task

A method is a named block of code that can receive values and return a result. Define methods inside a class, then call them from main or from another method. The basic form names an access level, a return type, a method name, and a parameter list.

public static int add(int a, int b) { return a + b; } declares a method with two int parameters and an int return type. The call add(7, 5) passes two values and produces 12. Use void when the method returns no value.

A method body can contain any statements you have learned, including loops and conditions. Putting a calculation in a method lets you test it with several inputs and reuse it without copying the code.

java
public class Main {
    public static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        int result = add(7, 5);
        System.out.println(result);
    }
}

Output

12

4.1.1 Parameters and return values

A parameter is a variable declared in the method signature. An argument is the value supplied at the call. The compiler checks the number and types of arguments, then binds each one to its parameter.

A method can return at most one value. return expression; finishes the method and sends the value back to the caller. A void method can use return; on its own to exit early, or simply end at its closing brace.

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

    public static void main(String[] args) {
        greet("Asha");
        greet("Ravi");
    }
}

Output

Hello, Asha!
Hello, Ravi!

4.1.2 How a call runs

When main calls a method, Java evaluates the arguments, passes control to the method, and runs its body. A return sends a value back and control resumes at the call site. A call inside a call follows the same rule, with each method waiting for the inner one to finish.

Method order in the file does not matter. main can call a method declared above or below it. What matters is that the compiler can find a method with a matching name and parameter list.

A method can call itself, which is called recursion. Recursion needs a base case that returns without making another call. It is useful for tasks such as walking a tree, but a loop is usually easier for simple counting.

4.1.3 Scope and local variables

A local variable is declared inside a method or a smaller block and exists only there. Parameters are local to their method as well. A variable declared inside a for loop cannot be read after the loop ends.

Scope keeps methods independent. A variable named total in main is not visible inside calculateTotal unless you pass it as an argument or return a result. That limitation is useful: each method can use clear local names without colliding with the rest of the program.

Declare a variable close to where it is used, initialize it before reading it, and avoid reusing one name for two different meanings in the same method.

java
public class Main {
    public static void main(String[] args) {
        int total = 0;
        for (int i = 1; i <= 3; i++) {
            int square = i * i;
            total += square;
        }
        System.out.println(total);
        // System.out.println(square); // square is out of scope
    }
}

Output

14

4.1.4 Passing arguments by value

Java uses pass by value for arguments. For a primitive, the method receives a copy of the number. Assigning a new value to the parameter does not change the caller's variable. For an object reference, the method receives a copy of the reference, so it can still modify the object both references point to. Reassigning the parameter itself does not change which object the caller's variable refers to.

The method can return a new value, but it cannot reach back into the caller's local variable through a primitive parameter. If a change must be visible outside the method, return the new value and assign it at the call site, or pass an object whose fields the method is allowed to update.

java
public class Main {
    public static void change(int value) {
        value = value + 10;
        System.out.println("Inside: " + value);
    }

    public static void main(String[] args) {
        int number = 5;
        change(number);
        System.out.println("Outside: " + number);
    }
}

Output

Inside: 15
Outside: 5

4.1.5 Overloading by parameter list

Method overloading means declaring several methods with the same name but different parameter lists. The compiler chooses the version whose parameters match the call. The difference can be the number of parameters, their types, or their order.

area(int side) and area(int length, int width) can coexist. Calling area(4) selects the first, and area(4, 5) selects the second. A method signature includes the name and parameter types, not the return type, so changing only the return type produces a duplicate-method error.

Keep overloads predictable. If two versions do very different things, different names make the code easier to read. If one version adds a default value for a missing argument, document that relationship in a comment or a simpler overload that calls the fuller one.

java
public class Main {
    public static int area(int side) {
        return side * side;
    }

    public static int area(int length, int width) {
        return length * width;
    }

    public static void main(String[] args) {
        System.out.println(area(4));
        System.out.println(area(4, 5));
    }
}

Output

16
20

4.1.6 Writing methods that are easy to use

A method name should say what the method does: calculateAverage, isEven, printReceipt. Parameters should be the values the method needs, and the return value should be the result the caller needs. Avoid reading and writing shared state when an argument and a return value would be clearer.

A method with one purpose is easier to test. You can call it with a few values and check the result without setting up a larger program. Long methods often contain smaller steps that can become their own methods, especially when a comment is needed to explain each section.

Validate inputs where a wrong value would break the calculation. A method that divides should handle a zero divisor before the division. A method that searches an array should handle an empty array before reading the first element.

4.1.7 Practice

  1. Write static int max(int a, int b) and call it with two different pairs of values.
  2. Write static boolean isEven(int number) and use it in a loop.
  3. Write static double average(int[] values) and handle an empty array by returning 0.0.
  4. Overload a method named printLine so one version prints a default line and another prints a repeated character a given number of times.
  5. Trace a call to add(3, multiply(2, 4)) by hand and list the order in which the methods return.

Step 5 is a check on the call order: the inner multiply call finishes before add receives its arguments.

Interview questions

3 questions from this note. Open one to see the answer; no account needed.

  • 01What is the difference between a parameter and an argument?

    A parameter is the variable declared in a method signature. An argument is the value passed at the call site.

  • 02Can two methods differ only by return type?

    No. Return type is not part of a method signature, so two methods that differ only by return type conflict. Use a different parameter list or a different name.

  • 03Does Java pass objects by reference?

    No. Java passes the object reference by value, so a method can modify the object but cannot change which object the caller's variable points to.