Local Variable
:A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class aren't even aware that the variable exists.
A local variable cannot be defined with "static" keyword.
:메서드의 중괄호 영역 내에 선언된 변수를 지역변수라고 한다.
지역변수의 특징
1) stack메모리에 올라가며 메서드의 호출이 끝나면 스택에서 사라진다.
메모리를 절약하기위해 필용할떄 선언하고 용도가 끝나면 사라지도록 설계한 변수이다.
2) 지역에서만 사용가능하다. 즉 다른 메서드에 동일한 이름의 변수가 있어도 서로 다른 변수이다.
3) 매개변수도 지역변수이다.
!! 만약 여러개의 메서드에서 하나의 변수를 접근하고 싶다면 클래스 영역에 선언해야만한다.
!! 클래스에 선언한 변수는 모든 메서드에서 접근가능하다.
public class LocalVariable {
//ClassVariable
public static Random rd = new Random();
public static void method0() {
int num=0; //LocalVariable, num of method1
num = rd.nextInt(100);
System.out.println("method0: "+num);
}
public static void method1() {
int num=0; //LocalVariable, num of method1
num = rd.nextInt(100);
System.out.println("method1: "+num);
}
public static void main(String[] args) {
int num=0;//num of Main method
method0();
System.out.println("num:"+num);
method1();
System.out.println("num:"+num);
}
}
'java' 카테고리의 다른 글
Java/Local Variable and Static Variable/ 지역변수와 스태틱변수의 비교 (0) | 2020.01.28 |
---|---|
Java/Static variable/스태틱변수, 클래스변수 (0) | 2020.01.28 |
Java/Swap values and arrays (0) | 2020.01.27 |
Java/return문; (0) | 2020.01.27 |
Java/Def of Method2/메소드정의2 (0) | 2020.01.27 |