1 of 17

All about Functions

Java

2 of 17

Key things to note:

If you don’t know this, it won’t matter too much for Level 2.

But it can make other problems easier and it’s definitely a skill you would want if you are going for Excellence.

Unfortunately it’ll just be a longish lecture from Mr Chuang to go over it!

Don’t bother taking notes, I’ll share the code as we go.

3 of 17

Functions - Linking back to what you know

You have seen functions before by now if you have done L2 MATH.

Y = sin(x)

Y = Log(x)

Y = x^2

Even this one!

Y = x + 1

4 of 17

How to think about them

You have a rule or inputs, the rule “processes” the input, and we get an output!

Example:

Y = x + 1

Input: 2 -> Output: 3

Input: 5 -> Output: 6

5 of 17

In L2 MATH Terms

  1. All possible inputs are domains.
  2. All possible outputs are ranges.
  3. A function is defined so that each input corresponds to 1 output.

NOTE: 3) will not be true in Computer Science.

This is also not true in what we call Discrete Mathematics!

6 of 17

Examples of “invalid” functions

Sqrt(x)

Equations that draws Circles

A bunch of other stuff that’s beyond the scope.

Such as:

arcsin(x)

Have you tried graphing that before?

7 of 17

In Computer Science.

Definition of a function:

A function is a rule that takes inputs and produces outputs.

Note: The restriction for number of inputs/outputs is no longer here!

8 of 17

Here’s a picture

You will see many f(x) in the future!

Basically f(x) is the same as y.

9 of 17

1 input -> Many outputs #1

Think of this scenario:

Input: a first name

Output: Their email, phone number, address

Hopefully this isn’t too strange to think that a function can do this.

10 of 17

1 input -> Many output #2

Sqrt(x)

Input: 9

Output: 3, -3

11 of 17

Other examples:

Many to one:

Input: length, width

Output: Area

Input: First Name, Last Name

Output: Age

12 of 17

Other examples #2

Many to Many:

Inputs: Length, Width, Height:

Outputs: Area needed to paint, Paint Needed, Number of Buckets needed to purchase

13 of 17

In BlueJ

Code in comments.

There are variables in the brackets, they are the inputs!

Note the return type is what the output is!

14 of 17

More examples…

Unfortunately most of these are math examples!

15 of 17

Something that’ll speed things up!

16 of 17

The Quiz…What we want to avoid!

Technically this does work…

But it’s much more efficient if we do something different!

Check the comments if you want to see the original code.

17 of 17

How to fix this…

Mr Chuang will be improvising this.

He’ll also need to talk about global variables and fields!

(He did this in 2023, the answers are in the comments below)