Zeta Oph's Study

[Data Structure (Java)] Function (함수) 본문

프로그래밍/Java

[Data Structure (Java)] Function (함수)

Zeta Oph 2024. 3. 18. 15:25

https://crane206265.tistory.com/61

[Java - 기초 문법] 06. 반복문 : while문 & for문 & for each문

https://crane206265.tistory.com/60 [Java - 기초 문법] 05. 조건문 : if문 & switch문 https://crane206265.tistory.com/59 [Java - 기초 문법] 04. 형변환 (type conversion / type casting) https://crane206265.tistory.com/58 [Java - 기초 문법] 0

crane206265.tistory.com

학인시 끝내고 오랜만에 왔습니다.
이제 데이타구조 수업 정리를 티스토리에 해보려고 합니다. (영어/한글 내 맘대로 혼용 예정 ㅎ)
[Java - 기초 문법] 주제와 어느 정도는 이어질 것 같아요


Functions

Method TypeExplanation
instance methodfunction in class (use with particular instance of the class)
static method (function)associated with the class itself, not with a particular instance of the class
클래스 없이 스스로 사용 가능한 메서드 : 함수

 
Java에서는 같은 클래스 안에 static method를 선언하는 방식으로 함수를 사용합니다.
--> main class 안에서 선언한 static 메서드는 main 클래스 아래에서 함수와 같이(클래스 선언 없이) 사용 가능합니다.
 
ex)
User-defined functions : main()
Built-in functions : Math.random(), Math.sqrt(), Integer.parseInt(), ...
 
 
<몇몇 개념과 자바에서 대응되는 구조>

ConceptConstruction in Java
funtionstatic method
input valueargument
output valuereturn value
formulamethod body
independent variableparameter variable

 
 
How to declare the function

public static <return_type> <method_name> (<param_type> <param_name>) {
    <method_body>
    ex) local_var, return, ...;
}

 
위와 같은 형태로 함수를 선언할 수 있으며, 각각에 들어가야 하는 것은 아래와 같습니다.
<return_type> : return 할 값의 자료형 (primitive type : int, boolean, char, ...)
<method_name> : 함수의 이름
<param_type> <param_name> : 전달할 매개변수의 자료형, 이름
<method_body> : 함수의 몸체
 
* if return type : void -> return; code is not necessary
 

Def) Scope of a variable
the code that can refer to the variable by its name : 변수의 범위

 
scope of a variable in Java : the code following its declaration, in the same block (선언된 block 안에서만)
 
 
overloading
: using the same name for static method, but with different input parameters
함수의 이름이 같아도 변수 개수가 다르면 상황에 맞춘 것으로 동작합니다.

public class main() {
    public static int add(int a, int b) {	//1
    	return a+b;
    }
    
    public static int add(int a, int b, int c) {	//2
    	return a+b+c;
    }
    
    public static void main(String[] args) {
    	System.out.println(add(1, 2)); 		//1이 동작
        System.out.println(add(1, 2, 3));	//2가 동작
    }
}
TERMINAL

3
6

 
같은 이름의 함수를 여러개 선언했지만, parameter 개수에 따라 적당한 함수를 잘 찾아서 오류 없이 동작합니다.
 
 
* function : need to deal with seperated task
함수의 유용성 : 일을 분리하여 다루기 쉽다는 장점이 있습니다. (문제의 분할)