본문 바로가기

Java

함수와 메서드

함수란?

함수(function) 는 프로그래밍에서 특정 작업을 수행하는 코드의 집합으로, 입력을 받아 처리 후 결과를 반환할 수 있다. 함수는 코드의 재사용을 높이고, 프로그램의 구조를 체계적으로 관리할 수 있게 도와준다.

 

  • 하나의 기능을 수행하는 일련의 코드 묶음이다.
  • 구현된 (정의된) 함수는 호출하여 사용하고 호출된 함수는 기능이 끝나면 실행의 제어가 반환된다.
  • 함수로 구현된 하나의 기능은 여러 곳에서 동일한 방식으로 호출되어 사용될 수 있다.

함수 설계하기

함수는 이름, 파마메터(매개 변수), 반환 값, 함수 몸체(body)로 구성

public static void main(String args[] args) {

	// 함수 사용하기는 이름을 호출해서 사용할 수 있다. 
	add(5, 10);  // 함수에 사용은 모양 맞추기 이다. 
	
	int resultAdd = add(100, 200);
	// 함수는 여러번 호출이 가능, 재사용이 가능, 리턴 타입이 있다면 결과값을 받을 수 있다.

} // 메인 함수

package basic.ch06;

// 배운 다음...
// 자바의 모든 코드는 class XXX {} 블록안에 코드를 작성하기로 약속되어 있다.
public class FuncionMainTest1 {

	// 메인함수 - 코드의 시작점 void - 텅 빈 (리턴값이 없다)
	public static void main(String[] args) {

		System.out.println("여기 메인 함수를 시작합니다.");
		int result1 = add(5, 10);
		System.out.println("result : " + result1);

		// 성적합을 구한다.
		int result2 = add(90, 80);
		System.out.println("result2 : " + result2);

	}// end of main

	// 두 수를 받아서 덧셈하는 함수를 만들어 보자
	static int add(int n1, int n2) {

		int result; // 변수 -> 지역변수
		result = n1 + n2;
		return result;

	}// end of add (함수) - 함수 안에 선언하는 변수는 지역변수

}// end of class

// int a; 이렇게 사용 못함
package basic.ch06;

public class Funcion1 {

	public static void main(String[] args) {
		
		int num1;
		int num2;
		int sum;
		add(10, 10);
		
		int result3 = calcSum(7, 10);
		System.out.println("result3 : " + result3);
		
	}// end of main
	
	static int add(int n1, int n2) {
		int result;
		result = n1 + n2;
		return n1 + n2;
	}

	// 연습 문제
	// 함수 수정 -- 파라메터 정수 2개 받을 수 있도록 설계
	// s1, s2 -> 반복
	// 1 , 10 -> 55
	// 7 , 200 -> 7 + 8 + 9 ...  
	static int calcSum(int s1, int s2) {

		int sum = 0;
		int i;
		for (i = s1; i <= s2; i++) { // 횟수 10번 동작하는 녀석
			// 0 = 0 + 1
			// 1 = 1 + 2
			// 3 = 3 + 3
			sum = sum + i; // 55
		}
		return sum;
	}
	
}// end of class
package basic.ch06;

public class FunctionMainTest2 {

	public static void main(String[] args) {
		
		// 함수를 언제든지 호출해서 사용할 수 있다. 
		
		addNum(10, 10, 10);
		System.out.println(30);
		System.out.println(addNum(10, 10, 10));
		int result = addNum(10, 10, 10);
		System.out.println("result : " + result );
		System.out.println("---------------------");
		sayHello("안녕 반가워"); // 함수에 호출을 모양 맞추기이다. 
		int result2 = calcSum();
		System.out.println("result2 : " + result2);

	} // end of main
	
	// 함수 설계, 함수 사용 
	
	// 세개의 정수값을 받아서 덧셈하는 기능을 만들어 보자. 
	static int addNum(int n1, int n2, int n3) {
		int result = 0; 
		result = n1 + n2 + n2; 
		return result;
	}
	
	// 리턴 값이 없는 함수를 만들어 보자. 
	static void sayHello(String greeting) {
		System.out.println(greeting + " ^^");
	}
	
	// 매개 변수가 없는 함수를 만들어 보자.  
	static int calcSum() {
		int sum = 0; 
		int i; 
		for(i = 1; i<= 100; i++ ) { // 횟수 100 번 동작 하는 녀석 
			//   0 = 0 + 1
			//   1 = 1 + 2
			//   3 = 3 + 3
			sum = sum + i; // 5050 
		}
		return sum;
	}
	

} // end of class

함수 호출과 JVM 스택 메모리

  • 스택: 함수가 호출될 때 지역 변수들이 사용하는 메모리
  • 함수의 수행이 끝나면 자동으로 반환되는 메모리

package basic.ch06;

public class Function1 {

	public static void main(String[] args) {

		int num1;
		int num2;
		int sum;
		add(10, 10);

	} // end of main

	static int add(int n1, int n2) {
		int result;
		result = n1 + n2;
		return result;
	}

	// 연습 문제
	static int calcSum() {
		int sum = 0;
		int i;
		for (i = 1; i <= 100; i++) { // 횟수 100 번 동작 하는 녀석
			// 0 = 0 + 1
			// 1 = 1 + 2
			// 3 = 3 + 3
			sum = sum + i; // 5050
		}
		return sum;
	}
}
728x90

'Java' 카테고리의 다른 글

RunTime Data Area  (0) 2024.04.15
메소드 ( method )와 변수  (0) 2024.04.15
객체에 값 할당하기  (0) 2024.04.15
클래스와 객체  (0) 2024.04.15
OOP ( Object-Oriented Programming, OOP ) - 객체지향  (0) 2024.04.15