Skip to content

Functions

What are functions?

A function (or method, as they are often called in Java) is a self-contained block of code that performs a specific task. Functions are crucial in programming because they help us break down our code into reusable pieces. We can call the same function any number of times, which saves us from having to write the same code repeatedly.

Here's an example of a simple function in Java:

void greet() {
    System.out.println("Hello, world!");
}

This function, named greet, prints the string "Hello, world!" when called. To call a function, you use its name followed by parentheses. For example, greet();

Function declaration, parameters, and return values

Functions in Java have a specific structure. They begin with a declaration, which includes the function's return type, name, and parameters.

The return type is the type of data the function sends back when it's finished. If a function doesn't need to return any data, you can use the keyword void for the return type.

Parameters (also called arguments) are values that we can pass into a function when we call it. These values can then be used within the function. Parameters are optional; a function can have none, one, or many.

Here's an example of a function that takes parameters and returns a value:

int addNumbers(int num1, int num2) {
    int sum = num1 + num2;
    return sum;
}

In this example, addNumbers is a function that takes two integers as parameters (num1 and num2) and returns their sum.

To call this function, you would write addNumbers(5, 3);, which would return the integer 8.

Tasks

In a new Java file named Week4Task2.java, complete the following tasks:

  1. Write a function named calculateArea that takes two parameters: length and width. This function should return the product of length and width, which represents the area of a rectangle.
  2. Call your calculateArea function with different values for length and width and print the results.
  3. Write a function named sayHelloToUser that takes one parameter: name. This function should print a personalized greeting, like "Hello, [name]!"
  4. Call your sayHelloToUser function with different names and observe the output.

Answers

Additional Resources

W3Schools - Java Methods

Oracle - Defining Methods

GeeksforGeeks - Functions in Java