메소드 형식


  • 메소드는 클래스의 멤버 함수이다.

인자 전달 방식


기본 타입의 값이 전달되는 경우 ( call by value )

  • 인자가 건네는 값이 매개변수에 복사되어서 전달된다.

객체가 전달되는 경우

  • 객체의 레퍼런스 값이 전달된다.

배열이 전달되는 경우

  • 배열에 대한 레퍼런스 값이 전달된다.

예시


char[] 배열을 전달받아 출력하는 printCharArray() 메소드와 배열 속의 공백(' ') 문자를 '.'로 대치하는 replaceSpace() 메소드를 작성하라.



public class AraayPassingEx {
    static void replaceSpace(char a[]) {
        for(int i=0; i<a.length; i++)
            if(a[i] == ' ')
                a[i] = ',';
    }

    static void printCharArray(char a[]) {
        for(int i=0; i<a.length; i++)
            System.out.print(a[i]);
        System.out.println();
    }

    public static void main(String[] args) {
        char c[] = {'T', 'h', 'i', 's', ' ','i','s',' ','a',' ','p','e','n','c','i','l','.'};
        printCharArray(c);
        replaceSpace(c);
        printCharArray(c);
    }
}

실행결과
This is a pencil.
This,is,a,pencil.

+ Recent posts