Java + Spring Boot track

Lesson 05 · Part 1: Basics

Methods

A method is “a bunch of code with a name”. When you need to do the same thing multiple times, separating it into methods improves readability and reusability at the…

Part 1: Basics4 min readFree lesson

A method is “a bunch of code with a name”. When you need to do the same thing multiple times, separating it into methods improves readability and reusability at the same time. This section covers method declaration, overloading, meaning of static, and variable arguments (...).

Learning Objectives

  • Know the method declaration format (access modifier, return type, name, parameters)
  • Know the difference between overloading and overriding (overriding is part 08)
  • Understand the difference between static methods and instance methods.
  • Look at the operation of the variable argument String...

Key concepts

1) Method declaration

public static int add(int a, int b) {
    return a + b;
}
  • Access limiter: public / private / (default) package-private / protected
  • Return type: If not present, void
  • Parameters: 0 or more
  • Body: Braces { ... }

2) Overloading

static int max(int a, int b) { return a > b ? a : b; }
static double max(double a, double b) { return a > b ? a : b; }

You can create multiple methods with the same name but different parameter signatures.

3) static method

class MathUtil {
    static int square(int x) { return x * x; }
}
MathUtil.square(5);  //Called without instance

static is a method belonging to the class itself. Call it as class name.method() without creating an object.

4) Variable factor (...)

static int sumAll(int... nums) {
    int s = 0;
    for (int n : nums) s += n;
    return s;
}
sumAll(1, 2, 3, 4);    // 10
sumAll();              // 0

It is treated internally as an array, and only one can be placed at the end of the signature.

See as example

Example 1 — MethodBasics.java: Declaration and call

public class MethodBasics {
    public static void main(String[] args) {
        int s = add(3, 4);
        System.out.println("3 + 4 = " + s);
        greet("exponent");
    }

    /** The sum of two integers.*/
    static int add(int a, int b) {
        return a + b;
    }

    /** Personnel output.*/
    static void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }
}

Execution result

3 + 4 = 7
Hello, Jisoo!

Note: We can see that main is also a static method.

Example 2 — Overloading.java: same name, different signature

public class Overloading {
    public static void main(String[] args) {
        System.out.println(max(3, 7));
        System.out.println(max(3.5, 2.1));
        System.out.println(max("apple", "banana"));
    }

    static int max(int a, int b) { return a > b ? a : b; }
    static double max(double a, double b) { return a > b ? a : b; }
    static String max(String a, String b) { return a.compareTo(b) > 0 ? a : b; }
}

Execution result

7
3.5
banana

Memo: If only the return type is different and the parameters are the same, overloading is not allowed.

Example 3 — StaticVsInstance.java: Class vs Instance

public class StaticVsInstance {
    static int staticCount;     //Share 1 class
    int instanceCount;          //Separate for each instance

    void increment() {
        staticCount++;
        instanceCount++;
    }

    public static void main(String[] args) {
        StaticVsInstance a = new StaticVsInstance();
        StaticVsInstance b = new StaticVsInstance();
        a.increment(); a.increment();
        b.increment();
        System.out.println("a.instance=" + a.instanceCount);
        System.out.println("b.instance=" + b.instanceCount);
        System.out.println("static=" + StaticVsInstance.staticCount);
    }
}

Execution result

a.instance=2
b.instance=1
static=3

Note: The static field is one for the entire class, and the instance field is separate for each object.

Example 4 — Varargs.java: Variable arguments

public class Varargs {
    public static void main(String[] args) {
        System.out.println(sumAll());
        System.out.println(sumAll(1, 2, 3));
        System.out.println(sumAll(10, 20, 30, 40));
    }

    /** Add up all variable numbers of integers.*/
    static int sumAll(int... nums) {
        int s = 0;
        for (int n : nums) s += n;
        return s;
    }
}

Execution result

0
6
100

Note: int... internally operates the same as int[].

Common Mistakes

  1. The return type is void, but write return value;
  2. Using the same name for a parameter twice
  3. Direct access to instance fields within the static method (impossible)
  4. Confusion between overloading and overriding — overriding is inheritance (Part 08)
  5. Put variable arguments in the middle of method signature

Cleanup

  • Methods are the basic unit of code reuse.
  • Same name/different signature is overloading
  • static belongs to a class and is called without an instance.
  • There is only one variable argument in the last position.

Try it yourself

cd 01_Basics/05_Method/src
javac Overloading.java
java Overloading

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

src/MethodBasics.javaJava
public class MethodBasics {
    public static void main(String[] args) {
        int s = add(3, 4);
        System.out.println("3 + 4 = " + s);
        greet("exponent");
    }

    /** The sum of two integers.*/
    static int add(int a, int b) {
        return a + b;
    }

    /** Personnel output.*/
    static void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }
}
src/Overloading.javaJava
public class Overloading {
    public static void main(String[] args) {
        System.out.println(max(3, 7));
        System.out.println(max(3.5, 2.1));
        System.out.println(max("apple", "banana"));
    }

    static int max(int a, int b) { return a > b ? a : b; }
    static double max(double a, double b) { return a > b ? a : b; }
    static String max(String a, String b) { return a.compareTo(b) > 0 ? a : b; }
}
src/StaticVsInstance.javaJava
public class StaticVsInstance {
    static int staticCount;
    int instanceCount;

    void increment() {
        staticCount++;
        instanceCount++;
    }

    public static void main(String[] args) {
        StaticVsInstance a = new StaticVsInstance();
        StaticVsInstance b = new StaticVsInstance();
        a.increment(); a.increment();
        b.increment();
        System.out.println("a.instance=" + a.instanceCount);
        System.out.println("b.instance=" + b.instanceCount);
        System.out.println("static=" + StaticVsInstance.staticCount);
    }
}
src/Varargs.javaJava
public class Varargs {
    public static void main(String[] args) {
        System.out.println(sumAll());
        System.out.println(sumAll(1, 2, 3));
        System.out.println(sumAll(10, 20, 30, 40));
    }

    /** Add up all variable numbers of integers.*/
    static int sumAll(int... nums) {
        int s = 0;
        for (int n : nums) s += n;
        return s;
    }
}

Assignment

Problem 1 — Prime Determination Method

  • File name: Homework01.java
  • Core concepts: method declaration, return value

Requirements

  • Create a static boolean isPrime(int n) method to determine if it is less than 1, it will be false, and if it is less than 1, it will be judged as a prime number by checking the divisor.
  • Main outputs results from 2 to 10.

Expected output

2 -> true
3 -> true
4 -> false
5 -> true
6 -> false
7 -> true
8 -> false
9 -> false
10 -> false

Problem 2 — Average (overloading + variable arguments)

  • File name: Homework02.java
  • Key concepts: overloading, variable arguments

Requirements

  • Create two files: static double avg(int... nums) and static double avg(double... nums).
  • If the input is empty, it returns 0.

Expected output

int avg(1,2,3,4) = 2.5
double avg(1.5, 2.5) = 2.0
empty = 0.0

Check the correct answer

After solving it yourself, compare it with the reference solution below.

Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

Homework01.javaJava
/** Deciding on prime numbers.*/
public class Homework01 {
    public static void main(String[] args) {
        for (int n = 2; n <= 10; n++) {
            System.out.println(n + " -> " + isPrime(n));
        }
    }

    static boolean isPrime(int n) {
        if (n < 2) return false;
        for (int i = 2; i * i <= n; i++) {
            if (n % i == 0) return false;
        }
        return true;
    }
}
Homework02.javaJava
/** Average: overloading + variable arguments.*/
public class Homework02 {
    public static void main(String[] args) {
        System.out.println("int avg(1,2,3,4) = " + avg(1, 2, 3, 4));
        System.out.println("double avg(1.5, 2.5) = " + avg(1.5, 2.5));
        System.out.println("empty = " + avg());
    }

    static double avg(int... nums) {
        if (nums.length == 0) return 0;
        int s = 0;
        for (int n : nums) s += n;
        return (double) s / nums.length;
    }

    static double avg(double... nums) {
        if (nums.length == 0) return 0;
        double s = 0;
        for (double n : nums) s += n;
        return s / nums.length;
    }
}

Learn this lesson with a mentor

Work through the Java + Spring Boot track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now