Methods

invisibleufo101·2024년 9월 14일

Java

목록 보기
5/10
post-thumbnail

Method Types

  • void → returns nothing
  • int → returns an int
  • double → returns a double
  • String → returns a String
  • int[] → returns an array with the data type int

Method Overloading

Just like constructors, methods can also be overloaded.

int add(int x, int y) {}

double add(double x, double y) {}  // Overloading because parameter data types are different
  • Overloading → The data type, order of parameters, and number of parameters must be different for methods with the same name.

Method Naming

  • Getter → retrieves some data
  • Setter → modifies some data or updates a DB

Example:

getName()  // gets the name of an object
setName()  // sets the name of an object

Passing Arrays as Parameters

There are two ways to pass arrays as parameters to a method:

  1. Traditional Array Passing:
int sum(int[] arr) {
    int ret = 0;
    for (int i : arr) {
        ret += i;
    }
    return ret;
}
  1. Using Varargs:
int sum(int ... arr) {
    int ret = 0;
    for (int i : arr) {
        ret += i;
    }
    return ret;
}

Call by Value vs Call by Reference

  • Call by Value: Passing a copy of the variable's value to the method.
  • Call by Reference: Passing the variable itself, meaning the variable can be altered inside the method.

Note: Use a deep copy buffer to prevent changes to the original variable in call by reference.


Methods with Return Values

The returned value must match the method’s declared return type.

Example:

String add(String a, String b) {
    return a + b;  // Returns a concatenated string
}

Alternatively, the return value should be convertible to the function’s return type:

int add(byte a, byte b) {
    return a + b;  // When bytes undergo arithmetic operations, they are automatically converted to int
}

Void Functions

  • Void methods do not return any values.
  • They can have a return statement only to exit early—for instance, in recursive functions to prevent infinite loops.

It is important to declare the same method with different parameters to handle various situations flexibly.

  • Overloading applies only to methods.
  • Parameters must differ in data types, order, or number, so the program can distinguish them.
profile
하나씩 차근차근

0개의 댓글