본문 바로가기

Java 기본 문법 - 참조 서적 [이것이 자바다 - 한빛미디어]/3. 참조 타입

3. Java 자바 참조 타입 - 배열

배열

같은 타입의 데이터를 연속된 공간에 나열시키고, 각 데이터에 인덱스(index)를 부여해 놓은 자료구조

 

 

배열 변수의 선언

 

두 가지 형태로 선언이 가능하다.

 

타입[ ] 변수;

타입 변수[ ];

  ex)

      int[] intArray;

      double[] doubleArray;

      String[] strArray;

  ex)

      int intArray[];

      double doubleArray[];

      String strArray[];

 

- 배열 변수도 참조 변수이기 때문에 null 값으로 초기화 할 수 있다.

 

타입[ ] 변수 = null;

 

null 값을 가진 상태에서 변수[인덱스] 값을 읽거나 저장할 때는 NullPointerrException 발생!

 

 

배열 객체 생성

배열 객체는 중괄호 { } 를 이용한 값 목록으로 생성, new 연산자를 이용하는 방법

두 가지 형태로 생성할 수 있다.

 

- 값 목록으로 배열 객체 생성

 

배열 항목에 먼저 저장될 값의 목록이 있다면 아래처럼 배열 객체를 만들 수 있다.

 

데이터타입[ ] 변수 = { 값0, 값1,  값2, . . . };

 

배열 타입의 스택, 힙 영역

ex) int[ ] numbers = { 1, 2, 3, 4, 5}

 

- 저장된 배열 항목은 아래와 같이 수정할 수 있다.

 

numbers[1] = 50;

 

public class ArrayCreateByValueListExam {
	public static void main(String[] args) {
    	int scores = { 83, 90, 87 };
        
        System.out.println("score[0] : " + scores[0]);
        System.out.println("score[1] : " + scores[1]);
        System.out.println("score[2] : " + scores[2]);
        
        int sum = 0;
        for (int i = 0; i < 3; i++) {
        	sum += scores[i];
        }
        
        System.out.println("총합 : "+ sum);
        double avg = (double) sum / 3;
        System.out.println("평균 : "+ avg);
    }
}

 

 

- 값 목록으로 배열 객체를 생성 시 주의할 점

 

배열 변수를 이미 선언한 후에 다른 실행문에서 중괄호를 사용한 배열 생성은 허용되지 않는다. 

 

  타입[ ] 변수;

  변수 = { 값0, 값1, 값2, . . . };     // 컴파일 에러!!  초기화 불가

 

배열 변수를 미리 선언한 후 값 목록들이 나중에 결정되는 상황이라면

new 연산자를 통해 값 목록을 지정해야 한다.

 

  변수 = new 타입[ ]  { 값0, 값1, 값2, . . . };

 

아래와 같이 배열 변수가 미리 선언되어야 하는 경우,  null 값으로 초기화 시킨 후,

이후에 배열 변수에 배열 객체를 참조시키면 된다.

 

  String[ ] names = null;

  names = new String[ ] { "Kephi", "batzzi", . . . };

 

메소드의 매개 값이 배열일 경우도 마찬가지!!

 

  int add (int[ ] score) { . . . }

  . . . 

  int result = add( { 95, 85, 90 } );                      // 컴파일 에러!!

  int result = add( new int[ ] { 95, 85, 90 } );     // new 사용해야 한다.

값 목록으로 배열을 생성함과 동시에 add( ) 메소드의 매개 값으로 사용할 때는

반드시 new 연산자를 사용해야 한다.

 

public class ArrayCreateByValueListExam {
	public static void main(String[] args) {
    	int[] scores;
        scores = new int[] { 83, 90, 87 };
        
        int sum1 = 0;
        for (int i = 0; i < 3; i++) {
        	sum1 += scores[i];
        }
        
        System.out.println("총합 : "+sum1);
        
        int sum2 = add( new int[] { 83, 90, 87 } );  // 리턴된 총합을 sum2에 저장
        System.out.println("총합 : "+sum2);
        System.out.println();
    }
    
    public static int add(int[] scores) {     // 총합 계산해서 리턴하는 메소드
    	int sum = 0;
        for(int i = 0; i < 3; i++) {
        	sum += scores[i];
        }
        return sum;
    }
}        

 

- new 연산자로 배열 객체 생성

 

위의 경우처럼 값의 목록을 가지고 있지 않지만, 향후 값을 저장할 배열을 미리 만들고 싶은 경우

new 연산자로 배열 객체를 생성한다.

 

타입[ ] 변수 = new 타입[길이];

길이 : 배열이 저장할 수 있는 값의 수를 지정한다.

 

이미 배열 변수가 선언된 후에도 가능하다.

 

  타입[ ] 변수 = null;

  변수 = new 타입[길이];

 

ex)

    int[ ] intArray = new int[5];

 

    자바에서는 intArray[0] ~ intArray[4] 까지 값이 저장될 수 있는 공간을 확보하고,

    배열의 생성 번지 (intArray[0])을 반환한다. 반환된 번지는 intArray 변수에 저장된다.

 

배열의 스택 / 힙 영역 저장

 

new 연산자로 배열을 처음 생성할 경우 자동으로 기본값 0 으로 초기화된다.

 

    int[] scores = new int[30];

 

    scores[0] ~ scores[29] 까지 모두 기본값 0 으로 초기화 된다.

 

 

만약 String 배열을 생성했다면, names[0] ~ names[29] 가지 모두 null로 초기화된다.

 

    String[ ] names = new String[30];

 

 

 

* 타입별 배열 초기값

 

구분

데이터 타입

초기값

기본 정수 타입

byte[ ]

0

char[ ]

'\u0000'

short[ ]

0

int[ ]

0

long[ ]

0L

기본 실수 타입

float[ ]

0.0F

double[ ]

0.0

기본 논리 타입

boolean[ ]

false

참조 타입

클래스[ ]

null

인터페이스[ ]

null

 

배열 생성 후 새로운 값을 저장하려면 대입 연산자를 사용한다.

 

변수[인덱스] = 값;

 

 

public class ArrayCreateByNewExam {
	public static void main(String[] args) {
    	int[] arr1 = new int[3];
        for(int i = 0; i < 3; i++) {
        	System.out.println("arr1["+i+"] : "+ arr1[i]);  // 모든 항목 0 출력
        }
        
        arr1[0] = 10;
        arr1[1] = 20;
        arr1[2] = 30;
        
        for(int i = 0; i < 3; i++) {
			System.out.println("arr1["+i+"] : "+ arr1[i]);  // 10, 20, 30 각각 출력
        }
        
        double[] arr2 = new double[3];
        
        for(int i = 0; i < 3; i++) {
        	System.out.println("arr2["+i+"] : "+ arr2[i]);  // 모든 항목 0.0 출력
        }
        
        arr2[0] = 0.1;
        arr2[1] = 0.2;
        arr3[2] = 0.3;
        
        for(int i = 0; i < 3; i++) {
        	System.out.println("arr2["+i+"] : "+ arr2[i]);  // 0.1, 0.2, 0.3 각각 출력
        }
        
        String[] arr3 = new String[3];
        
         for(int i = 0; i < 3; i++) {
        	System.out.println("arr3["+i+"] : "+ arr3[i]);  // 모든 항목 null 출력
        }
        
        arr3[0] = "1월";
        arr3[1] = "2월";
        arr3[2] = "3월";
        
         for(int i = 0; i < 3; i++) {
        	System.out.println("arr2["+i+"] : "+ arr2[i]);  // 1월, 2월, 3월 각각 출력
        }
    }
}