Skip to main content

Lesson 5 of 5 20 min read

Functions, problem-solving and a coding exercise

Organise code into methods with parameters and return values, and use a step-by-step approach to solve a coding problem.

In this lesson you will

  • Define and call methods with parameters and return values
  • Explain the difference between void and value-returning methods
  • Apply a repeatable problem-solving process to a small coding exercise

Methods package reusable steps

A method (often called a function in other languages) is a named block of code that performs one task. Methods let you write logic once and reuse it, and they make programs easier to read and test.

Java
public class Greeter {
    static void greet(String name) {
        System.out.println("Welcome to DevCrest, " + name + "!");
    }

    public static void main(String[] args) {
        greet("Arjun");
        greet("Meera");
    }
}
  • static means the method belongs to the class, so main can call it directly. You'll learn about objects and non-static methods later.
  • void means the method returns no value; it just performs an action.
  • String name is a parameter: a variable that receives the value passed in, called an argument ("Arjun").

Returning a value

A method can calculate something and hand the result back with return:

Java
static double average(int[] numbers) {
    int sum = 0;
    for (int n : numbers) {
        sum += n;
    }
    return (double) sum / numbers.length;
}

static boolean isEven(int n) {
    return n % 2 == 0;
}

public static void main(String[] args) {
    int[] marks = {70, 85, 90};
    double avg = average(marks);
    System.out.println("Average: " + avg);       // Average: 81.66666666666667
    System.out.println(isEven(10));              // true
}
Calling a method hands values in and gets a result back

main sends to average: average(marks) with {70, 85, 90}. average replies to main: return 81.666…. main sends to isEven: isEven(10). isEven replies to main: return true

The return type (double, boolean) is written before the method name, and every path through the method must return a value of that type. return also ends the method immediately.

A problem-solving process

Experienced developers rarely start by typing code. They follow steps like these:

  1. Understand the problem. Restate it in your own words. What are the inputs and the expected output?
  2. Work through examples by hand. Include an edge case, such as zero, a negative number or an empty array.
  3. Plan the steps in plain language (pseudocode).
  4. Write the code, one small method at a time.
  5. Test with your examples and fix what fails.

Walkthrough: count the vowels in a word

Understand: input is a String; output is how many of its letters are a, e, i, o or u, ignoring case.

Examples: "DevCrest" has 2 vowels (e, e). "sky" has 0. "" has 0.

Plan:

  1. Start a counter at 0.
  2. Look at each character in the word.
  3. If the lowercase character is a vowel, add one to the counter.
  4. Return the counter.

Code:

Java
public class Vowels {
    static boolean isVowel(char c) {
        char lower = Character.toLowerCase(c);
        return lower == 'a' || lower == 'e' || lower == 'i' || lower == 'o' || lower == 'u';
    }

    static int countVowels(String word) {
        int count = 0;
        for (int i = 0; i < word.length(); i++) {
            if (isVowel(word.charAt(i))) {
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(countVowels("DevCrest")); // 2
        System.out.println(countVowels("sky"));      // 0
        System.out.println(countVowels(""));         // 0
    }
}

Notice how splitting the work into isVowel and countVowels keeps each method short and easy to check.

Hands-on exercise

Solve the classic FizzBuzz problem with a method. Write static String fizzBuzz(int n) that returns "Fizz" when n is divisible by 3, "Buzz" when divisible by 5, "FizzBuzz" when divisible by both, and the number itself as text otherwise (use String.valueOf(n)). In main, loop from 1 to 30 and print fizzBuzz(i). Before coding, write the expected output for 3, 5, 15 and 7 by hand. Which condition must you check first, and why?

Knowledge check

3 questions • 70% to pass • Practice only, no certificate

  1. 1.What does this method return for max(4, 9)?
    CODE
    static int max(int a, int b) {
        if (a > b) {
            return a;
        }
        return b;
    }
  2. 2.In greet("Asha"), what is "Asha"?
  3. 3.What is the best first step when solving a new coding problem?
0 of 3 answered

Key concepts

  • A method is a named, reusable block of code; parameters receive the arguments passed in.
  • void methods perform an action; other methods return a value of their declared type with return.
  • Solve problems by understanding them, working examples by hand, planning, coding and testing.
  • Small methods with one job each are easier to read, test and fix.

Optional next step: DevCrest Academy

Enterprise Java, Spring Boot & Microservices Engineering

If you enjoyed writing Java, the academy course takes you from these basics to object-oriented design, Spring Boot REST APIs and microservices, with guided projects and mentor feedback.

  • Intermediate
  • 16 weeks • 120 hours
  • Hybrid or Online Live
  • From ₹7,500 per student

Fees and batch dates are sample data pending confirmation

Or keep learning for free with Web Development Basics.