Notice
Recent Posts
Recent Comments
Link
HwangHub
[Java] scope rule 본문
만약 지역 변수와 전역 변수의 이름이 동일할 경우,
예를 들어
public class Main {
public static int a = 10, b = 20;
public static void printAandB() {
System.out.println(a + " " + b);
}
public static void modify(int a, int b) {
System.out.println(a + " " + b);
printAandB();
int temp = a;
a = b;
b = temp;
}
public static void main(String[] args) {
modify(50, 60);
printAandB();
}
}
위와 같이 전역 변수에도 int a, int b가 정의되어 있는데, modify라는 함수의 파라미터(지역변수)도 int a, int b라고 선언된 경우에, modify 함수 실행 안에서 표기되는 a와 b는 지역변수의 값을 사용하게 된다.
즉, 지역 변수와 전역 변수가 같은 변수 이름을 갖는 경우 실행 시점에 가장 가까이에 있는 변수를 사용하게 됩니다.
'workspace > 아티클' 카테고리의 다른 글
[Java] Stream - 기본 & 중간 연산 메서드 (0) | 2023.07.04 |
---|---|
[Java] int 배열 정렬 (0) | 2023.07.04 |
[Java] Immutable한 문자열 (0) | 2023.07.02 |
[Java] call by value, call by reference (0) | 2023.07.02 |
[Java] 숫자 character의 아스키 코드 (0) | 2023.07.01 |
Comments