Java Methods

2SEONGA·2025년 1월 21일
0

Java

목록 보기
5/13
post-thumbnail

Method

Method(메서드)

  • 호출될 때만 실행되는 코드 블록
  • 특정 작업을 수행하는 역할 a.k.a. Function(함수)
  • Parameter(매개변수)를 메서드에 전달 가능

메서드를 사용하는 이유?

코드를 재사용하기 위해서

Method 생성

  • 클래스 내에서 이름 뒤 ()를 붙여서 선언
public class Main {
  static void myMethod() {
    System.out.println("선언된 메서드를 호출하면 출력");
  }

  public static void main(String[] args) {
    myMethod();
  }
}

// 선언된 메서드를 호출하면 출력

Method 호출

  • 이름 뒤 ();를 붙여서 호출
  • 여러 번 호출 가능
public class Main {
  static void myMethod() {
    System.out.println("선언된 메서드를 호출하면 출력");
  }

  public static void main(String[] args) {
    myMethod();
    myMethod();
    myMethod();
  }
}

// 선언된 메서드를 호출하면 출력
// 선언된 메서드를 호출하면 출력
// 선언된 메서드를 호출하면 출력

Method Parameter

Parameters and Arguments(매개변수와 인수)

  • 매개변수는 메서드 내부에서 변수로 작동
  • 매개변수는 메서드 이름 뒤에 괄호 안에 지정, 쉼표로 구분
public class Main {
  static void myMethod(String fname) {
    System.out.println(fname + " Lee");
  }

  public static void main(String[] args) {
    myMethod("Seonga");
    myMethod("Jeonga");
    myMethod("Cheonga");
  }
}

// Seonga Lee
// Jeonga Lee
// Cheonga Lee

Multiple Parameters(다중매개변수)

  • 원하는 만큼 매개변수 사용 가능
public class Main {
  static void myMethod(String fname, int age) {
    System.out.println(fname + " is " + age);
  }

  public static void main(String[] args) {
    myMethod("Seonga", 25);
    myMethod("Jeonga", 24);
    myMethod("Cheonga", 23);
  }
}

// Seonga is 25
// Jeonga is 24
// Cheonga is 23

A Method with If...Else(If else 문을 사용한 메서드)

public class Main {

  // Create a checkAge() method with an integer variable called age
  static void checkAge(int age) {

    // If age is less than 18, print "access denied"
    if (age < 18) {
      System.out.println("Access denied - You are not old enough!");

    // If age is greater than, or equal to, 18, print "access granted"
    } else {
      System.out.println("Access granted - You are old enough!");
    }

  }

  public static void main(String[] args) {
    checkAge(20); // Call the checkAge method and pass along an age of 20
  }
}

// Outputs "Access granted - You are old enough!"

Return

Return Values(반환 값)

  • 이전까지는 메서드가 값을 반환하지 않도록 void 를 사용
  • 만약 메서드가 값을 반환하길 원한다면,
    기본 데이터 유형(int, char 등)과 메서드 내부에 return을 사용
public class Main {
  static int myMethod(int x, int y) {
    return x + y;
  }

  public static void main(String[] args) {
    System.out.println(myMethod(5, 3));
  }
}
// 8
  • 읽고 유지 관리하기 쉽기 때문에 결과를 변수에 저장하는 것을 권장
public class Main {
  static int myMethod(int x, int y) {
    return x + y;
  }

  public static void main(String[] args) {
    int z = myMethod(5, 3);
    System.out.println(z);
  }
}
// 8

Method Overloading

Method Overloading(메서드 오버로딩)

  • 메서드 오버로딩을 사용하면 여러 메서드가 서로 다른 매개변수를 가지면서도 동일한 이름 사용 가능
static int plusMethod(int x, int y) {
  return x + y;
}

static double plusMethod(double x, double y) {
  return x + y;
}

public static void main(String[] args) {
  int myNum1 = plusMethod(8, 5);
  double myNum2 = plusMethod(4.3, 6.26);
  System.out.println("int: " + myNum1);
  System.out.println("double: " + myNum2);
}
// int:13
// double:10.56

Scope (범위)

  • 자바에서 변수는 생성된 지역 내에서만 접근 가능

Method Scope

  • 메서드 내부에 직접 선언된 변수는 선언된 코드 줄 다음에 있는 메서드 내부 어디에서나 사용 가능
public class Main {
  public static void main(String[] args) {

    // Code here CANNOT use x

    int x = 100;

    // Code here can use x
    System.out.println(x);
  } 
}
// 100

Block Scope

  • 코드 블록은 중괄호 사이에 있는 모든 코드를 의미 {}
  • 코드 블록 내부에 선언된 변수는 변수가 선언된 줄 뒤에 오는 중괄호 사이의 코드에서만 액세스 가능
public class Main {
  public static void main(String[] args) {

    // Code here CANNOT use x

    { // This is a block

      // Code here CANNOT use x

      int x = 100;

      // Code here CAN use x
      System.out.println(x);

    } // The block ends here

  // Code here CANNOT use x

  }
}
// 100

Recursion (재귀)

  • 자기 자신을 호출하는 함수 자체를 만드는 기술

Recursion Example

  • 재귀를 숫자 범위를 더하는 데 사용하여, 두 숫자를 더하는 간단한 작업으로 변환시켜 10까지의 모든 숫자 합산
public class Main {
  public static void main(String[] args) {
    int result = sum(10);
    System.out.println(result);
  } } } }
  public static int sum(int k) {
    if (k > 0) {
      return k + sum(k - 1);
    } else {
      return 0;
// 55

Halting Condition(정지 조건)

  • 모든 재귀 함수는 중지 조건이 있어야 하며,
    이는 함수가 자기 자신을 호출하는 것을 멈추는 조건

    • 앞의 예시에서 중지 조건은 매개변수 k가 0보다 작거나 같아지는 경우
  • 무한 재귀는 함수가 자기 자신을 호출하는 것을 멈추지 않는 경우

  • 재귀를 사용하여 5에서 10까지의 모든 숫자 합산

    • 이 재귀 함수의 중단 조건은 end가 start 보다 크지 않을 때
public class Main {
  public static void main(String[] args) {
    int result = sum(5, 10);
    System.out.println(result);
  }
  public static int sum(int start, int end) {
    if (end > start) {
      return end + sum(start, end - 1);
    } else {
      return end;
    }
  }
}

출처 : W3Schools Online Web Tutorials


profile
(와.. 정말 Chill하다..)

0개의 댓글