1. 변수

 - 기본의미 : 변하는 수

 - 질적, 양적 또는 문자등을 대표하여 문자로 나타내는 것



2. 변수의 종류

 1) 멤버 변수

  - 클래스 멤버로 선언되는 변수, 메서드 외부에 선언됨


  ① 클래스 변수

   - 변수 선언 시 static 키워드가 선언된 메서드

   - 프로그램 시작시 메모리에 개체 생성되어 프로그램 종료시까지 계속 남아있음


  ② 인스턴스 변수

  - 클래스로 선언되었지만 static 선언되지 않은 변수

  - 클래스 당 1개만 프로그램 시작 전에 생성됨

  - 해당 인스턴스가 참조되고 있다면 계속 사용 가능


 2) 지역 변수

  - 메서드 안에 선언된 변수, 해당 메서드에서만 사용 가능

  - 메서드 실행시 메모리에 생성되어 메서드 종료시 자동 삭제

  - 메서드 내 어디서든 호출 가능. 단, 선언한 다음 사용함



3. 변수 선언 문법


[modifiers] Type name;


 1) modifiers

  - 변수를 접근할 수 있는 접근자

  - 접근 권한

   : public 모든 클래스에서 접근 가능

   : protected 동일 패키지에 속하는 클래스, 하위 클래스에서만 접근 가능

   : private 클래스 내에서만 접근 가능

  - 활용 방법

   : final 변수릉 상수로 이용하는 경우 사용

   : static 클래스에 소속된 클래스 변수. 클래스 생성시 만들어짐

  - 비교표 

종류 

클래스 

하위 클래스 

동일 패키지 

모든 클래스 

private 

× 

× 

× 

(default) 

× 

 

× 

protected 

 

 

× 

public 

 

 

 


  2) Type : 변수 저장하는 데이터 타입 지정 (byte, short 등)


  3) name : 변수명




ex1)

class Example_8_5 { 


void sample1() {

int result = 10;

String str = "test1";

result++;

System.out.println("result = " + result);


}


void sample2() { 

String str = "test2";

System.out.println("str = " + str);

// System.out.println("result = " + result); 오류, result 변수 없음

}     


// 메서드의 블럭 내에서의 지역 변수 선언 예제

void sample() {

int result = 10;

{

int total = 20;

System.out.println("result = " + result);

System.out.println("total = " + total);

}

// System.out.println("total = " + total); 오류, total은 하위클래스의 지역 변수임

}


public static void main(String args[]) {

Example_8_5 obj = new Example_8_5();

obj.sample1();

obj.sample1();

obj.sample2();

obj.sample();

}

}



ex2)

class Example_8_6 {

//멤버 변수 선언 예제

String str = "Member str";

boolean flag;

int result;


//메서드 안에서 멤버 변수를 처리한다

void sample1() {

System.out.println("str = " + str);

result = 10;

System.out.println("result = " + result);

}


void sample2() {

System.out.println("result = " + result);

System.out.println("flag = " + flag);

}


public static void main(String args[]) {

Example_8_6 obj = new Example_8_6();

obj.sample1();

obj.sample2();

}



ex3)

class Example_8_7{

String str = "Member str";

int result=100;

float rate = 3.5f;


void sample() {

int result = 200; // 멤버변수로 result = 100이 있지만 지역변수 result = 200이 우선된다.

rate++; result++;

System.out.println("str = " + str);

System.out.println("result = " + result);

System.out.println("rate = " + rate);

}


public static void main(String args[]) {

Example_8_7 obj = new Example_8_7();

obj.sample();

obj.sample();

}




ps. 지역, 멤버 변수... 생각보다 헷갈림요. VB에선 같은 이름이면 오류났던거 같은데 Java는 같은 이름을 써도 되는건지...쩝



'Java > (교육)Perfect! Java2 Programming' 카테고리의 다른 글

명령행 매개변수  (0) 2015.06.20
연산자  (0) 2015.06.15
배열  (0) 2015.06.11
데이터 유형  (0) 2015.06.11
Java 프로그래밍 작성  (0) 2015.06.11