Core Java

core7Methods

Path
pkg1core/core7Methods.java
Package
pkg1core
Study order
6
Run
Single-file source launch
Command
java pkg1core/core7Methods.java
Lesson
Back to the chapter

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg1core/core7Methods.java
1package pkg1core;2 3/*4 * core7Methods.java5 * ------------6 * Defining methods: parameters, return values, overloading, varargs,7 * recursion, and pass-by-value semantics.8 *9 * EXPLANATION:10 *  - Java is ALWAYS pass-by-value. For objects, the VALUE passed is the11 *    reference (so you can mutate the object, but reassigning the param12 *    doesn't affect the caller).13 *  - Overloading = same name, different parameter lists (compile-time).14 *  - Varargs (Type...) accept zero or more arguments as an array.15 */16public class core7Methods {17 18    static int add(int a, int b) { return a + b; }              // basic19    static double add(double a, double b) { return a + b; }     // overload20    static int sum(int... values) {                             // varargs21        int total = 0;22        for (int v : values) total += v;23        return total;24    }25    static long factorial(int n) {                              // recursion26        if (n <= 1) return 1;                                   // base case27        return n * factorial(n - 1);                            // recursive step28    }29    static void tryReassign(int[] arr) {30        arr[0] = 99;          // mutates the caller's array (same object)31        arr = new int[]{0};   // reassigning the local param does NOT affect caller32    }33 34    public static void main(String[] args) {35        System.out.println("add(2,3)=" + add(2, 3));36        System.out.println("add(2.5,3.5)=" + add(2.5, 3.5));37        System.out.println("sum()=" + sum() + " sum(1,2,3,4)=" + sum(1, 2, 3, 4));38        System.out.println("factorial(5)=" + factorial(5));39 40        int[] data = {1, 2, 3};41        tryReassign(data);42        System.out.println("after tryReassign data[0]=" + data[0] + " (mutated), length=" + data.length + " (unchanged)");43    }44}