Java

Java) 함수 이해와 활용 : 매개변수 전달 방식과 리턴 값 처리

pogun 2025. 1. 1. 10:32

function : 함수

목적 : 코드 간략화 및 동일한 처리 코드를 집약적으로 작성

mothod : Class 안에 소속되어 있는 함수

 

기본형 : int, double, boolean 등 8가지 타입

참조형 : 그 외 사용자 정의 타입(클래스, 배열 등)

 

형식 :

    자료형  함수명(자료형 (가상)인수, 자료형 (가상)인수, 자료형 (가상)인수){

         처리(함수 내부)

         

          return 값;

   } 

잴 앞 자료형 : return Value

함수명(???) : ???를 매개변수, 인자, 인수, parameter

: 함수명 안에 파라미터는 없을 수도 있다.

: 리턴값도 필수 x


1. 입력값이 없고 리턴값도 없는 경우

public static void main(String[] args) {
    function(); // main에서 호출한다는 의미
}

static void function(){  
    System.out.println("function() 함수 처리");
}

: main에서 입력값이 없고 function에 리턴값이 없다.

: function(); 함수명은 main에서 호출하여 출력

2. 입력값이 있고 리턴값이 없는 경우

public static void main(String[] args) {
    int number = 5;
    functionOne(number); // 5 = argument (넘겨주는 실제의 값)
}

static void functionOne(int n){    // n <- parameter, 인수, 인자, 매개변수
    System.out.println("functionOne(n) " + n);
}

: 리턴값이 없을 경우 void를 쓴다.

3. 입력값이 있고 리턴값도 있는 경우

public static void main(String[] args) {
    char c = 'A';
    int re = functionTwo(c);
    System.out.println("re = " + re);
}

static int functionTwo(char c){
    System.out.println("functionTwo(char c) " + c);

    return 333;
}

: 위 코드를 보면 main에서 functionTwo(c)를 re에 넣은 후 출력하는 걸 알 수 있다.

: 즉 리턴값이 있으므로 void를 사용하면 안된다.

: 위 코드도 A가 넘어가고 리턴값이 333이므로 main에서 최종 출력은 333이 된다.

4. 입력값이 없고 리턴값이 있는 경우

public static void main(String[] args) {
    double dou = functionThree();
    System.out.println("dou = " + dou); // (int)dou 가능
    System.out.println(functionThree()); // 이렇게도 가능
}

static double functionThree(){
    System.out.println("functionThree()");
    double d = 123.432;
    return d;
}

: (int)dou를 하면 소수점 제외하고 123이 출력

영대문자를 넘겨주면 영소문자로 돌려주는 함수

public static void main(String[] args) {
    char e = 'A';
    char rc = functionEng(e);
    System.out.println("rc : " + rc)
}

static char functionEng(char c){
    int num = (int)c; // c는 A, num은 65
    System.out.println(num);

    num = num + 32;
    char rc = (char)num;
    System.out.println(num);

    return rc;
}

: 아스키 코드 활용 문제

: 여기서도 보면 re에 함수를 삽입하기 때문에 리턴값이 있다.(void를 사용하지 않는다.)

: A를 넘김 -> A의 아스키코드 65를 num에 삽입 -> 65에 32를 더하면 소문자 a 아스키 코드

-> a 아스키 코드를 다시 문자로 변환 후 리턴시킴 -> 출력

**main에 있는 변수명과 일치할 필요가 없다. 서로 독립된 블록**

**main에서 char e에 변수를 담았는데 여기서 functionEng(char c) <- 여기에 e를 안씀. 저걸로 연결하는 게 아니다.**

value(값)의 할당 : 기본형

public static void main(String[] args) {
    int n1 = 123;
    functionFour(n1); // 이 부분에서 함수명으로 값을 넘겨줌
    System.out.println("n1 : " + n1);
}

static void functionFour(int n){
    System.out.println("functionFour(int n)" + n);
    n = 234;
    System.out.println("n : " + n);
}

: main n1은 123, n은 234

: n1자체를 넘겨주는 것이 아닌 123을 넘겨주기 때문이다.

: 함수에서 처리를 해도 main에는 반영이 안된다.

address(주소)의 할당 : 참조형

public static void main(String[] args) {
    int arr[] = new int[1];
    arr[0] = 123;
    functionFive(arr);
    System.out.println("arr[0] : " + arr[0]);
}

static void functionFive(int ar[]){
    System.out.println("functionFive(int ar[])" + ar[0]);
    ar[0] = 234;
    System.out.println("함수내부 ar[0] : " + ar[0]);
}

: 123이 넘어가는 것이 아니라 배열 자체를 넘겨준다.

: 즉 main에서도 234f로 바뀐다.

: 리턴값을 지정하지 않는 void에서도 이렇게 가능

**기본형은 main의 복사본을 가지고 밑에서 처리하는 느낌**

**참조형은 main의 원본을 가지고 밑에서 처리하는 느낌**

배열을 두배로 연산 후 리턴을 받아서 출력하시오.

1. 값을 넘겨주고 리턴 받는 방법

public static void main(String[] args) {
    int array[] = {1, 2, 3, 4, 5};
    array = functionSix(array);
    System.out.println(Arrays.toString(array));
}

static int[] functionSix(int arr[]){
    System.out.println("functionSix(int arr[])" + arr[0]);
    for(int i = 0; i < arr.length; i++){
        arr[i] = arr[i] * 2;
    }
    return arr;
}

: 위 코드를 보면 array에 함수 리턴값을 받아오기 때문에 int[ ]형 사용

: 입력값이 배열이기 때문에 함수에서도 배열로 선언

 

2. 리턴값이 없는데 값을 받는 방법

public static void main(String[] args) {
    int array[] = {1, 2, 3, 4, 5};
    functionSeven(array);
    System.out.println(Arrays.toString(array));
}

static void functionSeven(int arr[]){
    for(int i = 0; i < arr.length; i++){
        arr[i] = arr[i] * 2;
    }
}

: 위 코드는 값을 받아오지 않는다.(즉, void 사용)

: 입력값이 배열이기 때문에 함수에서도 배열로 선언