top of page

Methods/functions

Methods make code more efficient and removes needless rewriting of code. Methods are essentially commands that execute a series of code.

Ex: telling your dog to sit would be the method, when called to sit, multiple steps are executed. Methods are defined and created outside of main, but are used and executed in main like all other code.
 

There are two types of methods, void and non-void methods. The differences are shown below.

Void methods

Void methods are methods that do not associated with any data type, and just execute the specified code in the definition of the method when called in main. Void methods do not need a return statement like non-void methods do. 

Non-void Methods

Non-void methods are methods that associate with a specific data type, and return the result of the code within them instead of just executing the code.

Non-void methods must have a return statement returning a value matching the data type associated which is defined when creating the method.

To get the data from the non-void method, we must call it inside of a print statement.

non void method.PNG

Parameters and Arguments

Methods are able to take in variables/values called parameters or arguments. In the defined method these parameters can be used as local variables, meaning that the variable is only able to be used within the method and doesn't exist outside of the method.

image.png
loader,gif

In the code example above, we have a method called example and it's parameters and arguments are two double variables, a numerator and denominator. In main, to have the method execute properly we need to pass in two numbers of type double, as per the method parameters.

Overloaded methods

Overloading a method means to just have multiple methods using the same method signature have different parameters. A method signature is just the name of the method we use to call it. 

image.png
image.png

In the code example above, we have the same example method previously used except there are two instances of the method.

The first instance of the method takes in two double variables while the second instance of the method takes in only one double variable. In main we call it using the same name but use different amount of arguments. This is an example of an overloaded method. 

Math Methods

Math is a Java utility included in the Java language. However in order to use it we need to import it

© 2024 by Samuel Wong.
Powered and secured by Wix

Call

(1) + 437-216-9455

Contact

@Brebeuf STEAM

  • Twitter
  • Instagram
bottom of page