본문 바로가기
Framwork/Java기초

Chapter 6. 메소드

by 김엉배 2022. 10. 26.
728x90
반응형


목차

1.  메소드 이해하기
2. 메소드 정의와 호출
3. 메소드에 배열을 넘기거나 반환하는 경우
4. 가변 인수
5. 메소드 오버 로딩(method overloading)

 

1. 메소드 이해하기 

   - 메소드는 입력받아서 어떤 일을 처리한 후에 결과를 반환한다.

반환 자료형 메소드명(매개변수)
{
     // 메소드 호출시에 수행되는 코드
}
  • 반환 자료형: 메소드가 반환할 값의 자료형을 적어 준다.
  • 반환할 값이 없는 경우에는 void라고 적어 준다.
  • 매개변수: 메소드 값을 입력하는 변수

 

2.  메소드 정의와 호출

     - 메소드를 만들어 놓는 것을 메소드 정의라고 한다. 

       매개변수와 반환값의 유무에 따라 다음과 같이 네 가지 경우로 볼 수 있다.

 

  • 매개변수와 반환값이 모두 없는 경우(입력과 출력이 모두 없음)
public class Code_81 {
	public static void show( )
	{
		System.out.println("I am show method");
	}
	
	public static void main(String[] args)
	{
		System.out.println("before show call");
		show( );
		System.out.println("after show call");
	}
}
//결과값
before show call
I am show method
after show call

- show() 메소드는 반환값이 없다.(return 구문이 없다.) 이 경우 void 키워드를 사용해야 한다.

- public은 접근 제어자라고 하고, static 이 붙은 메소드를 '정적 메소드' 라고 하고, main 메소드에도 항상 static이 붙는다.

  • main 메소드 앞에는 반드시 static을 붙인다.
  • static 메소드는 static 메소드만 호출할 수 있다.
public class Code_82 {
	public static void greeting1( )
	{
		System.out.println("Good morning");
	}
	
	public static void greeting2( )
	{
		System.out.println("Good afternoon");
	}
	
	public static void greeting3( )
	{
		System.out.println("Good evening");
	}
	
	public static void main(String[] args)
	{
		System.out.println("In the morning...");
		greeting1( );
		System.out.println("In the afternoon...");
		greeting2( );
		System.out.println("In the evening...");
		greeting3( );
		
		int a = 100;
		int b = 200;
	   System.out.println(a == b);
	}
}
//결과값
In the morning...
Good morning
In the afternoon...
Good afternoon
In the evening...
Good evening
false

 

  • 매개변수는 있고 반환값이 없는 경우(입력이 있고 출력은 없음)
public class Code_83 {
	public static void findPower(int x, int y)
	{
		int result = 1;
		for (int a = 1; a <= y; a++)
			result *= x;
		System.out.println(x +"의" + y + "제곱 : " + result);
	}
	
	public static void main(String[] args)
	{
		int a = 2, b = 10;
		findPower(a,b);
	}
}
//결과값
2의10제곱 : 1024

 

  • 매개변수는 없고 반환값이 있는 경우(입력은 없고 출력은 있음)
public class Code_84 {
	public static int doSomething( )
	{
		int result;
		result = 10 * 100;
		return result;
	}
	
	public static void main(String[] args)
	{
		int x;
		x = doSomething( );
		System.out.println("x : " + x);
	}
}
//결과값
x : 1000

 

  • 매개변수와 반환값이 모두 있는 경우(입력과 출력이 모두 있음)
import java.util.Scanner;

public class Code_85 {
	static int add(int x, int y)
	{
		int result;
		result = x + y;
		return result;
	}
	
	public static void main(String[] args)
	{
		Scanner scin = new Scanner(System.in);
		System.out.print("Enter two integers : ");
		int a = scin.nextInt( );
		int b = scin.nextInt( );
		int c = add(a,b);
		System.out.println(a + " + " + b + " = " + c);
		scin.close( );
	}
}
//결과값
Enter two integers : 99 232
99 + 232 = 331

- add 메소드에 있는 result를 지역변수(local variable)이라 한다. 이름대로 add 메소드 지역에서만 사용하는 변수 있다.

 

  • return 문이 여러 개 있는 경우
import java.util.Scanner;

public class Code_86 {
	static boolean check(int n)
	{
		if (n % 2 == 0)
			return true;
		else
			return false;
	}
	
	public static void main(String[] args)
	{
		Scanner scin = new Scanner(System.in);
		System.out.print("Enter one number : ");
		int a = scin.nextInt( );
		if (check(a) == true)
			System.out.println(a + " is even number");
		else
			System.out.println(a + " is odd number");
		scin.close( );
	}
}
//결과값
Enter one number : 23123
23123 is odd number
--------------------------
Enter one number : 22
22 is even number

 

3. 메소드에 배열을 넘기거나 반환하는 경우

mport java.util.Arrays;

public class Code_87 {
	static void updateArray(int[] B) // 배열 표
	{
		for (int i=0; i<B.length; i++)
			B[i] += 10;
	}
	
	public static void main(String[] args)
	{
		int[] A = {3, 5, 1, 9, 8, 10};
		System.out.println(Arrays.toString(A));
		updateArray(A); // 배열을 넘길 때 이름만 
		System.out.println(Arrays.toString(A));
	}
}
//결과값
[3, 5, 1, 9, 8, 10]
[13, 15, 11, 19, 18, 20]

- 배열은 참조 변수로 기본 자료형과 달리 참조값(주소)을 넘긴다.

 

public class Code_88 {
	public static int[] makeArray(int size)
	{
		int A[] = new int[size];
		for (int i=0; i<size; i++)
			A[i] = i * i;
		return A;
	}
	
	public static void main(String[] args)
	{
		int s = 5;
		int B[] = makeArray(s);
		for (int i=0; i<B.length; i++)
			System.out.println(B[i]);
	}
}
//결과값
0
1
4
9
16

- 메소드가 배열을 반환하는 경우

 

 

 

4. 가변 인수

    - 가변 인수는 메소드를 호출할 때 넘기는 인수의 개수가 가변적인 것을 말한다. 즉, 원하는 개수만큼의 인수를 입력으로 보내는 것을 의미

public class Code_89 {
	public static void varArgTest(int ... v)
	{
		System.out.println("number of arguments : " + v.length);
		for (int i=0; i<v.length; i++)
			System.out.println(v[i]);
	}
	
	public static void main(String[] args)
	{
		varArgTest( ); 
		varArgTest(1); 
		varArgTest(3, 5); 
		varArgTest(100, 200, 300);
	}
}
//결과값
number of arguments : 0
number of arguments : 1
1
number of arguments : 2
3
5
number of arguments : 3
100
200
300

- 일반 인수와 가변 인수를 섞어서 사용할 때, 반드시 가변 인수를 맨 마지막에 적어야 한다.

 

public class Code_90 {
	public static int largerThanValue(int value, int ... v)
	{
		int sum = 0;
		for (int i=0; i<v.length; i++) {
			if (v[i] >= value)
				sum += v[i];
		}
		return sum;
	}
	
	public static void main(String[] args)
	{
		int largerSum;
		largerSum = largerThanValue(10, 5, 3, 11, 17, 2, 20, 15);
		System.out.println("sum : " + largerSum);
	}
}
//결과값
sum : 63

 - 가변 개수의 인수는 하나만 사용할 수 있다.

 

 

5. 메소드 오버로딩

    - 자바에서는 같은 클래스 내에 같은 이름의 메소드를 여러 개 가질 수 있도록 한다. 

       이름이 같은 메소드가 여러 개 있더라도 각 메소드의 매개변수 부분을 다르게 함으로써 구별될 수 있도록 한다.

public class Code_91 {
	static void overMethod( ) {
		System.out.println("No parameters.");
	}
	
	static void overMethod(int x) {
		System.out.println("One parameter : " + x);
	}
	
	static void overMethod(int x, int y) {
		System.out.println("Two integer parameters : (" + x + "," + y + ")");
	}
	
	static void overMethod(int x, double y) {
		System.out.println("One integer " + x + " and the other double " + y);
	}
	
	public static void main(String[] args) {
		overMethod( );
		overMethod(10);
		overMethod(5,7);
		overMethod(100, 25.5);
	}
}
//결과값
No parameters.
One parameter : 10
Two integer parameters : (5,7)
One integer 100 and the other double 25.5
public class Code_92 {
	public static void test(int ... v)
	{
		System.out.println("v.length : " + v.length);
		for (int i=0; i<v.length; i++)
			System.out.println(v[i]);
	}
	
	public static void test(double ... w)
	{
		System.out.println("w.length : " + w.length);
		for (int i=0; i<w.length; i++)
			System.out.println(w[i]);
	}
	
	public static void test(String y, int ... x)
	{
		System.out.println("y : " + y);
		System.out.println("x.length : " + x.length);
		for (int i=0; i<x.length; i++)
			System.out.println(x[i]);
	}
	
	public static void main(String[] args)
	{
		test(1, 2, 3, 4, 5);
		test(1.1, 2.2, 3.3);
		test("hello", 10, 20, 30);
	}
}
//결과값
v.length : 5
1
2
3
4
5
w.length : 3
1.1
2.2
3.3
y : hello
x.length : 3
10
20
30

- 가변 개수 인수도 오버 로딩 메소드에 사용 가능하다.

728x90
반응형

'Framwork > Java기초' 카테고리의 다른 글

Chapter 7. 클래스와 객체(2)  (0) 2022.11.04
Chapter 7. 클래스와 객체(1)  (0) 2022.10.30
Chapter 5. 배열과 문자열  (2) 2022.10.23
Chapter 4. 조건문과 반복문  (0) 2022.10.09
Chapter 3. 계산을 위한 연산자  (0) 2022.10.04