댄스댄스 2012. 4. 19. 14:49

 

 

1. 배열 Array

 

- 같은 자료형들의 묶음, 1차원 배열과 다차원배열, 기본자료형 배열과 참조형 배열

- 배열의 활용 : 배열의 각 저장공간에 값을 저장하고 읽어올 때는 배열 참조변수와 인덱스를 이용

- index : 배열의 각 저장공간에 자동적으로 주어지는 일련번호. 0부터 시작해서 1씩 증가하는 연속적 정수

- 배열의 초기화 : 배열은 생성과 동시에 자신의 타입에 해당하는 기본값으로 초기화 된다.

 

* 배열선언

① 자료형[] 변수이름 ⇒ 추천

② 자료형 변수이름[]

 

* 배열생성

① int[] score;

    score=new int[5];

② int[] score=new int[5];

 

* 배열 초기화

① int[] score=new int[3];

    score[0]=11;

    score[1]=12;

    score[2]=13;

② int[] score={11,12,13};

 

2. 참조형 배열

- 참조변수들의 묶음

- 형식) String[] arr={“서울”,“제주”,“대전”};

 

 

파일명:ArrayTest1.java

public class ArrayTest1{
   public static void main(String[] args){
/*
배열 Array 이란?
자료형이 동일한 변수의 묶음.
변수를 쪼개서 사용
의미가 동일한 변수라면 배열을 이용하면 좀 더 편리하다.
배열을 구성하는 요소의 순서(index)는 0부터 시작하고
다음 요소의 순서는 1씩 증가된다.

 

* 배열의 선언 및 생성
① 자료형[] 변수이름 ⇒ 추천
② 자료형 변수이름[]
③ int[] score=new int[5];

 

int[] score //배열이 시작되는 시작주소를 score변수가 가르키고 있다
new int[5] //score변수가 가르키고 있는 주소에서 부터 20바이트를
                메모리 할당한다.

*/
       int[] score=new int[5]; //score배열 객체 생성
       score[0]=10; //요소값
       score[1]=20;
       score[2]=30;
       score[3]=40;
       score[4]=50;
      //int[] score={10,20,30,40,50};

      System.out.println("score배열의 갯수="+score.length);

      System.out.println("score[0]="+score[0]);
      System.out.println("score[1]="+score[1]);
      System.out.println("score[2]="+score[2]);
      System.out.println("score[3]="+score[3]);
      System.out.println("score[4]="+score[4]);

 

   int idx;
   for(idx=0; idx<score.length; idx++){
         System.out.println("score[" + idx + "]=" + score[idx]);
   }

 

   String[] str={"서울", "제주", "대전"};
   /*
   String[] str=new String[3];
   str[0]="서울"
   str[1]="제주"
   str[2]="대전"
   */
   for(idx=0; idx<str.length; idx++){
         System.out.println("str[" + idx + "]=" + str[idx]);
   }

   }