1
0
mirror of https://gitlab.com/magicalsoup/Highschool.git synced 2025-01-23 16:11:46 -05:00
highschool/Grade 10/Computer Science/ICS4U1/Methods.md
2019-09-18 16:09:13 +00:00

2.2 KiB

Methods

What are methods

A java method can be interpreted as a subprogram. It is a collection of statements taht are grouped togehter to perform an operation

Built- in vs User-defined Methods

Built-in: BUild-i nmethods arep art of hte complier package such as system.out.println

Function (return) - Type: it calcualtes and return a value

public static int claculate(int number){

procedure-type: executes some commands

Function (return)- type: pubic static return type method name (parameter 1)

procedure-type method: public static void method-name (paramenter 1)

How to create a method

In general, method declarations has 5 basic components (figure 2.): - Modifier: defines access type of the method i.e. from were it can be accessed in your application (For example: public) - The return type: the data type of the value returned by the method or void if it does not return a value (procedure and function type) - Method name: a specific names that identifies the method that can be used to invoke it later - Parameter list: Comma separated list of the input parameter are defined preceded with their data type, within the enclosed parentheses, If there are no parameters, you must use empty parenteses()

Method declaration

  • Method body: It is enclosed between braces. the code that you need to be execute to perfrom your intended operations
public int max(int x, int y) {

How to call a method (method invocation

To invoke a method you need the method name with the parameter list defined between parentheses

Exammple: Method Name (paramter list)

Must have () parentheses when calling a method, even with no passing parameters

Pass-By-Value

What happens: When a method is called ,a copy of the value of each argument is passed to the method

In the second method: This copy can be changed inside the method, however such a change has no effect on the actual argumnet

int num=10;
double decimal = 5.2;
NumberManeuvers(num decimal);
System.out.println("num = " + num + "and decimal = " + decimal);

public static void numberManeuvers(int i, double j) {
    if(i == 10) {
        j = 6.2;
        i = 12;
    }
}
// output = num = 10 and decimal = 5.2

Pass-By-Reference