변수
작성규칙
규칙 | 예 |
첫 번째 글자는 문자 이거나 $ , _ 이어야 하고 숫자로 시작할 수 없다. (필수) | 가능: price, $price, _companyName 불가능: 1v, @price, $#value |
영어 대소문자가 구분된다. (필수) | firstname과 firstName은 다른 변수 |
첫 문자는 영어 소문자로 시작하되, 다른 단어가 붙을 경우 첫 문자를 대문자로 한다. (관례) | maxSpeed, firstName, carBodyColor |
문자 수(길이)의 제한은 없다. | |
자바 예약어를 변수명으로 사용 할 수 없다. (필수) | 아래 표 참조! |
변수의 사용
변수값 읽기
public class java {
public static void main(String[] args) {
//10을 변수 age의 초기값으로 저장
int age = 10;
//변수 age의 값을 읽고 10을 더하는 산술 연산수행
//연산의 결과값을 변수 result의 초기값으로 저장
int result = age + 10;
//변수 result 의 값을 읽고 콘솔에 출력
System.out.println(result);
}
}
변수의 사용범위
public class variable {//클래스블록
public static void main(String[] args) { //메소드블록
int apple = 1; //main 메서드 의 로컬변수
int fruit = 0; //main 메서드 의 로컬변수
//-------------------------------------------------------------------
if (apple == 1) { //if문 블록
int banana = 2; //if문 안에만 사용가능한 로컬변수(local variable) banana
fruit = banana + apple; //if문 밖의 변수 apple과 fruit를 사용
}
//-------------------------------------------------------------------
System.out.println(fruit); //출력값 3
System.out.println(apple); //출력값
// System.out.println(banana); // banana변수는 if문 안에서만 사용가능 에러 발생
}
}
'JAVA > JAVA' 카테고리의 다른 글
제네릭(Generic) 타입의 상속과 구현 (0) | 2018.06.09 |
---|---|
제네릭(Generic) 와일드카드 타입 (0) | 2018.06.09 |
제네릭(Generic) 메소드 (0) | 2018.06.08 |
제네릭(Generic)이란 ? 제네릭 타입이란? (0) | 2018.06.08 |
Thread 정리..?? (0) | 2018.06.08 |