어려울 거 같아서 미뤄뒀던 프로그래밍 공부 이번에 숨 딱 참고 Java 다이브 💦
프로그램의 함수를 메서드(Method)라고 해요. 특정 기능(=연산)을 그룹화 해서 재사용하기 위한 단위에요.
public static void 메서드이름(){
... 수행할 연산식...
}
정의된 메서드는 다른 메서드를 구성하는 {...} 안에서 다음의 형식으로 사용될 수 있고 이를 메서드를 호출한다고 해요.
메서드이름();
public class Main01 {
public static void plus( ) {
}
public static void main(String[] args) {
plus(); // plus라는 메서드를 호출
}
}
public static void 메서드이름( 변수형 변수이름 ) { ... }
public static void plus( int x ) {}
public static void name( String name ) {}
public static void 메서드이름( 변수형 변수이름, 변수형 변수이름, ...){...}
public static void plus( int x, int y ) {}
public static void name( String name, String gender ) {}
public static void 메서드이름( 변수형 변수이름, 변수형 변수이름 ){
...
}
메서드이름(값1, 값2);
public static 리턴형(데이터타입) 메서드이름( 변수형 파라미터1, 변수형 파라미터n..){
...
return 리턴값;
}
public class Main01 {
public static void main(String[] args) {
// 메서드의 리턴값을 변수에 저장할 수 있다.
int a = plus(10, 5);
System.out.println(a);
System.out.println(f1(30));
}
public static int plus(int x, int y) {
return x + y;
}
public static int f1( int x) {
int y = x + 1;
return y;
}
}
메서드 또한 서로 호출하는 것이 가능해요. 호출된 메서드가 값을 리턴하는 경우, 리턴받은 값을 다른 연산에 사용할 수 있어요.
public class Main02 {
public static void main(String[] args) {
System.out.println(f2(100));
}
public static int f1( int x ) {
return x + 1;
}
public static int f2( int x ) {
//메서드 안에서 다른 메서드 호출이 가능하다.
return f1(x) + 1;
}
}
/*
출력결과)
102
*/
다음 다이브에서 또 만나요 🌊
출처
https://media.giphy.com/media/l2Je1bFuOpkNpyqYM/giphy.gif
https://media.giphy.com/media/Jbb3KS22397YQ/giphy.gif