-
[JAVA] 로컬 변수의 사용 방법JAVA 2023. 7. 10. 23:30
로컬 변수(loca variable) :메소드 안에 선언된 변수
/*변수 타입 예시*/ public class Test { public static void main(String[] args) throws Exception { int num1 = 1; //정수 long num2 = 2; //정수 byte num3 = 3; //정수 short num4 = 4; //정수 double num5 = 5.6; //실수 float num6 = (float) 7.8; //실수 char ch1 = 'A'; //문자 boolean bol = true; //참거짓 String ch2 = "String type"; //문자열 System.out.println(num1); System.out.println(num2); System.out.println(num3); System.out.println(num4); System.out.println(num5); System.out.println(num6); System.out.println(ch1); System.out.println(bol); System.out.println(ch2); } }1
2
3
4
5.6
7.8
A
true
String type/*블록 안에서 선언된 변수 잘못 사용 예시*/ public class Test { public static void main(String[] args) throws Exception { { int num = 10; //블록 안에서 변수 선언 } System.out.println(num); //블록 안에서 선언된 변수 블록 밖에서 사용 X --> 에러 } }[error] num cannot be resolved to a variable
/*블록 밖에서 선언된 변수 블록 안에서 사용 예시*/ public class Test { public static void main(String[] args) throws Exception { int num = 10; { num = 20; //블록 밖에서 선언된 변수 블록 안에서 사용하는 것은 가능 } System.out.println(num); } }20
final변수 : 값을 바꿀 수 없는 변수
/*final 변수 사용 예시*/ public class Test { public static void main(String[] args) throws Exception { final double pi = 3.14; //final 변수 선언 double radius = 2.0, circum; circum = 2*pi*radius; System.out.println(circum); } }12.56
/*final 변수 잘못된 사용 예시*/ public class Test { public static void main(String[] args) throws Exception { final double pi; //final 변수 선언 double radius = 2.0; pi = 3.14; //초기화값 대입 double circum = 2*pi*radius; System.out.println(circum); pi = 3.141592; //final 변수는 값 바꿀 수 없음 -> 에러 double area =2*pi*radius*radius; System.out.println(area); } }[error] The final local variable pi may already have been assigned
'JAVA' 카테고리의 다른 글
[JAVA] for 반복문 (0) 2023.07.11 [JAVA] while 반복문 (0) 2023.07.11 [JAVA] 조건문 (0) 2023.07.11 [JAVA] 배열 (0) 2023.07.10 [JAVA] Print출력 (0) 2023.07.10