변수의 종류
1. 클래스 변수
- 선언 : 인스턴스 변수앞에 static을 붙인다
- 사용형식 : 클래스이름.클래스변수
- 클래스 변수는 모든 인스턴스가 공통된 저장공간을 가진다. (=공통변수)
- 클래스 변수는 인스턴스를 생성하지 않고 언제든 사용할 수 있다.
2. 인스턴스 변수
- 클래스의 인스턴스를 생성할 때 만들어진다.
- 사용을 위해서는 인스턴스를 먼저 생성해야 한다.
- 인스턴스는 독립적인 저장공간을 가지므로 서로 다른값을 가질 수 있다.
3. 지역변수
- 메서드 내에 선언되어 메서드 내에서만 사용 가능하다.
- 메서드가 종료되면 소멸하여 사용할 수 없다.
- ex) for문에 사용된 지역변수는 for문 내에서만 사용가능
1 2 3 4 5 6 7 8 9 10 | class Variables { int iv; // 인스턴스 변수 static int cv; // 클래스 변수 void method() { int iv=0; // 지역변수 } } | cs |
메서드
- 하나의 메서드는 한 가지 기능만 수행하도록 하는것이 좋다.
- 반복적으로 수행되는 것은 하나의 메서드로 정의하면 좋다.
- 관련된 여려 문장은 메서드로 만들어 놓는 것이 좋다.
<메서드 작성방법>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // 반환값이 있는경우 int add(int a int b) // 메서드 선언부 { /* {} 블록사이 : 메서드의 구현부 */ int result = a+b; return result; // 반환값 } // 반환값이 없는 경우 void 사용 void method() { int iv=0; // 지역변수 } | cs |
<return문>
메서드가 정상 종료되는 경우는 두 가지가 있다.
return문은 현재 실행중인 메서드를 종료학도 호출한 메서드로 되돌아가게 한다.
1 2 3 4 5 6 7 8 | 1. 반환값이 없는 경우 – return 문만 써주면 된다. return; 2. 반환값이 있는 경우 – return 문 뒤에 반환값을 지정해 주어야 한다. return 반환값; | cs |
반환값이 있는 경우 메서드의 타입과 반환타입이 일치해야 한다.
1 2 3 4 5 | int add(int a int b) // 메서드 선언부 - int 타입 { int result = a+b; return result; // 반환값 - int } | cs |
※ 반환값이 있는 메서드에서는 어떤 경우라도 return문에 의해 결과가 반환되어야 한다.
[예제 1]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class ReturnTest { public static void main (String[] args) { ReturnTest r = new ReturnTest(); int result = r.add(3,5); System.out.println(result); int[] result2 = {0}; r.add(3,5,result2); System.out.println(result2[0]); } int add(int a, int b) { return a+b; } void add(int a, int b, int[] result) { result[0] = a+b; } } | cs |
메서드 호출
<메서드의 호출 방법>
1 2 3 4 5 6 7 8 9 10 | MyMethod m = new MyMethod(); // 먼저 인스턴스를 생성한다. int value = m.add(1, 2); // 메서드를 호출한다. // 참조변수명.메서드명 int add(int a, int b) { int r = a+b; return r; } | cs |
[예제 2]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | public class MyMathTest { public static void main (String[] args) { MyMath mm = new MyMath(); long result1 = mm.add(5L, 3L); long result2 = mm.subtract(5L, 3L); long result3 = mm.multiply(5L, 3L); double result4 = mm.divide(5L, 3L); System.out.println("mm.add(5L, 3L) = "+result1); System.out.println("mm.subtract(5L, 3L) = "+result2); System.out.println("mm.multiply(5L, 3L) = "+result3); System.out.println("mm.divide(5L, 3L) = "+result4); } } class MyMath { long add(long a, long b) { long result = a+b; return result; } long subtract(long a, long b) { return a-b; } long multiply(long a, long b) { return a*b; } double divide(double a, double b) { return a/b; } } | cs |
JVM의 메모리 구조
1. 메서드영역(method area)
프로그램 실행 중 어떤 클래스가 사용되면, JVM은 해당 클래스의 클래스파일을 읽어서 분석하여 클래스에 대한 정보를 이곳에 저장한다. 이 때 클래스의 클래스 변수도 이 영역에 함께 생성된다.
2. 힙(heap)
인스턴스가 생성되는 공간. 인스턴스 변수들이 생성되는 공간이다.
3. 호출스택(call stack)
호출스택은 메서드의 작업에 필요한 메모리 공간을 제공한다. 메서드가 호출되면 호출스택에 호출된 메서드를 위한 메모리가 할당되고, 이 메모리는 메서드가 작업을 수행하는 동안 지역변수 들과 연산의 중간결과를 저장하는데 사용된다. 그리고 메서드가 작업을 마치면 할당된 메모리공간은 반환되어 비워진다.
[예제 3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // Call Stack 테스트 public class CallstackTest { public static void main (String[] args) { firstMethod(); } static void firstMethod(){ secondMethod(); } static void secondMethod(){ System.out.println("secondMethod() 호출"); } } | cs |
[예제 4]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | // Call Stack 테스트2 public class CallstackTest2 { public static void main (String[] args) { System.out.println(" main 실행 "); firstMethod(); System.out.println(" main 끝 "); } static void firstMethod(){ System.out.println(" first 실행 "); secondMethod(); System.out.println(" first 끝 "); } static void secondMethod(){ System.out.println(" second 실행 "); System.out.println(" second 끝 "); } } | cs |
[실행결과]
기본형과 참조형 매개변수
- 기본형 매개변수: 변수의 값을 읽기만 할 수 있다. 기본형의 값이 복사됨.
- 참조형 매개변수 : 변수의 값을 읽고 변경할 수 있다. 인스턴스의 주소가 복사됨.
[예제 5]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | // 기본형, 참조형 매개변수 테스트 public class DataTest { // 기본형 - 변수의 값 복사 // 참조형 - 인스턴트의 주소 복사 public static void main (String[] args) { Data d = new Data(); d.x = 10; System.out.println(" main() : x = "+d.x); change(d.x); System.out.println("\n After change(d.x) \n"); System.out.println(" main() : x = "+d.x); } static void change(int x) // 기본형 매개변수 { x = 1000; // 단순히 값을 재할당, change 매서드 종료시 사라짐 System.out.println(" change() : x = "+x); } } class Data { int x; } | cs |
[실행결과]
[예제 6]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | // 기본형, 참조형 매개변수 테스트 public class DataTest2 { // 기본형 - 변수의 값 복사 // 참조형 - 인스턴트의 주소 복사 public static void main (String[] args) { Data d = new Data(); d.x = 10; System.out.println(" main() : x = "+d.x); change(d); System.out.println("\n After change(d.x) \n"); System.out.println(" main() : x = "+d.x); } static void change(Data2 d) // 참조형 매개변수 { d.x = 1000; // 주소를 가지고 변수에 값을 할당 System.out.println(" change() : x = "+d.x); }} class Data { int x; } | cs |
[실행결과]
<재귀호출>
- 메서드의 내부에서 메서드 자기 자신을 다시 호출하는 것을 재귀호출이라 한다.
[예제 7]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public class RecursiveTest { public static void main (String[] args) { System.out.println("factorial(10) = " + factorial(10)); } static long factorial(int n) { long result = 0; if(n==1) result =1; else { result = n * factorial(n-1); // 자신의 메서드 다시 호출 System.out.println("n = "+n+", result = "+result); } return result; // 삼항연산자로 간략히 표현가능 // return (n==1) ? 1 : n * factorial(n-1); } } | cs |
[실행결과]
'코딩 > Java' 카테고리의 다른 글
자바 - 접근제어자 (3) | 2016.09.12 |
---|---|
객체지향 3부 - 오버로딩, 생성자 (0) | 2016.09.11 |
객체지향 1부 - 특징, 클래스와 객체 (0) | 2016.09.07 |
자바 오버로딩(Overloading) (0) | 2016.09.06 |
자바 - 이름 붙은 반복문 (0) | 2016.09.04 |