728x90
반응형
배열의 선언
방법 1. 타입[ ] 변수
int[] intArray;
방법2. 타입 변수[ ]
int intArray[];
*참조할 객체가 없다면 null값으로 초기화 가능 <- 배열은 참조 변수이기 때문에!
배열의 생성
타입[ ] 변수 = {값1, 값2, ...};
: 선언과 값 지정을 동시에 하는 것.변수는 스택 메모리에 값은 힙 메모리에 저장된다.
예제
public static void main(String[] args){
int[] score = {80, 90, 87};
/**
* sout 3개 대체하는 방법
* for(int i = 0; i<3; i++){ sout("score[" + i+ "]" + score[i])}
*/
System.out.println("score[0] : "+score[0]);
System.out.println("score[1] : "+score[1]);
System.out.println("score[2] : "+score[2]);
int sum = 0;
for(int i = 0;i<3;i++){
sum += score[i];
}
System.out.println("total : "+sum);
double avg = (double)sum/3;
System.out.println("average : "+avg);
}
결과
※ length
->배열의 길이를 나타내주는. 큰 규모의 배열을 사용할 때 용이!
i<3 대신에 i<score.length 해줘도 된다.
728x90
반응형