Skip to content
Laviyx Learn

Try

Java Methods Practice

Practise writing static methods, return values, pass-by-value behaviour, overloading, varargs and recursion in Java.

Beginner7 problemsUpdated

Review first: Methods, Parameters and Return Values, Method Overloading, Scope and static, Recursion

  1. 1.A prime-checking method

    Beginner

    Write static boolean isPrime(int n) and print every prime from 1 to 30 on one line.

    Show hint

    Numbers below 2 are not prime; otherwise test divisors while d * d <= n.

    Show solution
    Java
    public class Main {
        static boolean isPrime(int n) {
            if (n < 2) return false;
            for (int d = 2; d * d <= n; d++) {
                if (n % d == 0) return false;
            }
            return true;
        }
    
        public static void main(String[] args) {
            StringBuilder primes = new StringBuilder();
            for (int i = 1; i <= 30; i++) {
                if (isPrime(i)) primes.append(i).append(' ');
            }
            System.out.println(primes.toString().trim());
        }
    }
    Output
    2 3 5 7 11 13 17 19 23 29
  2. 2.Pass by value

    Beginner

    Write static void addBonus(int salary) that adds 5000 to its parameter, and static void addBonus(int[] salaries) that adds 5000 to every element. Show which changes are visible to the caller.

    Show hint

    Primitives are copied; an array parameter is a copy of the reference to the same array.

    Show solution
    Java
    import java.util.Arrays;
    
    public class Main {
        static void addBonus(int salary) {
            salary += 5000;
        }
    
        static void addBonus(int[] salaries) {
            for (int i = 0; i < salaries.length; i++) salaries[i] += 5000;
        }
    
        public static void main(String[] args) {
            int salary = 50000;
            addBonus(salary);
            System.out.println(salary);
    
            int[] team = {40000, 60000};
            addBonus(team);
            System.out.println(Arrays.toString(team));
        }
    }
    Output
    50000
    [45000, 65000]

    The int version changes only its own copy. The array version changes the caller's array, because both refer to the same array object. Both methods share a name, which is overloading by parameter type.

  3. 3.Overloaded area

    Beginner

    Write two overloads of area: one for a circle (double radius) and one for a rectangle (double width, double height). Print the circle's area for radius 2 with two decimals, and the rectangle's area for 3 × 4.5.

    Show hint

    Use Math.PI for the circle, and printf("%.2f%n", ...) to format.

    Show solution
    Java
    public class Main {
        static double area(double radius) {
            return Math.PI * radius * radius;
        }
    
        static double area(double width, double height) {
            return width * height;
        }
    
        public static void main(String[] args) {
            System.out.printf("%.2f%n", area(2));
            System.out.println(area(3, 4.5));
        }
    }
    Output
    12.57
    13.5
  4. 4.Average of any number of values

    Beginner

    Write static double average(double... values) that returns 0 when called with no arguments. Print average(4, 8, 6), average(10) and average().

    Show hint

    Varargs arrive as an array; check its length.

    Show solution
    Java
    public class Main {
        static double average(double... values) {
            if (values.length == 0) return 0;
            double sum = 0;
            for (double v : values) sum += v;
            return sum / values.length;
        }
    
        public static void main(String[] args) {
            System.out.println(average(4, 8, 6));
            System.out.println(average(10));
            System.out.println(average());
        }
    }
    Output
    6.0
    10.0
    0.0
  5. 5.Recursive factorial

    Beginner

    Write a recursive static long factorial(int n) and print factorial(10) and factorial(20).

    Show hint

    Base case: n <= 1 returns 1. Otherwise return n * factorial(n - 1).

    Show solution
    Java
    public class Main {
        static long factorial(int n) {
            if (n <= 1) return 1;
            return n * factorial(n - 1);
        }
    
        public static void main(String[] args) {
            System.out.println(factorial(10));
            System.out.println(factorial(20));
        }
    }
    Output
    3628800
    2432902008176640000
  6. 6.Fast power with recursion

    Beginner

    Write a recursive static long power(long base, int exp) that uses base^exp = (base^(exp/2))^2 (times base again when exp is odd). Print power(2, 10) and power(3, 13).

    Show hint

    Compute half = power(base, exp / 2) once, then return half * half or half * half * base.

    Show solution
    Java
    public class Main {
        static long power(long base, int exp) {
            if (exp == 0) return 1;
            long half = power(base, exp / 2);
            return exp % 2 == 0 ? half * half : half * half * base;
        }
    
        public static void main(String[] args) {
            System.out.println(power(2, 10));
            System.out.println(power(3, 13));
        }
    }
    Output
    1024
    1594323

    Halving the exponent each time needs only about log2(exp) calls, instead of exp multiplications.

  7. 7.Count method calls

    Beginner

    Write static int nextId() that returns 1, then 2, then 3 on successive calls, using a static field. Call it three times.

    Show hint

    A static field keeps its value between calls.

    Show solution
    Java
    public class Main {
        static int lastId = 0;
    
        static int nextId() {
            lastId++;
            return lastId;
        }
    
        public static void main(String[] args) {
            System.out.println(nextId() + " " + nextId() + " " + nextId());
        }
    }
    Output
    1 2 3

    Java evaluates the operands of + from left to right, so the three calls happen in order.