누구도 평범한 사람은 없다

메소드에 인수 전달 본문

Program/Java Programming

메소드에 인수 전달

Hue Kim 2012. 10. 1. 05:22

1. 값에 의한 전달 (pass by value)

 

class PassByValue {

	public static void increment(int j) {

		// main의 j값 increment의 형식매개변수 j에 복사된다. 그림에서 보듯이 이름이 같은것은 아무런 의미가 없고 두개의
		// j는 독립된 별도의 공간을 차지한다.
		j++;
		System.out.println("Value of j int the increment =" + j);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		int j = 5;
		// main j의 값이 5로 설정된다.

		System.out.println("Value of j before the call = " + j);
		increment(j);
		// j를 실매개변수로 하여 icrement를 호출한다.
		System.out.println("Value of j after the call =" + j);
		// TODO Auto-generated method stub

	}

}

 

Value of j before the call = 5
Value of j int the increment =6
Value of j after the call =5

 

 

2. 참조에 의한 전달(pass by reference)

 

class PassByReference {

	int OnetoZero(int arg[]) {

		// arr이 객체이므로 참조에 의한 전달이 되고 OnetoZero도 동일한 객체 arr을 가리킨다.

		int count = 0;
		for (int i = 0; i < arg.length; i++) {
			// 배열 원소를 순선대로 찾아 1이있으면 count에 1을 증가 시키고 원소의 1을 0으로 변환.
			if (arg[i] == 1) {
				count++;
				arg[i] = 0;
			}
		}
		return count;
		// count와 제어를 main에 반환
	}

	public static void main(String[] args) {

		// main 시작

		int arr[] = { 1, 3, 4, 5, 1, 1, 7 };
		// int 배열을 생성하고 원소의 초기값을 설정한다.

		PassByReference test = new PassByReference();
		int numOnes;
		System.out.print("Value of the array : [");
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
		System.out.println("]");
		numOnes = test.OnetoZero(arr);
		// OnetoZero를 배개변수 arr로 호출
		System.out.println("Number of Ones =" + numOnes);
		System.out.print("New values of the array:[ ");
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
		System.out.println("]");
	}

}

 

Value of the array : [1 3 4 5 1 1 7 ]

Number of Ones =3

New values of the array:[ 0 3 4 5 0 0 7 ]

'Program > Java Programming' 카테고리의 다른 글

패키기 상속(Package import)  (0) 2012.10.01
자바 패키지(Java package)  (0) 2012.10.01
자바의 main 메소드 사용  (0) 2012.10.01
메소드 호출(Call)  (0) 2012.10.01
메소드(Method)  (0) 2012.09.23
Comments