[JAVA] 6. 메서드(함수)

최재원's avatar
Feb 05, 2025
[JAVA] 6. 메서드(함수)

1. 함수의 종류

notion image
public class Mem01 { // 1. 기본 메서드 (함수) static void f() { System.out.println("기본함수 f()"); } // 2. 인수가 있는 메서드 (함수) // 역함수 = 어떤 수라도 1로 바꾸는 함수 x*1/x static void g(int x) { System.out.println("인수가 있는 함수 g(x) : " + x / x); } // 3. 인수가 여러개인 메서드 (함수) static void h(int x, int y) { System.out.println("인수가 여러개인 함수 h(x,y) : " + (x + y)); } // 4. 리턴이 있는 메서드 (함수) static int mod(int x, int y) { return x % y; } public static void main(String[] args) { f(); // 같은 클래스 안에 있는 함수는 클래스 이름 생략 가능 g(99); h(5, 4); int n = mod(10, 3); System.out.println("리턴이 있는 메서드 mod(x,y)의 결과: " + n); } }
notion image

2. 계산기 함수

public class Cal01 { static int add(int a, int b) { return a + b; } static int sub(int a, int b) { return a - b; } static int mul(int a, int b) { return a * b; } static int div(int a, int b) { return a / b; } public static void main(String[] args) { // 문제 : 5+4 -> 결과*2 -> 결과/3 -> 결과-5 -> 결과출력 // 1. 더하고 결과 받기 int r = add(5, 4); // 2. 곱하고 결과 받기 r = mul(r, 2); // 3. 나누고 결과 받기 r = div(r, 3); // 4. 빼고 결과 받기 r = sub(r, 5); System.out.println(r); } }
notion image
 
Share article

jjack1